<template>
  <div class="sonTable">
    <div class="optionForm">
      <baseNewForm
          ref="optionForm"
          :spanNumber="24"
          :isFunBtn="false"
          :formRow="optionFormRow"
          :ruleForm="optionRuleForm"
          :labelPosition="'top'"
          @onSelect="selectChangeHanlde"
          @inputBlur="optionFormInputBlur"
          @onSubmit="optionOnSubmit"
      >
      </baseNewForm>
      <baseNewForm
          ref="typeOptionForm"
          :spanNumber="24"
          :isFunBtn="false"
          :formRow="typeOptionFormRow"
          :ruleForm="typeOptionRuleForm"
          :labelPosition="'top'"
          @onSelect="typeSelectChangeHanlde"
          @onSubmit="typeOptionOnSubmit"
      >
      </baseNewForm>
      <baseNewForm
          ref="propertyForm"
          :spanNumber="24"
          :isFunBtn="false"
          :formRow="propertyFormRow"
          :ruleForm="propertyRuleForm"
          :labelPosition="'top'"
          @onSubmit="propertyOnSubmit"

      >
      </baseNewForm>
    </div>
    <div class="smtitle">
      可选控间属性
    </div>
    <div class="checkBoxList">
      <el-checkbox-group v-model="propertyActiveList"
                         @change="propertyActiveListChangeHanlde"
      >
        <el-checkbox v-for="(item,index) in propertyList" :label="item.id" :key="item.id">{{
            item.label
          }}
        </el-checkbox>
      </el-checkbox-group>
    </div>
  </div>
</template>
<script>
import baseNewForm from '../compoments/baseNewForm.vue'
import { deepClone } from '@/utils'
import { getApiModuleApi } from '@/api/apiChunks'

export default {
  name: 'sonTable',
  props: {
    activedTableData: {
      type: Array,
      default: () => {
        return []
      }
    },
    mainTempClick: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      activedTableRow: {},//当前选中行
      optionFormRow: [
        {
          elCol: [
            {
              type: 'input',
              title: '中文名称',
              id: 'chName',
              row: 24,
              disabled: false,
              required: true,
              fontSize: 16
            }
          ]
        },
        {
          elCol: [
            {
              type: 'input',
              title: '英文名称',
              id: 'enName',
              row: 24,
              disabled: false,
              required: true,
              fontSize: 16,
              pattern: /^[a-z][a-z0-9_]{0,50}$/,
              message: '必须以小写字母开头，只能包含小写字母、数字和下划线，不能包含中文字符或其他符号。',
              disabledOfId: true
            }
          ]
        },
        {
          elCol: [
            {
              type: 'select',
              title: '字段类型',
              id: 'filedType',
              row: 24,
              disabled: false,
              required: true,
              fontSize: 16,
              options: []
            }
          ]
        },
        {
          elCol: [
            {
              type: 'num',
              title: '长度',
              id: 'filedLength',
              row: 24,
              disabled: false,
              required: true,
              fontSize: 16,
              max: 255
            }
          ]
        },
        {
          elCol: [
            {
              type: 'input',
              title: '显示名',
              id: 'title',
              row: 24,
              disabled: false,
              required: true,
              fontSize: 16
            }
          ]
        }
        , {
          elCol: [
            {
              type: 'select',
              title: '宽度',
              id: 'row',
              row: 24,
              disabled: false,
              required: true,
              fontSize: 16,
              options: [
                {
                  label: '3',
                  id: '3'
                }, {
                  label: '6',
                  id: '6'
                }, {
                  label: '9',
                  id: '9'
                }, {
                  label: '12',
                  id: '12'
                }, {
                  label: '15',
                  id: '15'
                }, {
                  label: '18',
                  id: '18'
                }, {
                  label: '21',
                  id: '21'
                }, {
                  label: '24',
                  id: '24'
                }
              ]
            }
          ]
        },
        {
          elCol: [
            {
              type: 'num',
              title: '单元格宽度',
              id: 'width',
              row: 24,
              disabled: false,
              required: false,
              fontSize: 16,
              message: 'px'
            }
          ]
        },
        {
          elCol: [
            {
              type: 'select',
              title: '数据类型',
              id: 'type',
              row: 24,
              disabled: false,
              required: true,
              fontSize: 16,
              options: [
                {
                  label: 'input',
                  id: 'input'
                }, {
                  label: 'datepick',
                  id: 'datepick'
                },
                // {
                //   label: 'daterange',
                //   id: 'daterange'
                // },
                {
                  label: 'radio',
                  id: 'radio'
                }, {
                  label: 'textrea',
                  id: 'textrea'
                }, {
                  label: 'select',
                  id: 'select'
                }, {
                  label: 'treeselect',
                  id: 'treeselect'
                },
                {
                  label: 'number',
                  id: 'num'
                }
              ]
            }
          ]
        },
        {
          elCol: [
            {
              type: 'onecheck',
              title: '必填',
              id: 'required',
              row: 24,
              disabled: false,
              required: false,
              fontSize: 16,
              options: [
                {
                  label: '是',
                  id: 'true'
                }, {
                  label: '否',
                  id: 'false'
                }
              ]
            }
          ]
        },
        {
          elCol: [
            {
              type: 'onecheck',
              title: '禁止修改',
              id: 'disabled',
              row: 24,
              disabled: false,
              required: false,
              fontSize: 16,
              options: [
                {
                  label: '是',
                  id: 'true'
                }
              ]
            }
          ]
        }
      ],
      optionRuleForm: {},//表字段options数据
      //type选中后的表
      typeOptionFormRow: [],
      typeOptionRuleForm: {},//表字段根据type数据
      propertyFormRow: [],//可选属性表表格（渲染）
      propertyRuleForm: {},//可选属性表数据
      propertyActiveList: [],//可选属性选中列表（v-model)
      propertyList: [
        {
          label: '大于',
          id: 'up'
        }, {
          label: '小于',
          id: 'low'
        },
        {
          label: '正则',
          id: 'pattern'
        },
        { label: '正则提示', id: 'message' }
      ],//可选属性列表
        //可选属性表数据字典
      typeDist: {
        select: [
          {
            type: 'select',
            id: 'service',
            title: '服务名称',
            row: 24,
            disabled: false,
            required: true,
            fontSize: 16,
            options: []
          },
          {
            type: 'select',
            id: 'label',
            title: 'label',
            row: 24,
            disabled: false,
            required: true,
            fontSize: 16,
            options: []
          }, {
            type: 'input',
            id: 'value',
            title: 'value',
            row: 24,
            disabled: true,
            required: true,
            fontSize: 16,
            options: []
          }
        ],
        radio: [
          {
            type: 'select',
            id: 'service',
            title: '服务名称',
            row: 24,
            disabled: false,
            required: true,
            fontSize: 16,
            options: []
          },
          {
            type: 'select',
            id: 'label',
            title: 'label',
            row: 24,
            disabled: false,
            required: true,
            fontSize: 16,
            options: []
          }, {
            type: 'input',
            id: 'value',
            title: 'value',
            row: 24,
            disabled: true,
            required: true,
            fontSize: 16,
            options: []
          }
        ],
        treeselect: [
          {
            type: 'select',
            id: 'service',
            title: '服务名称',
            row: 24,
            disabled: false,
            required: true,
            fontSize: 16,
            options: []
          },
          {
            type: 'select',
            id: 'label',
            title: 'label',
            row: 24,
            disabled: false,
            required: true,
            fontSize: 16,
            options: []
          }, {
            type: 'input',
            id: 'value',
            title: 'value',
            row: 24,
            disabled: true,
            required: false,
            fontSize: 16,
            options: []
          },
          {
            type: 'select',
            id: 'upId',
            title: 'upId',
            row: 24,
            disabled: false,
            required: true,
            fontSize: 16,
            options: []
          }
        ]
      },
      serviceOptions: [], //服务下啦
      //radiolist属性数字字典
      propertyDist: {
        up: {
          type: 'select',
          id: 'up',
          title: '大于',
          row: 24,
          disabled: false,
          required: true,
          fontSize: 16,
          options: []
        },
        low: {
          type: 'select',
          id: 'low',
          title: '小于',
          row: 24,
          disabled: false,
          required: true,
          fontSize: 16,
          options: []
        },
        pattern: {
          type: 'input',
          id: 'pattern',
          title: '正则',
          row: 24,
          disabled: false,
          required: true,
          fontSize: 16
        },
        message: {
          type: 'input',
          id: 'message',
          title: '正则提示',
          row: 24,
          disabled: false,
          required: true,
          fontSize: 16
        }
      }
    }
  },
  methods: {
    //回显事件
    activedOnClick(val) {
      this.activedTableRow = val
      //清空type带出来的ruleForm
      this.typeOptionFormRow = []
      this.typeOptionRuleForm = {
        value: 'id'
      }
      this.propertyFormRow = []
      this.propertyRuleForm = {}
      this.propertyActiveList = []
      let propertyRuleForm = []
      let optionRuleForm = []
      let typeOptionRuleForm = []

      this.$nextTick(() => {
        // 重置表单
        this.$refs.optionForm.resetForm()
        this.optionRuleForm = deepClone(val)
        console.log(this.optionRuleForm, 'this.optionRuleForm')
        let dom = document.querySelector('.optionForm')
        dom.scrollTo({
          top: 0,
          behavior: 'smooth'
        })
        //表单规则处理
        if (!val.mdmModuleDbFiledsRules) return
        val.mdmModuleDbFiledsRules.forEach(item => {
          if (item.ruleCode === 'required' || item.ruleCode === 'disabled') {
            if (!item.ruleValue) {
              this.$set(this[item.formName], item.ruleCode, false)
            } else if (typeof item.ruleValue === 'boolean') {
              this.$set(this[item.formName], item.ruleCode, item.ruleValue)
            } else {
              this.$set(this[item.formName], item.ruleCode, JSON.parse(item.ruleValue))
            }
          } else {
            this.$set(this[item.formName], item.ruleCode, item.ruleValue)
          }
          if (item.formName === 'propertyRuleForm') {
            propertyRuleForm.push(item.ruleCode)
          }
        })
        if (this.typeOptionRuleForm.service) {
          this.typeSelectChangeHanlde(this.typeOptionRuleForm.service, '', '', {
            id: 'service',
            options: this.serviceOptions
          }, true)
        }
        this.selectChangeHanlde(this.optionRuleForm.type, '', '', { id: 'type' }, true)
        this.selectChangeHanlde(this.optionRuleForm.filedType, '', '', { id: 'filedType' }, true)
        this.propertyActiveList = propertyRuleForm
        this.propertyActiveListChangeHanlde(this.propertyActiveList)

      })
    },
    //表字段下拉触发（根据type类型动态对表
    selectChangeHanlde(val, index, indexRow, row, init = false) {
      if (row.id === 'type') {
        this.typeOptionFormRow = []
        if (!init) {
          this.typeOptionRuleForm = {
            value: 'id'
          }
        }
        if (val && this.typeDist[val]) {
          this.typeDist[val].forEach(item => {
            // 如果是服务名称则将请求下来的服务名用上
            if (item.id === 'service') {
              item.options = deepClone(this.serviceOptions)
            }
            let tempObj = {
              elCol: [
                {
                  ...item
                }
              ]
            }
            this.typeOptionFormRow.push(tempObj)
          })
        }
      }
      //字段类型下啦改变时 将数据类型下啦重置
      if (row.id === 'filedType') {
        if (val) {
          let dist = {
            1: [
              {
                label: 'number',
                id: 'num'
              }
            ],
            2: [
              {
                label: 'number',
                id: 'num'
              }
            ],
            3: [
              {
                label: 'input',
                id: 'input'
              },
              {
                label: 'radio',
                id: 'radio'
              },
              {
                label: 'textrea',
                id: 'textrea'
              },
              {
                label: 'select',
                id: 'select'
              },
              {
                label: 'treeselect',
                id: 'treeselect'
              }
            ],
            4: [
              {
                label: 'datepick',
                id: 'datepick'
              }
              // {
              //   label: 'daterange',
              //   id: 'daterange'
              // }
            ]
          }
          this.optionFormRow[7].elCol[0].options = dist[val]
          if (val == 4) {
            this.optionFormRow[3].elCol[0].disabled = true
            this.optionFormRow[3].elCol[0].required = false
            this.$set(this.optionRuleForm, 'filedLength', '')
          } else {
            this.optionFormRow[3].elCol[0].disabled = false
            this.optionFormRow[3].elCol[0].required = true
          }
        } else {
          this.optionFormRow[3].elCol[0].disabled = false
          this.optionFormRow[3].elCol[0].required = true
        }
        if (!init) {
          this.$set(this.optionRuleForm, 'type', '')
          this.typeOptionFormRow = []
          this.typeOptionRuleForm = {}
        }

      }

    }
    ,
    //表单输入框失焦事件（为了让中文名称可以给显示名）
    optionFormInputBlur(id, row) {
      if (id === 'chName' && !row.title) {
        this.$set(row, 'title', row['chName'])
      }
    }
    ,
    //配置项表通过
    optionOnSubmit() {
      this.$refs.typeOptionForm.submitForm()
    }
    ,
    //type表下拉触发（目的是为了服务名称下拉后拿到label
    async typeSelectChangeHanlde(val, index, indexRow, row, initFlag = false) {
      if (row.id === 'service') {
        if (val) {
          let obj = row.options.find(item => {
            return val === item.id
          })
          console.log(obj, 'obj')
          const res = await getApiModuleApi({
            tl: 'mdmModuleService',
            as: '',
            dj: 'queryMdmServiceField'
          }, { mdmId: obj.mdmId, dbId: obj.dbId })
          this.labelOptions = []
          res.attribute.forEach(item => {
            this.labelOptions.push({
              id: item.enName,
              label: item.chName
            })
          })
        } else {
          this.labelOptions = []
        }

        this.typeOptionFormRow.forEach(item => {
          if (item.elCol[0].id === 'label' || item.elCol[0].id === 'upId') {
            if (!initFlag) {
              this.$set(this.typeOptionRuleForm, item.elCol[0].id, '')
            }
            item.elCol[0].options = deepClone(this.labelOptions)
          }
        })
      }
    }
    ,
    //type表通过
    typeOptionOnSubmit() {
      this.$refs.propertyForm.submitForm()
    }
    ,
    //可选属性表通过校验 准备开始保存
    propertyOnSubmit() {
      console.log('进入保存方法', this.activedTableRow)
      let params = {
        mdmId: this.$route.query.id,
        dbId: this.mainTempClick.id,
        dbType: this.mainTempClick.dbType,
        dbName: this.mainTempClick.dbName,
        id: this.activedTableRow.id
      }
      //开始暂存
      let tempDist = {
        title: true,
        row: true,
        type: true,
        required: true,
        disabled: true,
        width: true
      }
      let tempArr = []
      let disabledWords = ['id', 'formmain_id', 'data_status', 'sorts', 'create_user_id', 'create_time', 'modify_user_id', 'modify_time', 'sts', 'org_id', 'company_id', 'data_id']
      if (disabledWords.includes(this.optionRuleForm.enName)) {
        this.$vmNews(`暂存失败，英文名${this.optionRuleForm.enName}不合法。`)
        return
      }
      if (this.optionRuleForm.type === 'datepick' || this.optionRuleForm.type === 'daterange') {
        if (this.optionRuleForm.filedType != 4) {
          this.$vmNews('字段类型与数据类型不合法，请选择日期类型', 'warning')
          return
        }
      }
      if (this.optionRuleForm.filedType == 4) {
        if (this.optionRuleForm.type !== 'datepick' && this.optionRuleForm.type !== 'daterange') {
          this.$vmNews('字段类型与数据类型不合法', 'warning')
          return
        }
      }
      if (this.optionRuleForm.filedLength * 1 > 255) {
        this.$vmNews('长度不能大于255')
        return
      }
      if (this.optionRuleForm.filedType == 2 && this.optionRuleForm.filedLength * 1 > 65) {
        this.$vmNews('当字段类型为金额时长度不得大于65')
        return
      }
      this.$set(params, 'chName', this.optionRuleForm.chName)
      this.$set(params, 'enName', this.optionRuleForm.enName)
      this.$set(params, 'filedType', this.optionRuleForm.filedType)
      this.$set(params, 'filedLength', this.optionRuleForm.filedLength)
      this.optionFormRow.forEach(item => {
        if (tempDist[item.elCol[0].id]) {
          tempArr.push({
            ruleName: item.elCol[0].title,
            ruleCode: item.elCol[0].id,
            ruleValue: this.optionRuleForm[item.elCol[0].id],
            ruleType: 2,
            formName: 'optionRuleForm'
          })
        }
      })
      this.typeOptionFormRow.forEach(item => {
        tempArr.push({
          ruleName: item.elCol[0].title,
          ruleCode: item.elCol[0].id,
          ruleValue: this.typeOptionRuleForm[item.elCol[0].id],
          ruleType: 2,
          formName: 'typeOptionRuleForm'
        })
      })
      this.propertyFormRow.forEach(item => {
        tempArr.push({
          ruleName: item.elCol[0].title,
          ruleCode: item.elCol[0].id,
          ruleValue: this.propertyRuleForm[item.elCol[0].id],
          ruleType: 2,
          formName: 'propertyRuleForm'
        })
      })
      params.mdmModuleDbFiledsRules = tempArr
      console.log(params)
      this.$emit('sonSaveHandle', params)

    }
    ,
    // 可选属性表变更方法
    propertyActiveListChangeHanlde(val) {
      this.propertyFormRow = []
      // 消除表单里被取消的值
      Object.keys(this.propertyRuleForm).forEach(item => {
        if (!val.includes(item)) {
          this.$delete(this.propertyRuleForm, item)
        }
      })
      if (val === 'up' || val === 'low') {
        this.activedTableData.forEach(item => {
          tempOptions.push({ label: item.id, chName: item.enName })
        })
      }

      // 通过字典找到值的类型渲染在表单上
      val.forEach(item => {
        let tempOptions = []
        //若是大于和小于则需要将datepick拿到放进来选
        if (item === 'up' || item === 'low') {
          this.activedTableData.some(ele => {
            console.log(ele, 'ele')
            if (this.activedTableRow.id === ele.id || !ele.mdmModuleDbFiledsRules) return false
            ele.mdmModuleDbFiledsRules.forEach(ele02 => {
              if (ele02.ruleValue === 'datepick') {
                tempOptions.push({ label: ele.chName, id: ele.enName })
              }
            })
          })
        }
        let tempObj = {
          elCol: [
            {
              ...this.propertyDist[item],
              options: tempOptions
            }
          ]
        }
        this.propertyFormRow.push(tempObj)
      })

    }
  },
  components: {
    baseNewForm
  }
}
</script>


<style scoped lang="scss">
.smtitle {
  color: #333;
  font-weight: 400;
  padding: 20px 0;
  border-top: 1px solid #EBEBEB;
}

.checkBoxList {
  padding-bottom: 50px;
}
</style>
