<template>
  <ai-detail v-if="pageShow" class="add-form">
    <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 || !!(formData.resident_id && item.isInit)" />
                </template>
                <!-- 单选radio -->
                <template v-else-if="item.type == 'radio'">
                  <el-radio-group v-model="formData[item.fieldDbName]" :disabled="item.disable == 1 || !!(formData.resident_id && item.isInit)">
                    <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 || !!(formData.resident_id && item.isInit)"></el-switch>
                </template>
                <!-- 多选checkbox -->
                <template v-else-if="item.type == 'checkbox'">
                  <el-checkbox-group v-model="formData[item.fieldDbName]" :disabled="item.disable == 1 || !!(formData.resident_id && item.isInit)">
                    <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 === 'gird'">
                  <el-input disabled :value="girdName" size="small" placeholder="请选择网格">
                    <template slot="append">
                      <el-button size="small" @click="showGrid = true" :disabled="!!(formData.resident_id && item.isInit)">选择网格</el-button>
                    </template>
                  </el-input>
                </template>
                <template v-else-if="item.type === 'resident'">
                  <el-input
                    v-model="formData.name"
                    :placeholder="'请选择'+item.fieldName">
                    <template slot="append">
                      <ai-person-select
                        :instance="instance"
                        :url="'/app/appresident/list?areaId=' + user.info.areaId"
                        :isMultiple="false" dialogTitle="选择" @selectPerson="onChange">
                        <template name="option" v-slot:option="{ item }">
                          <span class="iconfont iconProlife">{{ item.name }}</span>
                          <ai-id mode="show" :show-eyes="false" :value="item.idNumber"/>
                        </template>
                      </ai-person-select>
                    </template>
                  </el-input>
                </template>
                <template v-else-if="item.type == 'idNumber'">
                  <ai-id v-model="formData[item.fieldDbName]" :disabled="item.disable == 1 || !!(formData.resident_id && item.isInit)" />
                </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 || !!(formData.resident_id && item.isInit)"
                            :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 || !!(formData.resident_id && item.isInit)" :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 || !!(formData.resident_id && item.isInit)"
                            :maxlength="item.maxLength" type="textarea" show-word-limit :rows="3"></el-input>
                </template>
                <!-- 日期选择 -->
                <template v-else-if="item.type == 'date'">
                  <el-date-picker style="width: 100%;" v-model="formData[item.fieldDbName]" type="date" placeholder="请选择" :disabled="item.disable == 1 || !!(formData.resident_id && item.isInit)"
                                  :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 || !!(formData.resident_id && item.isInit)"
                                  :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 || !!(formData.resident_id && item.isInit)"
                                  :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 || !!(formData.resident_id && item.isInit)"
                               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" :disabled="item.disable == 1 || !!(formData.resident_id && item.isInit)"/>
                </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 || !!(formData.resident_id && item.isInit)"/>
                </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>
      <ai-dialog
        title="选择网格"
        :visible.sync="showGrid"
        :destroyOnClose="true"
          @close="showGrid = false"
          @onConfirm="getCheckedTree"
          width="720px">
        <div class="grid">
          <el-tree
            :data="treeObj.treeList"
            :props="treeObj.defaultProps"
            node-key="id"
            ref="tree"
            :check-strictly="true"
            show-checkbox
            :default-checked-keys="treeObj.checkedKeys"
            default-expand-all
            @check="onCheckChange">
          </el-tree>
        </div>
      </ai-dialog>
    </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: {
        age: 2
      },
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      girdName: '',
      showGrid: false,
      formDataList: [],
      pageShow: true,
      treeObj: {
        treeList: [],
        defaultProps: {
          children: "girdList",
          label: "girdName",
        },
        checkedKeys: [],
      },
      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.getGridList()
    this.getFormData()
    if (this.params.id) {
      this.getDetail()
    } 
  },
  methods: {
    getGridList() {
      this.instance.post(`/app/appgirdinfo/listAll`).then((res) => {
        if (res.code == 0) {
          this.treeObj.treeList = this.format(res.data)
          if (this.formData.girdId) {
            this.$set(this.treeObj, 'checkedKeys', [this.formData.girdId])
          }
        }
      })
    },

    onChange (e) {
      Object.keys(this.formData).forEach(item => {
        for (var p in e){
          if (item === p) {
            this.$set(this.formData, item, e[item])
          }
        }
      })

      const idNumberInfo = this.idCardNoUtil.getIdCardInfo(e.idNumber)
      this.formData.resident_id = e.id
      this.$set(this.formData, 'birthDate', idNumberInfo.birthday)
      this.formData.photo = e.photo ? [{
        url: e.photo
      }] : []
    },
    getCheckedTree() {
      const gird = this.$refs.tree.getCheckedNodes()

      if (gird.length) {
        this.girdName = gird[0].girdName
        this.formData.gird_id = gird[0].id
      } else {
        this.girdName = ''
        this.formData.gird_id = ''
      }

      this.showGrid = false
    },

    onCheckChange (e) {
      this.$nextTick(() => {
        this.$refs.tree.getCheckedKeys().forEach(v => {
          this.$refs.tree.setChecked(v, false)
        })
        this.$refs.tree.setChecked(e.id, true)
      })
    },

    format (list) {
      return list.map(item => {
        if (item.girdLevel !== '2') {
          item.disabled = true
        }

        if (item.girdList && item.girdList.length) {
          item.girdList = this.format(item.girdList)
        }

        return item
      })
    },

    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 === 'upload') {
          colItem = {
            ...item,
            fieldValue: []
          }
        } 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 || 1,
            max: item.maxValue || 1000000000,
            minValue: item.minValue || 1,
            maxValue: item.maxValue || 1000000000
          }
          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])
        if (item.type === 'number') {
          this.$set(this.formData, item.fieldDbName, 1)
        } else {
          this.$set(this.formData, item.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.configs.tableInfos.map((item) => {
            this.formData[item.fieldDbName] = res.data[item.fieldDbName] || ''
            if(item.type == 'checkbox') {
              var checkList = this.formData[item.fieldDbName]?.split(',')
              this.formData[item.fieldDbName] = checkList
            }

            if (item.type === 'gird' && this.formData[item.fieldDbName]) {
              this.girdName = res.data.gird_id_name
              this.girdName = res.data.gird_id_name
            }

            if (item.type === 'upload' && !this.formData[item.fieldDbName]) {
              this.formData[item.fieldDbName] = []
            }
          })
        }
      })
    },
    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] = this.formData[items.fieldDbName].map(v => v.url).join(',')
                }

                if(items.type == 'gird' && this.formData[items.fieldDbName]) {
                  this.formData[items.fieldDbName] = this.formData[items.fieldDbName] + '_' + this.girdName
                }
                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;
}

.add-form {
  ::v-deep .AiPersonSelect {
    .el-button {
      border-color: transparent;
    background-color: transparent;
    color: inherit;
    border-top: 0;
    border-bottom: 0;
    background: transparent;
    }
  }
}

.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>
