<template>
  <ai-detail v-if="pageShow">
    <template #title>
      <ai-title :title="params.id ? '编辑'+colData.applicationName : '新增' + colData.applicationName" isShowBottomBorder
                isShowBack @onBackClick="onBack(true)"></ai-title>
    </template>
    <template #content>
      <el-form ref="formData" class="ai-form" :rules="rules" :model="formData" label-width="110px" size="small">
        <ai-card :title="items[0].groupName" v-for="(items, indexs) in formDataList" :key="indexs" v-if="items.length">
          <template slot="content">
            <div v-for="(item, index) in items" :key="index" :style="item.grid == 1 ? 'width: 100%;' : 'width: 50%;'"
                 class="form-div">
              <el-form-item :label="item.fieldName" :prop="item.fieldDbName" style="width: 100%">
                <!-- 字典下拉选择 -->
                <template v-if="item.type == 'dict'">
                  <ai-select v-model="formData[item.fieldDbName]" :placeholder="item.fieldName" :selectList="dict.getDict(item.dict)" :disabled="item.disable == 1" />
                </template>
                <!-- 单选radio -->
                <template v-else-if="item.type == 'radio'">
                  <el-radio-group v-model="formData[item.fieldDbName]" :disabled="item.disable == 1">
                    <el-radio :label="item.dictValue" v-for="(item, i) in dict.getDict(item.dict)" :key="i">{{ item.dictName }}</el-radio>
                  </el-radio-group>
                </template>
                <!-- 开关onOff -->
                <template v-else-if="item.type == 'onOff'">
                  <el-switch v-model="formData[item.fieldDbName]" active-color="#26f" inactive-color="#ddd" active-value="1" inactive-value="0" :disabled="item.disable == 1"></el-switch>
                </template>
                <!-- 多选checkbox -->
                <template v-else-if="item.type == 'checkbox'">
                  <el-checkbox-group v-model="formData[item.fieldDbName]" :disabled="item.disable == 1">
                    <el-checkbox v-for="(item, i) in dict.getDict(item.dict)" :label="item.dictValue" :key="i">
                      {{ item.dictName }}
                    </el-checkbox>
                  </el-checkbox-group>
                </template>
                <!-- 身份证输入框 -->
                <template v-else-if="item.type == 'idNumber'">
                  <ai-id v-model="formData[item.fieldDbName]" :disabled="item.disable == 1" />
                </template>
                <!-- input输入框 -->
                <template v-else-if="item.type == 'input' || item.type == 'name' || item.type == 'phone'">
                  <el-input v-model="formData[item.fieldDbName]" :placeholder="'请输入'+item.fieldName" clearable :disabled="item.disable == 1"
                            :maxlength="item.maxLength" show-word-limit></el-input>
                </template>
                <!-- number 输入框 -->
                <template v-else-if="item.type == 'number'">
                  <el-input-number v-model="formData[item.fieldDbName]" :label="'请输入'+item.fieldName" :disabled="item.disable == 1" :precision="item.decimalPlaces" :max="item.maxValue" :min="item.minValue"></el-input-number>
                </template>
                <!-- textarea输入框 -->
                <template v-else-if="item.type == 'textarea' || item.type == 'text'">
                  <el-input v-model="formData[item.fieldDbName]" :placeholder="'请输入'+item.fieldName" clearable :disabled="item.disable == 1"
                            :maxlength="item.maxLength" type="textarea" show-word-limit :rows="3"></el-input>
                </template>
                <!-- 日期选择 -->
                <template v-else-if="item.type == 'date'">
                  <el-date-picker v-model="formData[item.fieldDbName]" type="date" placeholder="请选择" :disabled="item.disable == 1"
                                  :value-format="item.timePattern"></el-date-picker>
                </template>
                <!-- 日期带时分秒选择 -->
                <template v-else-if="item.type == 'datetime'">
                  <el-date-picker v-model="formData[item.fieldDbName]" type="datetime" placeholder="选择日期时间" :disabled="item.disable == 1"
                                  :value-format="item.timePattern"></el-date-picker>
                </template>
                <!-- 时间-时分秒选择 -->
                <template v-else-if="item.type == 'time'">
                  <el-time-picker v-model="formData[item.fieldDbName]" placeholder="请选择" :disabled="item.disable == 1"
                                  :value-format="item.timePattern"></el-time-picker>
                </template>
                <!-- 附件 -->
                <template v-else-if="item.type == 'upload'">
                  <ai-uploader :instance="instance" isShowTip fileType="file" v-model="formData[item.fieldDbName]" :disabled="item.disable == 1"
                               acceptType=".zip,.rar,.doc,.docx,.xls,.ppt,.pptx,.pdf,.txt,.jpg,.png,.xlsx"
                               :limit="item.fileMaxCount" :maxSize="item.fileChoseSize"></ai-uploader>
                </template>
                <!-- 富文本 -->
                <template v-else-if="item.type == 'rtf'">
                  <ai-editor v-model="formData[item.fieldDbName]" :instance="instance"/>
                </template>
                <!-- 地区选择 -->
                <template v-else-if="item.type == 'area'">
                  <ai-area-get :instance="instance" v-model="formData[item.fieldDbName]" :name.sync="formData[item.fieldDbName +'_name']" :disabled="item.disable == 1"/>
                </template>
                <!-- 人员选择 -->
                <div class="especial" v-else-if="item.type == 'user'">
                  <span class="icon">&nbsp;</span>
                  <span class="people">{{ item.fieldName }}:</span>
                  <ai-wechat-selecter slot="append" isShowUser :instance="instance"
                                      v-model="formData[item.fieldDbName]"></ai-wechat-selecter>
                </div>
              </el-form-item>
            </div>
          </template>
        </ai-card>
      </el-form>
    </template>
    <template #footer>
      <el-button class="delete-btn footer-btn" @click="onBack">取消</el-button>
      <el-button class="footer-btn" type="primary" @click="submit('formData')">提交</el-button>
    </template>
  </ai-detail>
</template>

<script>
import {mapState} from 'vuex'

export default {
  name: 'Add',
  props: {
    instance: Function,
    params: Object,
    dict: Object,
    appId: String,
    backType: String,
    configs: Object
  },
  data() {
    return {
      formData: {},
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      formDataList: [],
      pageShow: false,
      colData: {},
      areaId: ''
    }
  },
  computed: {
    ...mapState(['user']),
    rules() {
      let rules = {}
      this.colData?.tableInfos?.map(e => {
        rules[e.fieldDbName] = []
        if (e.mustFill == 1) {//是否必填
          rules[e.fieldDbName]?.push({required: true, message: e.fieldTips})
        }
      })
      return rules
    }
  },
  created() {
    this.getFormData()
    if (this.params.id) {
      this.getDetail()
    } 
  },
  methods: {
    initForm(data) {
      this.colData = data
      let dictList = []
      let formList = {}
      data.tableInfos.map((item) => {
        let colItem
        if (item.dictionaryCode) {
          dictList.push(item.dictionaryCode)
        }
        if (item.dictionaryCode && item.type != 'radio' && item.type != 'checkbox' && item.type != 'onOff') {
          colItem = {
            ...item,
            type: 'dict',
            dict: item.dictionaryCode
          }
          if (!this.params.id) {
            colItem.fieldValue = item.defaultValue || ''
          }
        } else if (item.type == 'radio') {
          colItem = {
            ...item,
            dict: item.dictionaryCode,
          }
          if (!this.params.id) {
            colItem.fieldValue = item.defaultValue || ''
          }
        } else if (item.type == 'checkbox') {
          colItem = {
            ...item,
            dict: item.dictionaryCode,
            fieldValue: []
          }
          if (!this.params.id && item.defaultValue) {
            var val = item.defaultValue?.split('`')
            colItem.fieldValue = val
          }

        } else if (item.type == 'onOff') {
          colItem = {
            ...item,
          }
          if (!this.params.id) {
            colItem.fieldValue = item.defaultValue || 0
          }
        } else if (item.type == 'number') {
          colItem = {
            ...item,
            type: item.type,
            min: item.minValue || '',
            max: item.maxValue || ''
          }
          if (!this.params.id) {
            colItem.fieldValue = Number(item.defaultValue) || 0
          }
        }else {
          if (item.type == 'date' && !item.timePattern) {
            item.timePattern = 'yyyy-MM-dd'
          }
          if (item.type == 'datetime' && !item.timePattern) {
            item.timePattern = 'yyyy-MM-dd HH:mm:ss'
          }
          if (item.type == 'time' && !item.timePattern) {
            item.timePattern = 'HH:mm:ss'
          }

          colItem = {
            ...item,
            type: item.type,
          }
          if (!this.params.id) {
            colItem.fieldValue = item.defaultValue || ''
          }
        }
        // console.log(colItem)
        formList[item.groupIndex]?.push(colItem) || (formList[item.groupIndex] = [colItem])
        this.$set(this.formData, colItem.fieldDbName, colItem.fieldValue || "")
      })
      this.formDataList = Object.values(formList)

      this.$forceUpdate()

      if (dictList.length) {
        this.getDictList(dictList)
      } else {
        this.pageShow = true
      }
    },
    getFormData() {
      this.initForm(this.configs)
    },
    getDetail() {
      this.instance.post(`/app/appapplicationinfo/queryDetailById?appId=${this.appId}&id=${this.params.id}`).then((res) => {
        if (res?.data) {
          this.formData = res.data
          this.configs.tableInfos.map((item) => {
            if(item.type == 'checkbox') {
              var checkList = this.formData[item.fieldDbName]?.split(',')
              this.formData[item.fieldDbName] = checkList
            }
          })
        }
      })
    },
    getDictList(listName) {
      this.dict.load(listName.join(',')).then(() => {
        this.pageShow = true
      })
    },
    submit() {
      this.$refs.formData?.validate((valid) => {
        if (valid) {
          this.formDataList.map((item) => {
            if (item.length) {
              item.map((items) => {
                if (items.type == 'checkbox' && this.formData[items.fieldDbName].length) { //多选
                  this.formData[items.fieldDbName] = this.formData[items.fieldDbName]?.toString()
                }
                if (items.type == 'upload' && this.formData[items.fieldDbName].length) { //附件 只传id
                  var files = []
                  this.formData[items.fieldDbName].map((item) => {
                    files.push(item.id)
                  })
                  this.formData[items.fieldDbName] = files.join(',')
                }
                if(items.type == 'area' && this.formData[items.fieldDbName]) {
                  var area = []
                  area.push(this.formData[items.fieldDbName])
                  area.push(this.formData[items.fieldDbName+'_name'])
                  this.formData[items.fieldDbName] = area.join('_')
                }
              })
            }
          })
          this.instance.post(`/app/appapplicationinfo/addOrUpdate?appId=${this.appId}`, {
            ...this.formData,
            id: this.params.id || ''
          }).then((res) => {
            if (res.code == 0) {
              this.$message.success('提交成功')
              setTimeout(() => {
                this.onBack(true)
              }, 600)
            }
          })
        }
      })
    },
    onBack(isRefresh) {
      this.$emit('change', {
        type: this.backType == 'Detail' ? 'detail' : 'list',
        params: this.params,
        isRefresh: !!isRefresh,
      })
    },
  },
}
</script>

<style scoped lang="scss">
::v-deep .ai-card{
  width: 100%;
}
.form-div {
  display: inline-block;
  vertical-align: top;
}

.especial {
  margin-bottom: 12px;

  .icon {
    vertical-align: top;
    display: inline-block;
    padding-top: 5px;
    margin-left: 20px;
    color: #f46;
  }

  .people {
    display: inline-block;
    font-size: 14px;
    color: #666;
    padding-right: 12px;
    vertical-align: top;
    width: 64px;
    word-break: break-all;
    box-sizing: border-box;
  }

  .AiWechatSelecter {
    display: inline-block;
    margin-left: 3px;
  }

  .hint {
    font-size: 14px;
    color: #999;
    margin-left: 16px;
  }

  .mar-r40 {
    margin-right: 40px;
  }

  .w80 {
    width: 80px;
    text-align: right;
    color: #888;
  }
}

.AiWechatSelecter {
  width: calc(100% - 120px);
}
</style>
