<template>
  <div class="app-container">
    <div>{{ editPage ? '修改' : '添加' }}政策</div>
    <el-form
      style="width: 50%; margin: 15px 0 0 15px"
      label-position="left"
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="80px"
    >
      <el-form-item label="政策标题" prop="title">
        <el-input
          placeholder="请输入"
          v-model="ruleForm.title"
          :disabled="editPage"
        ></el-input>
      </el-form-item>
      <el-form-item label="城市" prop="ids">
        <!-- <el-select
          v-model="ruleForm.level"
          placeholder="请选择"
          :disabled="editPage"
        >
          <el-option
            v-for="item in levelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select> -->
        <el-cascader
          v-model="ruleForm.ids"
          :options="levelOptions"
          :props="{ expandTrigger: 'hover' }"
          :show-all-levels="false"
          :disabled="editPage"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="归口" prop="attribute">
        <el-select
          v-model="ruleForm.attribute"
          placeholder="请选择"
          :disabled="editPage"
        >
          <el-option
            v-for="item in attributeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发布日期" required>
        <el-form-item prop="listDate">
          <el-date-picker
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            v-model="ruleForm.listDate"
            style="width: 30%"
            :disabled="editPage"
          ></el-date-picker>
        </el-form-item>
      </el-form-item>
      <el-form-item label="来源" prop="source">
        <el-input
          placeholder="请输入"
          v-model="ruleForm.source"
          :disabled="editPage"
        ></el-input>
      </el-form-item>
      <el-form-item label="正文" prop="text">
        <div id="text">
          <editor v-model="ruleForm.text" :min-height="192" />
        </div>
      </el-form-item>
      <el-form-item label="附件">
        <!-- <el-upload
          action="https://jsonplaceholder.typicode.com/posts/"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          multiple
          :limit="3"
          :on-exceed="handleExceed"
          :file-list="fileList">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload> -->
        <!-- <el-upload ref="upload" :limit="3" accept=".xlsx, .xls, .docx" :headers="upload.headers"
        :action="upload.url" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload> -->

      <el-button type="info" size="small" @click="upload.open = true">添加附件</el-button>
      
      </el-form-item>
      <el-form-item v-if="ruleForm.method!==1">
      <!-- <el-form-item v-if="!editPage"> -->
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确定</el-button
        >
        <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
      </el-form-item>
    </el-form>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls, .docx" :headers="upload.headers"
        :action="upload.url" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Editor from '@/components/Editor';
import { getToken } from "@/utils/auth";
import { addPolicy, updatePolicy, getPolicyInfo } from '@/api/policy/library';
import { getCityByLevel } from '@/api/policy/library';
export default {
  components: {
    Editor,
  },
  data() {
    return {
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "添加附件",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/minio/upload"
      },
      editPage: false,
      ruleForm: {
        title: '',
        ids: '',
        attribute: '',
        listDate: '',
        source: '',
        text: '',
      },
      // 归口选项
      attributeOptions: [
        {
          value: 'KJJ',
          label: '科技',
        },
        {
          value: 'JXJ',
          label: '经信',
        },
        {
          value: 'FGW',
          label: '发改',
        },
        {
          value: 'OTHER',
          label: '其他',
        },
      ],
      // 级别选项
      levelOptions: [
        {
          value: '1',
          label: '安徽省',
        },
        {
          value: '2',
          label: '地级市',
          children: [],
        },
        {
          value: '3',
          label: '合肥区县',
          children: [],
        },
      ],
      rules: {
        title: [{ required: true, message: '请输入政策标题', trigger: 'blur' }],
        ids: [{ required: true, message: '请选择级别', trigger: 'change' }],
        attribute: [
          { required: true, message: '请选择归口', trigger: 'change' },
        ],
        listDate: [
          {
            required: true,
            message: '请选择日期',
            trigger: 'change',
          },
        ],
        source: [{ required: true, message: '请填写来源', trigger: 'blur' }],
        text: [
          { required: true, message: '请填写富文本内容', trigger: 'blur' },
        ],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.editPage) {
            // 修改
            updatePolicy(this.ruleForm).then(({ message }) => {
              this.msgSuccess(message);
            });
          } else {
            // 添加
            addPolicy(this.ruleForm).then(({ message }) => {
              this.msgSuccess(message);
            });
          }
          // this.$router.go(-1);
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // resetForm(formName) {
    //   this.$refs[formName].resetFields();
    // }
    // 文件上传中处理
    handleFileUploadProgress (event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess (response, file, fileList) {
      this.ruleForm.text+=`<div>附件<a href="${response.data.url}">${response.data.name}</a></div>`
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.message, "导入结果", { dangerouslyUseHTMLString: true });
    },
    // 提交上传文件
    submitFileForm () {
      this.$refs.upload.submit();
    },
  },
  watch: {
    ruleForm: {
      handler: function () {
        this.$nextTick(() => {
          this.formatRichText(this.ruleForm.downloadUrl);
        });
      },
    },
    deep: true,
  },
  created() {
    let { id } = this.$route.query;
    if (id) {
      this.editPage = true;
      getPolicyInfo({ policyId: id }).then(({ data }) => {
        this.ruleForm = data;
      });
    }
    getCityByLevel({ level: 2 }).then(({ data }) => {
      this.levelOptions[1].children = data;
    });
    getCityByLevel({ level: 3 }).then(({ data }) => {
      this.levelOptions[2].children = data;
    });
  },
};
</script>
<style lang="scss" scoped>
/deep/.ql-toolbar {
  .ql-formats:last-child {
    display: none;
  }
}
</style>
