<!-- 表单 -->
<template>
  <span>
    <span v-for="(groupItem, groupIndex) in fieldRuleGroups" :key="groupIndex">
      <h2 class="title" v-if="groupItem.Title">{{ groupItem.Title }}</h2>
      <el-row>
        <el-col :span="item.colSpan" v-for="(item, itemIndex) in groupItem.Columns" :key="itemIndex">
          <cs-form-item :ref="'formItem_' + item.field" :rules="item.rules" :label="item.title">
            <slot v-if="item.controlType < 0" name="custom" :item="item"></slot>

            <!-- 单选控件 -->
            <template v-else-if="item.controlType == 3 && !item.setting.type">
              <el-radio-group v-model="formData[item.field]" @input="change">
                <el-radio v-for="(option, index) in item.setting.option" :key="index" :label="option.Value">
                  {{ option.Label }}
                </el-radio>
              </el-radio-group>
            </template>
            <!-- 多选控件 -->
            <template v-else-if="item.controlType == 3 && item.setting.type">
              <el-checkbox-group v-model="formData[item.field]" @input="change">
                <el-checkbox v-for="(option, index) in item.setting.option" :key="index" :label="option.Value">
                  {{ option.Label }}
                </el-checkbox>
              </el-checkbox-group>
            </template>

            <component
              :is="item.componentName"
              :style="{ maxWidth: item.maxWidth, minWidth: item.minWidth, width: item.width }"
              :type="item.fieldType"
              :tenant-id="tenantId"
              :autosize="{ minRows: 2, maxRows: 4 }"
              :minlength="item.setting && item.setting.min ? item.setting.min : null"
              :maxlength="item.setting && item.setting.max ? item.setting.max : null"
              :options="item.setting && item.setting.option ? item.setting.option : null"
              :value-format="item.setting && item.setting.format ? item.setting.format : null"
              :max="item.uploadFieldMax"
              :picker-options="item.pickerOptions"
              v-model="formData[item.field]"
              :multiple="item.multiple"
              only-id
              :size="size"
              @input="change"
              v-else
            ></component>
          </cs-form-item>
        </el-col>
      </el-row>
    </span>
  </span>
</template>
<script>
export default {
  name: 'csDpForm',
  props: {
    // 租户id
    tenantId: {
      type: Number
    },
    // 动态字段业务注册表Code
    tableCode: {
      type: String,
      required: true
    },
    // 动态字段视图字段表Code
    viewCode: {
      type: String,
      required: true
    },
    // 主键关键字
    key: {
      type: String,
      default: 'Id'
    },
    // 关键字：preview（配置页预览）、new（新建）、edit（编辑）、view（查看 只读）
    type: {
      type: String,
      default: 'new'
    }
  },
  data() {
    return {
      currentKey: '',
      fieldRuleGroups: [],
      formData: {} //要提交的数据
    }
  },
  components: {},
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    tableCode: {
      handler(val) {
        if (!val) {
          this.$util.warning('请传递 tableCode 属性')
          return
        }
        this.init()
      },
      immediate: false, // 首次绑定是否执行
      deep: true // 对象内部的属性监听，也叫深度监听
    },
    viewCode: {
      handler(val) {
        this.init()
      },
      immediate: false, // 首次绑定是否执行
      deep: true // 对象内部的属性监听，也叫深度监听
    }
  },
  //方法集合
  methods: {
    change() {
      this.$forceUpdate()
    },

    initData() {
      const refs = []
      let titles = {}
      this.fieldRuleGroups.forEach(groupItem => {
        groupItem.Columns.forEach(item => {
          if (titles[item.title]) {
            titles[item.title]++
            item.rulesKey = item.title + titles[item.title]
          } else {
            titles[item.title] = 1
            item.rulesKey = item.title
          }

          if (!this.formData[item.field] && item.setting && item.setting.defaultValue) {
            this.formData[item.field] = item.setting.defaultValue
          }

          if (!item.width) {
            if (item.colSpan == 12) {
              item.width = '95.5%'
            } else {
              item.width = '98%'
            }
          }
          const rules = []
          // 设置最大值、最小值
          if (item.setting) {
            if (item.setting.min && Number(item.setting.min)) {
              rules.push(`min:${item.setting.min}`)
            }
            if (item.setting.max && Number(item.setting.max)) {
              rules.push(`max:${item.setting.max}`)
            }
          }
          // 设置必填验证
          if (item.isRequired) {
            rules.push('required')
          }
          switch (item.controlType) {
            case 1: // 文本框
              item.componentName = 'ElInput'
              item.fieldType = 'text'
              switch (item.setting.type) {
                case 1: // 身份证号
                  rules.push('idNumber')
                  break
                case 2: // 邮箱
                  rules.push('email')
                  break
              }
              break
            case 2: // 多行文本框
              item.componentName = 'ElInput'
              item.fieldType = 'textarea'
              break
            case 3: // 数字框
              item.componentName = 'ElInput'
              item.fieldType = 'number'
              switch (item.setting.type) {
                case 1: // 整数
                  rules.push('integer', 'numeric')
                  break
                case 2: // 实数
                  rules.push('numeric')
                  if (item.setting && item.setting.precision) {
                    rules.push(`decimalPoint:${item.setting.precision}`)
                  }
                  break
                case 3: // 联系电话
                  rules.push('mobile')
                  break
              }
              break
            case 4: // 选择框
              // 多选
              if (item.setting.type) {
                item.componentName = 'ElCheckbox'
                if (this.formData[item.field]) {
                  if (typeof this.formData[item.field] == 'string') {
                    this.formData[item.field] = this.formData[item.field].split(',')
                  }
                  let dataNumbers = []
                  for (let i = 0; i < this.formData[item.field].length; i++) {
                    const data = this.formData[item.field][i]
                    if (!Number(data)) {
                      dataNumbers = []
                      break
                    }
                    dataNumbers.push(Number(data))
                  }
                  if (dataNumbers.length > 0) {
                    this.formData[item.field] = dataNumbers
                  }
                } else {
                  if (item.setting.defaultValue) {
                    this.formData[item.field] = item.setting.defaultValue.split(',')
                  } else {
                    this.formData[item.field] = []
                  }
                }
              }
              // 单选
              else {
                item.componentName = 'ElRadio'
              }
              break
            case 5: // 下拉选择器
              item.componentName = 'CsFieldSelect'
              item.multiple = false
              if (item.setting.type) {
                item.multiple = true
              }
              break
            case 6: // 日期选择器
              item.componentName = 'ElDatePicker'
              item.fieldType = item.setting.type
              if (item.fieldType === 'year' && this.formData[item.field]) {
                this.formData[item.field] = this.formData[item.field].toString()
              }
              break
            case 7: //时间选取器
              if (item.setting.format == 'HH:mm') {
                item.componentName = 'ElTimeSelect'
                item.pickerOptions = {
                  start: '00:00',
                  end: '23:59',
                  step: '00:01'
                }
              } else if (item.setting.format == 'HH:mm:ss') {
                item.componentName = 'ElTimePicker'
                item.pickerOptions = {
                  selectableRange: '00:00:00 - 23:59:00'
                }
              }
              break
            case 8: // 开关
              item.componentName = 'ElSwitch'
              if (this.formData[item.field] !== undefined) {
                if (this.formData[item.field] === true || this.formData[item.field] === 'true') {
                  this.formData[item.field] = true
                } else {
                  this.formData[item.field] = false
                }
              } else {
                if (
                  item.setting.defaultValue &&
                  (item.setting.defaultValue === true || item.setting.defaultValue === 'true')
                ) {
                  this.formData[item.field] = true
                } else {
                  this.formData[item.field] = false
                }
              }
              break
            case 9: // 选择用户
              item.componentName = 'CsUser'
              item.multiple = item.setting.type ? true : false
              if (item.multiple && !this.formData[item.field]) {
                this.formData[item.field] = []
              }
              break
            case 10: // 选择学生
              item.componentName = 'CsStudent'
              item.multiple = item.setting.type ? true : false
              if (item.multiple && !this.formData[item.field]) {
                this.formData[item.field] = []
              }
              break
            case 11: // 文件上传
              item.multiple = item.setting.type ? true : false
              if (item.multiple && !this.formData[item.field]) {
                this.formData[item.field] = []
              }
              item.mixed = false
              break
            case 12: // 图片上传
              item.componentName = 'CsFieldUploadImage'
              if (this.formData[item.field] == undefined) {
                this.formData[item.field] = []
              }
              if (item.setting.limit > 1) {
                item.multiple = true
              } else {
                item.multiple = false
              }
              if (item.setting && item.setting.limit) {
                item.uploadFieldMax = item.setting.limit
              }
              break
            case 13: // 国家
              break
            case 14: // 民族
              break
            case 15: // 出生地
              break
            case 16: // 家庭住址
              break
            case 17: // 城市
              break
          }
          item.rules = rules.join('|')
          refs.push('formItem_' + item.field)
        })
      })
      console.log(this.fieldRuleGroups)
      this.$nextTick(() => {
        refs.forEach(ref => {
          this.$refs[ref][0].$refs.provider.reset()
        })
      })
    },

    init() {
      let action = ''
      switch (this.type) {
        case 'new':
          action = 'GetByNew'
          break
        case 'edit':
          action = 'GetByEdit'
          break
        case 'view':
          action = 'GetByView'
          break
        case 'preview':
          action = 'GetByPreview'
          break
      }
      this.getAxios(`//api/v2/DP2/FormConfig`, {
        action: action,
        tableCode: this.tableCode,
        viewCode: this.viewCode,
        key: this.key
      }).then(res => {
        this.$emit('getTitle', res.Title)
        this.fieldRuleGroups = res.ColumnGroups
        this.currentKey = res.Key
        if (res.FormData) {
          this.formData = res.FormData
        }
        this.$emit('getDataHandle', this.fieldRuleGroups, res => {
          this.fieldRuleGroups = res
          this.initData()
        })
        this.initData()
      })
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.init()
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang="scss" scoped></style>
