<template>
  <el-dialog v-loading="loading" v-if="dialogVisible" :visible.sync="dialogVisible" :before-close="goBack" :title="title">
    <el-form ref="form" :model="form" :rules="rules" label-width="150px">
      <el-form-item label="应急预案名称:" prop="REMARKS">
        <el-input v-model="form.REMARKS" style="width: 600px"/>
      </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" :limit="1"/>
      </el-form-item>
      <el-form-item label="国民经济行业分类:" prop="CATEGORY_LIST" width="300px">
        <multiple-choice :dynamic-tags.sync="form.CATEGORY_LIST" :labels="categoryList" :row-key="key.categoryKey" :row-name="key.categoryName" lazy/>
      </el-form-item>
      <el-form-item label="预案类型:" prop="SPECIFICATION_TYPES">
        <multiple-choice :dynamic-tags.sync="form.SPECIFICATION_TYPES" :labels="industryTypeList" :row-key="key.specificationTypeKey" :row-name="key.specificationTypeName"/>
      </el-form-item>
      <el-form-item label="预案属性:" prop="ATTRIBUTE_LIST">
        <multiple-choice :dynamic-tags.sync="form.ATTRIBUTE_LIST" :labels="attributeList" :row-key="key.attributeKey" :row-name="key.attributeName"/>
      </el-form-item>
      <el-form-item 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 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-type ref="selectType" :limit="1" append-to-body @getResult="getType"/>
  </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 selectType from '../../../util/selectType.vue'
import multipleChoice from '../../../util/multipleChoice.vue'
import uploadFile from '../../../../components/uploadFile/index.vue'
import TextEditing from '../../../util/textEditing.vue'

export default {
  components: { TextEditing, Pagination, editLabel, selectType, multipleChoice, uploadFile },
  directives: { waves },
  props: {
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: false,
      form: {
        REMARKS: '',
        FILE: [],
        labels: [''],
        TYPE: '',
        TYPES: [''],
        types: [],
        SPECIFICATION_TYPES: [''],
        specification_types: [],
        CATEGORY_LIST: [''],
        category_list: [],
        STATUS: '',
        ASSOCIATION: '3',
        ATTRIBUTE_LIST: [''],
        attribute_list: []
      },
      key: {
        typeKey: 'DICTIONARIES_ID',
        typeName: 'NAME',
        specificationTypeKey: 'DICTIONARIES_ID',
        specificationTypeName: 'NAME',
        categoryKey: 'DICTIONARIES_ID',
        categoryName: 'NAME',
        labelsKey: 'BUS_LABEL_FACTORY_ID',
        labelsName: 'NAME',
        attributeKey: 'DICTIONARIES_ID',
        attributeName: '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'
        }],
        ATTRIBUTE_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: [],
      attributeList: [],
      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 = []
          this.form.attribute_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 = ['']
          if (!this.form.ATTRIBUTE_LIST || this.form.ATTRIBUTE_LIST === 0) this.form.ATTRIBUTE_LIST = ['']
        }).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()
          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))
          for (let i = 0; i < this.form.CATEGORY_LIST.length; i++) {
            if (this.form.CATEGORY_LIST[i]) {
              this.form.category_list.push({
                CATEGORY: 'CATEGORY_LIST',
                CATEGORY_ID: this.form.CATEGORY_LIST[i].DICTIONARIES_ID,
                CATEGORY_NAME: this.form.CATEGORY_LIST[i].NAME
              })
            }
          }
          formData.append('CATEGORY_LIST', JSON.stringify(this.form.category_list))
          for (let i = 0; i < this.form.ATTRIBUTE_LIST.length; i++) {
            if (this.form.ATTRIBUTE_LIST[i]) {
              this.form.attribute_list.push({
                CATEGORY: 'ATTRIBUTE_LIST',
                CATEGORY_ID: this.form.ATTRIBUTE_LIST[i].DICTIONARIES_ID,
                CATEGORY_NAME: this.form.ATTRIBUTE_LIST[i].NAME
              })
            }
          }
          formData.append('ATTRIBUTE_LIST', JSON.stringify(this.form.attribute_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.isEdit = false
      this.form = {
        REMARKS: '',
        FILE: [],
        labels: [''],
        TYPE: '',
        TYPES: [''],
        types: [],
        SPECIFICATION_TYPES: [''],
        specification_types: [],
        CATEGORY_LIST: [''],
        category_list: [],
        STATUS: '',
        ASSOCIATION: '3',
        ATTRIBUTE_LIST: [''],
        attribute_list: []
      }
    },
    getDic() {
      // 预案列别
      requestFN(
        'dictionaries/getLevels', { DICTIONARIES_ID: '6f1a24ee886f4b4885b030216b3c0e05' }
      ).then((data) => {
        this.typeList = data.list
      }).catch((e) => {
        this.loading = false
      })
      // 预案类型
      requestFN(
        'dictionaries/getLevels', { DICTIONARIES_ID: 'dc6884c3a9664b1597e61a0f75c8e709' }
      ).then((data) => {
        this.industryTypeList = data.list
      }).catch((e) => {
        this.loading = false
      })
      // 国民经济行业分类
      requestFN(
        'dictionaries/getLevels', { DICTIONARIES_ID: 'f2598ba72e864eadabf0ca4b664d26b9' }
      ).then((data) => {
        this.categoryList = data.list
      }).catch((e) => {
        this.loading = false
      })
      // 预案属性
      requestFN(
        'dictionaries/getLevels', { DICTIONARIES_ID: '56640b5df1f14b25a93b55ca4bbb8c5e' }
      ).then((data) => {
        this.attributeList = data.list
      }).catch((e) => {
        this.loading = false
      })
    }
  }
}

</script>
