<template>
  <el-dialog v-loading="loading" v-if="dialogVisible" :visible.sync="dialogVisible" :title="title" destroy-on-close @close="clear"	>
    <el-form ref="form" :model="form" :rules="rules" label-width="180px">
      <el-form-item v-if="false" label="规程属性:" prop="CATEGORY_LIST">
        <multiple-choice :dynamic-tags.sync="form.CATEGORY_LIST" :labels="categoryList" :row-key="key.categoryKey" :row-name="key.categoryName" :limit="1" @getChooseOne="getChooseOne"/>
      </el-form-item>
      <el-form-item label="安全操作规程名称:" prop="REMARKS">
        <el-input v-model="form.REMARKS" style="width: 100%"/>
      </el-form-item>
      <el-form-item label="类型:" prop="TYPES">
        <multiple-choice :dynamic-tags.sync="form.TYPES" :labels="typeList" :row-key="key.typeKey" :row-name="key.typeName"/>
      </el-form-item>
      <el-form-item v-if="false" label="国民经济行业类型:" prop="SPECIFICATION_TYPES">
        <multiple-choice :dynamic-tags.sync="form.SPECIFICATION_TYPES" :labels="industryTypeList" :row-key="key.specificationTypeKey" :row-name="key.specificationTypeName" lazy/>
      </el-form-item>
      <el-form-item v-if="false" label="状态:" prop="STATUS">
        <el-select v-model="form.STATUS" placeholder="请选择" style="width: 100%;">
          <el-option label="停用" value="0"/>
          <el-option label="启用" value="1"/>
        </el-select>
      </el-form-item>
      <el-form-item v-if="!isEdit" label="文件:" prop="FILE">
        <upload-file :file-list.sync="form.FILE" :limit="1" :file-size="200" append-to-body accept=".pdf"/>
      </el-form-item>
      <el-form-item v-if="!isEdit" label="添加文件内容:">
        <el-button size="small" type="primary" @click="openTextEdit()">添加文件内容</el-button>
      </el-form-item>
      <el-form-item v-if="isEdit" label="添加文件内容:">
        <el-button size="small" type="primary" @click="openTextEdit({BUS_TEXT_LIBRARY_ID:form.BUS_TEXT_LIBRARY_ID},true)">查看</el-button>
        <el-button size="small" type="primary" @click="openTextEdit({BUS_TEXT_LIBRARY_ID:form.BUS_TEXT_LIBRARY_ID},false)">编辑内容</el-button>
        <el-button size="small" type="primary" @click="exportWord({BUS_TEXT_LIBRARY_ID:form.BUS_TEXT_LIBRARY_ID})">导出word</el-button>
      </el-form-item>
      <el-form-item label="标签:" prop="labels">
        <multiple-choice :dynamic-tags.sync="form.labels" :row-key="key.labelsKey" :row-name="key.labelsName" can-add/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="goBack">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
    <edit-label ref="editLabel" append-to-body/>
    <select-label ref="selectLabel" append-to-body @getResult="getChooseTage"/>
    <select-type ref="selectType" :limit="1" append-to-body @getResult="getType"/>
    <text-editing ref="textEditing" :disabled="textDisabled" append-to-body title="文本编辑器" @getResult="getText"/>
  </el-dialog>
</template>
<script>
import Pagination from '@/components/Pagination'
import waves from '@/directive/waves'
import { upload } from '@/utils/upload'
import { requestFN } from '@/utils/request'
import editLabel from '../../../Label/components/editLabel.vue'
import selectLabel from '../../../Label/components/selectLable.vue'
import selectType from '../../../util/selectType.vue'
import multipleChoice from '../../../util/multipleChoice.vue'
import UploadFile from '../../../../components/upload-file/index.vue'
import TextEditing from '../../../util/textEditing.vue'

export default {
  components: { TextEditing, Pagination, editLabel, selectLabel, selectType, multipleChoice, UploadFile },
  directives: { waves },
  props: {
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: false,
      form: {
        REMARKS: '',
        FILE: [],
        labels: [''],
        TYPE: '',
        TYPES: [''],
        SPECIFICATION_TYPES: [''],
        CATEGORY_LIST: [''],
        STATUS: '',
        ASSOCIATION: '0',
        types: [],
        specification_types: [],
        category_list: [],
        TEXT_INFO: ''
      },
      key: {
        typeKey: 'DICTIONARIES_ID',
        typeName: 'NAME',
        specificationTypeKey: 'DICTIONARIES_ID',
        specificationTypeName: 'NAME',
        categoryKey: 'DICTIONARIES_ID',
        categoryName: 'NAME',
        labelsKey: 'BUS_LABEL_FACTORY_ID',
        labelsName: 'NAME'
      },
      rules: {
        REMARKS: [{ required: true, message: '请输安全操作规程', trigger: 'change' }],
        STATUS: [{ required: true, message: '请选择状态', trigger: 'change' }],
        FILE: [{ required: true, message: '请选择文件', trigger: 'blur' }],
        TYPES: [{
          required: true,
          validator: (rules, value, callback) => {
            if (!value || value.length === 0 || value[0] === '') {
              return callback(new Error('类型必选'))
            }
            return callback()
          },
          trigger: 'blur'
        }],
        SPECIFICATION_TYPES: [{
          required: true,
          validator: (rules, value, callback) => {
            if (!value || value.length === 0 || value[0] === '') {
              return callback(new Error('操作规程行业类型必选'))
            }
            return callback()
          },
          trigger: 'blur'
        }],
        CATEGORY_LIST: [{
          required: true,
          validator: (rules, value, callback) => {
            if (!value || value.length === 0 || value[0] === '') {
              return callback(new Error('规程属性必选'))
            }
            return callback()
          },
          trigger: 'blur'
        }]
      },

      loading: false,
      e: {},
      isEdit: false,
      typeList: [],
      industryTypeList: [],
      categoryList: [],

      remoteControl: {
        keyOne: true
      },
      textDisabled: false
    }
  },
  methods: {
    init(e) {
      this.dialogVisible = true
      this.e = e ? e.e : {}
      this.isEdit = e ? e.isEdit : false
      this.getDic()
      if (e) {
        this.loading = true
        requestFN(
          '/textLibrary/goEdit',
          { BUS_TEXT_LIBRARY_ID: this.e.BUS_TEXT_LIBRARY_ID }
        ).then((data) => {
          this.loading = false
          this.form = data.data
          this.form.FILE = []
          this.form.types = []
          this.form.specification_types = []
          this.form.category_list = []

          if (!this.form.TYPES || this.form.TYPES.length === 0) this.form.TYPES = ['']
          if (!this.form.SPECIFICATION_TYPES || this.form.SPECIFICATION_TYPES.length === 0) this.form.SPECIFICATION_TYPES = ['']
          if (!this.form.CATEGORY_LIST || this.form.CATEGORY_LIST.length === 0) this.form.CATEGORY_LIST = ['']
          if (!this.form.labels || this.form.labels.length === 0) this.form.labels = ['']

          this.remoteControl.keyOne = !(this.form.CATEGORY_LIST[0].CATEGORY_ID === '8051d985a2bc406a83ea9360b64182b2')
        }).catch((e) => {
          this.$message.error(e)
          this.loading = false
        })
      } else {
        this.isEdit = false
      }
    },
    save() {
      if (this.checkForm()) {
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '上传中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          const formData = new FormData()
          if (this.form.TEXT_INFO) this.form.TEXT_INFO = this.form.TEXT_INFO.replaceAll('<img', '<img style="max-width:100%"')
          Object.keys(this.form).map(key => {
            formData.append(key, this.form[key])
          })
          if (!this.isEdit) {
            if (!this.form.FILE || this.form.FILE.length <= 0) {
              this.$message.error('请上传文件')
              loading.close()
              return
            }
          }
          for (let i = 0; i < this.form.FILE.length; i++) {
            if (this.form.FILE[i].raw) {
              formData.append('FILE', this.form.FILE[i].raw)
            }
          }
          formData.append('labels', JSON.stringify(this.form.labels))
          for (let i = 0; i < this.form.TYPES.length; i++) {
            if (this.form.TYPES[i]) {
              this.form.types.push({
                CATEGORY: 'TYPES',
                CATEGORY_ID: this.form.TYPES[i].DICTIONARIES_ID,
                CATEGORY_NAME: this.form.TYPES[i].NAME
              })
            }
          }
          formData.append('TYPES', JSON.stringify(this.form.types))
          for (let i = 0; i < this.form.SPECIFICATION_TYPES.length; i++) {
            if (this.form.SPECIFICATION_TYPES[i]) {
              this.form.specification_types.push({
                CATEGORY: 'SPECIFICATION_TYPES',
                CATEGORY_ID: this.form.SPECIFICATION_TYPES[i].DICTIONARIES_ID,
                CATEGORY_NAME: this.form.SPECIFICATION_TYPES[i].NAME
              })
            }
          }
          formData.append('SPECIFICATION_TYPES', JSON.stringify(this.form.specification_types))
          if (!this.form.category_list) this.form.category_list = []
          this.form.category_list.push({
            CATEGORY: 'CATEGORY_LIST',
            CATEGORY_ID: '31c2e389f2284ac48d54e85d56528092',
            CATEGORY_NAME: '行业专属类'
          })
          formData.append('CATEGORY_LIST', JSON.stringify(this.form.category_list))
          upload(
            '/textLibrary/init',
            formData
          ).then((data) => {
            loading.close()
            this.dialogVisible = false
            this.$emit('logical-end', { result: 'OK' })
            this.$message.success('保存成功')
          }).catch((e) => {
            loading.close()
            console.log(e)
          })
          this.clear()
        } else {
          return false
        }
      })
    },
    checkForm() {
      if (this.form.labels.length > 15) {
        this.$message.error('关联标签数不能超过15个')
        return true
      }
    },
    goBack() {
      this.dialogVisible = false
      this.clear()
      this.$emit('goBack', this.e)
    },
    getChooseTage(e) {
      if (e.TYPE === '0') {
        const list = e.e
        for (const listKey in list) {
          const index = this.form.labels.findIndex(item => {
            item.BUS_LABEL_FACTORY_ID === list[listKey].BUS_LABEL_FACTORY_ID
          })
          if (index < 0) {
            const label = JSON.parse(JSON.stringify(list[listKey]))
            label.label = label.NAME
            label.value = JSON.stringify(list[listKey])
            const index = this.form.labels.findIndex(item => item.value === label.value)
            if (index < 0) {
              this.form.labels.push(label)
            }
          }
        }
      } else {
        if (e.e.length > 1) {
          this.$message.error('只能选择一个类型')
          return
        }
        this.form.TYPE_NAME = e.e[0].NAME
        this.form.TYPE = e.e[0].BUS_LABEL_FACTORY_ID
        this.$forceUpdate()
      }
    },
    getType(e) {
      this.form.TYPE = e.info[0].DICTIONARIES_ID
      this.form.TYPE_NAME = e.info[0].NAME
    },
    clear() {
      this.dialogVisible = false
      console.log('clear')
      this.isEdit = false
      this.form = {
        REMARKS: '',
        FILE: [],
        labels: [''],
        TYPE: '',
        TYPES: [''],
        SPECIFICATION_TYPES: [''],
        STATUS: '',
        ASSOCIATION: '0',
        types: [],
        specification_types: []
      }
    },
    getDic() {
      // 安全操作规程类型
      requestFN(
        'dictionaries/getLevels', { DICTIONARIES_ID: 'ca4e4a7597f8485d8be323bd6876c40b' }
      ).then((data) => {
        this.typeList = data.list
      }).catch((e) => {
        this.loading = false
      })
      // 操作规程行业类型
      requestFN(
        'dictionaries/getLevels', { DICTIONARIES_ID: 'f2598ba72e864eadabf0ca4b664d26b9' }
      ).then((data) => {
        this.industryTypeList = data.list
      }).catch((e) => {
        this.loading = false
      })
      // 行业类别
      requestFN(
        'dictionaries/getLevels', { DICTIONARIES_ID: '99543742b79b473480617191f7ac256e' }
      ).then((data) => {
        this.categoryList = data.list
      }).catch((e) => {
        this.loading = false
      })
    },
    getChooseOne(e) {
      this.remoteControl.keyOne = !(e && e.info && e.info.DICTIONARIES_ID && e.info.DICTIONARIES_ID === '8051d985a2bc406a83ea9360b64182b2')
    },
    openTextEdit(id, textDisabled) {
      if (!id) {
        this.textDisabled = false
        this.$refs.textEditing.init({ text: this.form.TEXT_INFO })
      } else {
        this.textDisabled = textDisabled
        this.loading = true
        requestFN('textLibrary/getTextInfo', id)
          .then((data) => {
            if (data.info && data.info.TEXT_INFO && data.info.TEXT_INFO !== '') {
              this.$refs.textEditing.init({ text: data.info.TEXT_INFO })
            } else {
              if (((!this.form.TEXT_INFO) || this.form.TEXT_INFO === '') && this.textDisabled) {
                this.$message.error('此数据未维护文件内容')
              } else {
                this.$refs.textEditing.init({ text: this.form.TEXT_INFO })
              }
            }
            this.loading = false
          }).catch((e) => {
            console.log(e)
            this.loading = false
          })
      }
    },
    getText(e) {
      this.form.TEXT_INFO = e.text
    },
    exportWord(info) {
      this.loading = true
      requestFN('textLibrary/getTextInfo', info)
        .then((data) => {
          if (data.info) {
            if ((!data.info) || data.info.TEXT_INFO === '') {
              this.$message.error('没有文件导出')
            } else {
              this.$message.success('导出成功')
              window.open(config.httpurl + '/textLibrary/exportWord?BUS_TEXT_LIBRARY_ID=' + info.BUS_TEXT_LIBRARY_ID)
            }
          } else {
            this.$message.error('此数据未维护文件内容')
          }
          this.loading = false
        }).catch((e) => {
          console.log(e)
          this.loading = false
        })
    }
  }
}

</script>