<template>
  <div class="des-form">
    <el-form ref="form" :model="form" :rules="rules" :hide-required-asterisk="isDisabled" size="small" label-width="80px">
      <el-row>
        <el-col :span="16">
          <el-form-item label="字段名称" prop="fieldCnName">
            <el-input v-model="form.fieldCnName" :disabled="isDisabled" />
          </el-form-item>

          <el-form-item label="字段标识" prop="fieldName" class="inline-error-item" :inline-message="true">
            <el-input v-if="isDisabled" v-model="form.fieldName" disabled />
            <el-input v-else v-model="form.fieldName" :disabled="!isAdd" />
          </el-form-item>

          <el-form-item label="字段类型" prop="isDataType">
            <el-input v-if="isDisabled" v-model="form.isDataTypeTxt" disabled />
            <el-select v-else v-model="form.isDataType" placeholder="" :disabled="!isAdd">
              <el-option v-for="item in dataTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="字段长度" prop="isColumnLength">
            <el-input v-if="isDisabled" v-model="form.isColumnLength" type="number" placeholder="" disabled />
            <el-input v-else v-model.number="form.isColumnLength" type="number" placeholder="" :disabled="!isAdd" />
          </el-form-item>

          <el-form-item label="著录形式" prop="isInputClass">
            <el-input v-if="isDisabled" v-model="form.isInputClassTxt" disabled />
            <el-select v-else v-model="form.isInputClass" placeholder="" @change="selectInputClass">
              <el-option v-for="item in inputClassOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="对应数据" prop="dictionaryId">
            <el-input v-if="isDisabled" v-model="form.dictionaryId.dictionaryName" disabled />
            <!-- @change="selectDictionary" -->
            <div v-else class="dictionary-selected">
              <el-select v-model="form.mateData" class="dictionary-left" placeholder="" value-key="id" :disabled="form.isInputClass !== 'select' && form.isInputClass !== 'popover'" @change="changeDictType">
                <el-option v-for="item in dataOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-select v-model="form.dictionaryId.id " class="dictionary-right" placeholder="" value-key="id" :disabled="form.mateData !== 3">
                <el-option v-for="item in dictionaryData" :key="item.id" :label="item.dictionaryName" :value="item.id" />
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="显示长度" prop="editLength">
            <!-- :min="46" :max="510"  -->
            <el-input v-model="form.editLength" type="number" :disabled="isDisabled" @keyup.enter.native="changEditLength" @blur="changEditLength" />
          </el-form-item>
          <el-form-item label="默认值" prop="isDefaultValue">
            <el-input v-model="form.isDefaultValue" :disabled="isDisabled" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item class="checkbox-item">
            <span>整行显示</span>
            <el-checkbox v-model="form.isLine" name="isLine" :disabled="isDisabled" @change="changeIsLine" />
          </el-form-item>
          <el-form-item class="checkbox-item">
            <span>输入字段</span>
            <el-checkbox v-model="form.isInput" name="isInput" :disabled="isDisabled" />
          </el-form-item>
          <el-form-item class="checkbox-item">
            <span>必填字段</span>
            <el-checkbox v-model="form.isRequired" name="isRequired" :disabled="isDisabled" />
          </el-form-item>
          <el-form-item v-if="isCategory" class="checkbox-item">
            <span>自动生成</span>
            <el-checkbox v-model="form.isAutomatic" name="isAutomatic" :disabled="isDisabled" @change="changeAuto" />
          </el-form-item>
          <el-form-item class="checkbox-item">
            <span>值不重复</span>
            <el-checkbox v-model="form.isRepeat" name="isRepeat" :disabled="isDisabled" />
          </el-form-item>
          <el-form-item class="checkbox-item">
            <span>自动补零</span>
            <el-checkbox v-model="form.isFilling" name="isFilling" :disabled="isDisabled || form.isInputClass !=='number'" @change="changeSupplement" />
          </el-form-item>
          <el-form-item class="input-num" label="位数" prop="fillingDigit">
            <el-input v-if="isDisabled || !form.isFilling" v-model="form.fillingDigit" disabled />
            <!-- <el-input v-model="form.fillingDigit" type="number" :min="1" :disabled="isDisabled || !form.isSupplement" /> -->
            <el-input-number v-else v-model="form.fillingDigit" controls-position="right" :min="1" :disabled="isDisabled || !form.isFilling" />
            <span>位</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { FetchDictionaryTree } from '@/api/system/dict'
import { getNoFormatField } from '@/api/system/category/fileNoFormat'

export default {
  name: 'SettingForm',
  components: {},
  props: {
    isCategory: {
      type: Boolean,
      required: true
    },
    isDisabled: {
      type: Boolean,
      required: true
    },
    isAdd: {
      type: Boolean,
      required: true
    },
    thisFields: {
      type: Object,
      required: true
    },
    isDesFormType: {
      type: String,
      default: ''
    }
  },
  data() {
    var checkMaxLength = (rule, value, callback) => {
      if (value !== undefined && (!Number.isInteger(value) || value <= 0)) {
        callback(new Error('请输入正整数数字值'))
      } else {
        if (this.form.isDataType === 1 && value > 2000) {
          callback(new Error('字符最大长度不能超过2000位'))
        } else if (this.form.isDataType === 2 && value > 11) {
          callback(new Error('数字最大长度不能超过11位'))
        } else {
          callback()
        }
      }
    }
    var checkFieldName = (rule, value, callback) => {
      const reg = /^(([A-Za-z][A-Za-z_]*[a-zA-Z])|([A-Za-z]))$/
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('字段标识只能由字母、字符“_”组成，并且必须以字母开头和结尾'))
      }
    }
    // 显示长度限制
    var checkEditLength = (rule, value, callback) => {
      if (this.form.editLength && this.form.editLength > 578) {
        callback(new Error('显示长度最大578'))
      } else if (this.form.editLength && this.form.editLength < 46) {
        callback(new Error('显示长度最小46'))
      } else {
        callback()
      }
    }
    // 对应字典必填判断
    var checkDictionaryConfigId = (rule, value, callback) => {
      if ((this.form.isInputClass === 'select' || this.form.isInputClass === 'popover') && !this.form.dictionaryId.id && this.form.mateData === 3) {
        callback(new Error('对应字典项不可为空！'))
      } else {
        callback()
      }
    }
    // 选择'自动补零'，位数必填
    var checkFillingDigit = (rule, value, callback) => {
      if (this.form.isFilling && !this.form.fillingDigit) {
        callback(new Error('请填写位数！'))
      } else {
        callback()
      }
    }
    var getRules = () => {
      const rules = {
        fieldCnName: [
          { required: true, message: '请输入中文名称', trigger: 'blur' },
          { max: 7, message: '最大长度7个字符', trigger: 'blur' }
        ],
        fieldName: [
          { required: true, message: '请选择字段标识', trigger: 'blur' },
          { validator: checkFieldName, trigger: 'blur' }
        ],
        isDataType: [
          { required: true, message: '请选择数据类型', trigger: 'blur' }
        ],
        isColumnLength: [
          { required: true, message: '请输入字段长度', trigger: 'blur' },
          { validator: checkMaxLength, trigger: 'blur' }
        ],
        editLength: [
          { validator: checkEditLength, trigger: 'blur' }
        ],
        dictionaryId: [
          { validator: checkDictionaryConfigId, trigger: 'blur' }
        ],
        fillingDigit: [
          { validator: checkFillingDigit, trigger: 'blur' }
        ]
      }
      if (this.isDisabled) {
        delete rules.isDataType
      }
      return rules
    }
    return {
      form: {
        dictionaryId: {
          id: null,
          dictionaryName: null
        }
      },
      rules: getRules(),
      // 字段类型
      dataTypeOptions: [
        { value: 1, label: '字符' },
        { value: 2, label: '数字' }
      ],
      // 著录形式
      inputClassOptions: [
        { value: 'select', label: '下拉框' },
        { value: 'popover', label: '弹出框' },
        { value: 'text', label: '文本框' },
        { value: 'number', label: '数字框' },
        { value: 'date', label: '日期框' },
        { value: 'textarea', label: '文本域' }
      ],
      // 对应字典
      dictionaryData: [],
      dataOptions: []
    }
  },
  watch: {
    thisFields(value) {
      this.form = value
      if (!this.isAdd) {
        this.getForm()
      }
    }
  },
  created() {
  },
  mounted() {
    this.form = this.thisFields
    console.log('isDesFormType', this.isDesFormType)
    if (this.isDesFormType === 'prearchiveLibrary') {
      this.dataOptions = [
        { value: 1, label: '全宗' },
        { value: 3, label: '字典' }
      ]
    } else {
      this.dataOptions = [
        { value: 1, label: '全宗' },
        { value: 2, label: '档案分类' },
        { value: 3, label: '字典' }
      ]
    }
    this.$nextTick(() => {
      if (!this.isAdd) {
        this.getForm()
      }
    })
  },
  methods: {
    getForm() {
      // 初始化
      this.form.isFilling = !!this.form.isFilling
      this.form.isLine = !!this.form.isLine
      this.form.isInput = !!this.form.isInput
      this.form.isRequired = !!this.form.isRequired
      this.form.isAutomatic = !!this.form.isAutomatic

      if (this.form.mateData !== 3) {
        this.dictionaryData = []
        this.form.dictionaryId = {
          id: null,
          dictionaryName: null
        }
      }

      // 字段类型
      if (this.form.isDataType === 1) {
        this.form.isDataTypeTxt = '字符'
      } else if (this.form.isDataType === 2) {
        this.form.isDataTypeTxt = '数字'
      }
      // 初始化 - 著录形式
      switch (this.form.isInputClass) {
        case 'select':
          this.form.isInputClassTxt = '下拉框'
          break
        case 'popover':
          this.form.isInputClassTxt = '弹出框'
          break
        case 'text':
          this.form.isInputClassTxt = '文本框'
          break
        case 'number':
          this.form.isInputClassTxt = '数字框'
          break
        case 'date':
          this.form.isInputClassTxt = '日期框'
          break
        case 'textarea':
          this.form.isInputClassTxt = '文本域'
          break
      }
      if (!this.isDisabled) {
        // 初始化 - 著录形式 - 对应字典
        if (this.form.isInputClass === 'select' || this.form.isInputClass === 'popover') {
          this.getDictrionaryList()
        } else {
          this.dictionaryData = []
          this.form.dictionaryId = {
            id: null,
            dictionaryName: null
          }
        }
      }
    },
    // 获取对应字典list
    getDictrionaryList() {
      FetchDictionaryTree().then(res => {
        this.dictionaryData = res
      })
    },
    // selectDictionary(value) {
    //   this.dictionaryId = value
    // },
    changeDictType(value) {
      this.form.dictionaryId = {
        id: null,
        dictionaryName: null
      }
    },
    // 著录形式为'下拉框'、'弹出框'的，对应字典不为空，反之为空
    selectInputClass(value) {
      if (value === 'select' || value === 'popover') {
        this.getDictrionaryList()
      } else {
        this.dictionaryData = []
        this.form.mateData = null
        this.form.dictionaryId = {
          id: null,
          dictionaryName: null
        }
        this.form.isFilling = false
        this.form.fillingDigit = null
      }
      // 字段类型为数字型，且默认著录类型为数字框不可更改
      if (this.form.isDataType === 2 && this.form.isInputClass !== 'number') {
        this.form.isInputClass = 'number'
        this.$message.error('字段类型为数字型，默认著录类型为数字框且不能修改')
      }
    },
    // 显示长度 input.value>200,则自动勾选上“显示一整行”
    changEditLength(e) {
      const value = e.target.value
      // if (value < 46) {
      //   this.$message.error('显示长度最小46')
      //   this.form.editLength = 46
      // }
      if (value > 225) {
        this.form.isLine = true
      }
      // if (value > 510) {
      //   this.$message.error('显示长度最大510')
      //   this.form.editLength = 510
      // }
    },
    changeIsLine() {
      if (!this.form.isLine) {
        if (this.form.editLength > 225) {
          this.form.editLength = 225
        }
      }
    },
    // '自动补零' false - 补零位数清空
    changeSupplement() {
      if (!this.form.isFilling) {
        this.form.fillingDigit = undefined
      }
      if (this.form.isFilling) {
        // '字段类型'为数字型时，'自动补零'不可操作
        if (this.form.isDataType === 2) {
          this.form.isFilling = false
          this.$message.error('字段类型必须为字符型才可操作！')
        }
        // 著录形式必须-数字框
        if (this.form.isInputClass !== 'number') {
          this.form.isFilling = false
          this.$message.error('著录形式必须为数字框才可操作！')
        }
        if (this.form.isDataType !== 2 && this.form.isInputClass === 'number') {
          this.form.fillingDigit = 1
        }
      }
    },
    // 自动生成 - 规则出自“档案规则设置”页面，著录形式为“文本框”才可
    changeAuto(value) {
      if (this.form.isAutomaticField === 1) {
        this.form.isAutomatic = false
        this.$message.error('已经为档号组成项，不可设置为自动生成')
      } else if (this.form.isInputClass !== 'text') {
        this.form.isAutomatic = false
        this.$message.error('著录形式必须为文本框才可操作！')
      } else if (value) {
        getNoFormatField({ categoryId: this.form.categoryId }).then((res) => {
          const repeatIndex = res.findIndex((item) => {
            return item.dictionaryId === this.form.id
          })
          if (repeatIndex >= 0) {
            this.form.isAutomatic = false
            this.$message.error('已经为档号组成项，不能设为自动生成!')
          }
        })
      }
    },
    // submitForm(formName) {
    // // 对应字典必填判断
    // if (this.form.isInputClass === 'select' || this.form.isInputClass === 'popover') {
    //   if (!this.form.dictionaryId.id ) {
    //     this.$message.error('对应字典项不可为空！')
    //     return
    //   }
    // }
    // // 选择'自动补零'，位数必填
    // if (this.form.isFilling) {
    //   if (!this.form.fillingDigit) {
    //     this.$message.error('请填写位数！')
    //     return
    //   }
    // }
    // // 显示长度限制
    // if (this.form.editLength) {
    //   if (this.form.editLength > 510) {
    //     this.$message.error('显示长度最大510')
    //     return
    //   }
    // }
    //   this.$refs[formName].validate((valid) => {
    //     if (valid) {
    //       alert('submit!')
    //     } else {
    //       console.log('error submit!!')
    //       return false
    //     }
    //   })
    // },
    resetForm(formName) {
      // this.$refs[formName].resetFields()
      // console.log(this.thisFields)
    }
  }
}
</script>
<style lang="scss" scoped>
.dictionary-selected{
  display: flex;
  justify-content: space-between;
  width: 264px;
  .dictionary-left{
    width: 104px;
    ::v-deep .el-input__inner{
      width: 104px !important;
    }
  }
  .dictionary-right{
    width: 150px;
    ::v-deep .el-input__inner{
      width: 150px !important;
    }
  }
}
</style>
