<template>
  <div>
    <span v-for="(groupItem, groupIndex) in fieldRuleGroups" :key="groupIndex">
      <h2 class="title" v-if="groupItem.Title">{{ groupItem.Title }}</h2>

      <span v-for="(item, itemIndex) in groupItem.Columns" :key="itemIndex">
        <slot v-if="item.controlType < 0" name="custom" :item="item"></slot>

        <component
          v-else-if="item.storeType < 2"
          :is="item.componentName"
          v-model="formData[item.field]"
          :label="!item.isHideTitle ? item.title : ''"
          :rules="item.rules"
          :rules-key="item.rulesKey"
          :type="item.fieldType"
          :tenant-id="tenantId"
          :maxlength="item.setting && item.setting.max ? item.setting.max : null"
          :options="item.setting && item.setting.option ? item.setting.option : null"
          :max="item.uploadFieldMax"
          :min-date="item.minDate"
          :max-date="item.maxDate"
          :min-hour="item.minHour"
          :max-hour="item.maxHour"
          :min-minute="item.minMinute"
          :max-minute="item.maxMinute"
          :multiple="item.multiple"
          :mixed="item.mixed"
          :picker-default-index="item.pickerDefaultIndex ? item.pickerDefaultIndex : null"
          @input="change(formData[item.field], item.field)"
        ></component>
      </span>
    </span>
  </div>
</template>

<script>
export default {
  name: 'CsDpForm',
  mixins: [],
  components: {},
  props: {
    // 租户id
    tenantId: {
      type: Number
    },
    // 动态字段业务注册表Code
    tableCode: {
      type: String,
      required: true
    },
    // 动态字段视图字段表Code
    viewCode: {
      type: String,
      required: true
    },
    // 主键关键字
    key: {
      type: String,
      default: 'Id'
    },
    // 关键字：new（新建）、edit（编辑）、view（查看 只读）
    type: {
      type: String,
      default: 'new'
    }
  },
  data() {
    return {
      currentKey: '',
      fieldRuleGroups: [],
      formData: {} //要提交的数据
    }
  },
  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 // 对象内部的属性监听，也叫深度监听
    }
  },
  computed: {},
  methods: {
    change(value, key) {
      this.$forceUpdate()
      this.$emit('input', this.formData, key)
    },

    /** 根据传递最大最小日期限制，解析成对应日期 */
    getAnalysisDate(format) {
      if (!format) {
        return ''
      }
      let nowDate = moment()
      let args = format.split('|')
      if (args[1]) {
        nowDate = nowDate.add(`${args[0]}s`, args[1])
      }
      return nowDate.toDate()
    },

    /** 创建选择年列表 */
    createYearOption(minFormat, maxFormat, defaultYear) {
      let minYear = 1949
      if (minFormat) {
        var minArgs = minFormat.split('|')
        if (minArgs[0] == 'year' && minArgs[1] && Number(minArgs[1])) {
          minYear = Number(minArgs[1])
        }
      }
      let maxYear = new Date().getFullYear() + 10
      if (maxFormat) {
        var maxArgs = maxFormat.split('|')
        if (maxArgs[0] == 'year' && maxArgs[1] && Number(maxArgs[1])) {
          maxYear = Number(maxArgs[1])
        }
      }
      if (Number(defaultYear)) {
        let year = Number(defaultYear)
        if (year < minYear) {
          minYear = year
        } else if (year > maxYear) {
          maxYear = year
        }
      }
      const yearArr = []
      for (var i = minYear; i <= maxYear; i++) {
        yearArr.push({ Label: `${i}年`, Value: i })
      }
      return yearArr
    },

    initData() {
      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
          }

          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 = 'CsField'
              switch (item.setting.type) {
                case 1: // 身份证号
                  rules.push('idNumber')
                  break
                case 2: // 邮箱
                  rules.push('email')
                  break
              }
              break
            case 2: // 多行文本框
              item.componentName = 'CsFieldTextarea'
              break
            case 3: // 数字框
              item.componentName = 'CsField'
              switch (item.setting.type) {
                case 1: // 整数
                  rules.push('integer', 'numeric')
                  item.fieldType = 'digit'
                  break
                case 2: // 实数
                  rules.push('numeric')
                  if (item.setting && item.setting.precision) {
                    rules.push(`decimalPoint:${item.setting.precision}`)
                  }
                  item.fieldType = 'number'
                  break
                case 3: // 联系电话
                  rules.push('mobile')
                  item.fieldType = 'tel'
                  break
              }
              break
            case 4: // 选择框
              if (item.setting.type) {
                item.componentName = 'CsFieldCheckbox' // 多选控件
                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 = 'CsFieldRadio' // 单选控件
              }
              break
            case 5: // 下拉选择器
              item.componentName = 'CsFieldPicker'
              item.multiple = false
              if (item.setting.type) {
                item.multiple = true
              }
            case 6: // 日期选择器
              if (item.setting.min) {
                item.minDate = this.getAnalysisDate(item.setting.min)
              }
              if (item.setting.max) {
                item.maxDate = this.getAnalysisDate(item.setting.max)
              }
              switch (item.setting.type) {
                case 'year': // 按年筛选
                  item.setting.option = this.createYearOption(
                    item.setting.min,
                    item.setting.max,
                    item.setting.defaultValue
                  ) // 获取年列表
                  var year = new Date().getFullYear()
                  if (item.setting.defaultValue) {
                    year = Number(item.setting.defaultValue)
                  }
                  for (let i = 0; i < item.setting.option.length; i++) {
                    const option = item.setting.option[i]
                    if (option.Value == year) {
                      item.pickerDefaultIndex = i
                      break
                    }
                  }
                  item.componentName = 'CsFieldPicker'
                  break
                case 'month': // 年月筛选
                  item.componentName = 'CsFieldYearMonth'
                  break
                case 'date': // 年月日筛选
                  item.componentName = 'CsFieldDate'
                  break
                case 'datetime': // 年月日时分秒
                  item.componentName = 'CsFieldDateTime'
                  break
              }
              break
            case 7: // 时间选择框
              if (item.setting.min) {
                let minTimeArgs = item.setting.min.split(':')
                item.minHour = minTimeArgs[0]
                item.minMinute = minTimeArgs[1]
              }
              if (item.setting.max) {
                let maxTimeArgs = item.setting.max.split(':')
                item.maxHour = maxTimeArgs[0]
                item.maxMinute = maxTimeArgs[1]
              }
              switch (item.setting.format) {
                case 'HH:mm':
                  item.componentName = 'CsFieldTime'
                  break
                case 'HH:mm:ss':
                  item.componentName = 'CsFieldTimeSs'
                  break
              }
              break
            case 8: // 开关
              item.componentName = 'CsFieldSwitch'
              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 = 'CsFieldUser'
              if (this.formData[item.field] == undefined) {
                this.formData[item.field] = []
              }
              if (item.setting && item.setting.type) {
                item.multiple = true
              } else {
                item.multiple = false
              }
              item.mixed = false
              break
            case 10: // 选择学生
              item.componentName = 'CsFieldStudent'
              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: // 国家
              item.componentName = 'CsFieldCountry'
              break
            case 14: // 民族
              item.componentName = 'CsFieldEthnicity'
              break
            case 15: // 出生地
              item.componentName = 'CsFieldBirthplace'
              break
            case 16: // 家庭住址
              item.componentName = 'CsFieldAddress'
              break
            case 17: // 城市
              item.componentName = 'CsFieldCity'
              break
          }
          item.rules = rules.join('|')
        })
      })
      console.log(this.fieldRuleGroups)
    },

    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()
      })
    }
  },
  created() {},
  mounted() {
    this.init()
  }
}
</script>
<style lang="scss" scoped>
.title {
  color: rgba(69, 90, 100, 0.6);
  font-weight: normal;
  font-size: 14px;
  line-height: 16px;
  margin: 0;
  padding: 16px 16px;
}
</style>
