<template>
  <div class="add">
    <div class="pad-l32">
      <div class="item" v-if="!isEdit">
        <span class="label"><span class="tips">*</span>类型</span>
        <div class="value" @click="showType=true">
          <AiMore v-model="appName"/>
        </div>
      </div>
      <div class="info-content" v-for="(items, indexs) in formDataList" :key="indexs">
        <div v-for="(item, index) in items" :key="index">
          <!-- 初始化字段锁定 -->
          <div class="item" v-if="!!formData[item.isInit]&&item.isInit!=item.fieldDbName">
            <span class="label"><span class="tips">{{ item.mustFill == 1 ? '*' : '' }}</span>{{ item.fieldName }}</span>
            <div class="value" v-if="item.dict"
                 v-text="toString($dict.getLabel(item.dict, formData[item.fieldDbName]))"/>
            <div class="value" v-else-if="item.type=='area'">
              <AiAreaPicker :value="formData[item.fieldDbName]" isForm disabled/>
            </div>
            <div class="value" v-else-if="item.type=='upload'">
              <template v-if="formData[item.fieldDbName]">
                <ai-image v-for="(op,i) in [formData[item.fieldDbName]].flat()" :key="i" :src="op" preview/>
              </template>
              <span v-else>-</span>
            </div>
            <div class="value" v-else v-text="toString(formData[item.fieldDbName])"/>
          </div>
          <!-- input输入框 -->
          <div class="item" v-else-if="item.type == 'input' || item.type == 'name' || item.type == 'phone'">
            <span class="label"><span class="tips">{{ item.mustFill == 1 ? '*' : '' }}</span>{{ item.fieldName }}</span>
            <div class="value">
              <u-input type="text" placeholder="请输入" input-align="right" placeholder-style="color:#999;font-size:16px;"
                       height="48" v-model="formData[item.fieldDbName]" :maxlength="item.maxLength"/>
            </div>
          </div>
          <!-- number 输入框 -->
          <div class="item" v-else-if="item.type == 'number'">
            <span class="label"><span class="tips">{{ item.mustFill == 1 ? '*' : '' }}</span>{{ item.fieldName }}</span>
            <div class="value">
              <u-input type="number" placeholder="请输入" input-align="right"
                       placeholder-style="color:#999;font-size:16px;" height="48" v-model="formData[item.fieldDbName]"
                       :maxlength="item.maxLength"/>
            </div>
          </div>
          <!-- 身份证输入框 -->
          <div class="item" v-else-if="item.type == 'idNumber'">
            <span class="label"><span class="tips">{{ item.mustFill == 1 ? '*' : '' }}</span>{{ item.fieldName }}</span>
            <div class="value">
              <u-input type="idcard" placeholder="请输入" input-align="right"
                       placeholder-style="color:#999;font-size:16px;" height="48" v-model="formData[item.fieldDbName]"
                       :maxlength="item.maxLength"/>
            </div>
          </div>
          <!-- textarea输入框 富文本-->
          <div class="textarea" v-else-if="item.type == 'textarea' || item.type == 'text' || item.type == 'rtf'">
            <span class="label"><span class="tips">{{ item.mustFill == 1 ? '*' : '' }}</span>{{ item.fieldName }}</span>
            <div class="value">
              <u-input type="textarea" placeholder="请输入请输入" placeholder-style="color:#999;font-size:16px;" height="200"
                       v-model="formData[item.fieldDbName]" :maxlength="item.maxLength"/>
            </div>
          </div>
          <!-- 字典下拉选择 -->
          <div class="item" v-else-if="item.type == 'dict'">
            <span class="label"><span class="tips">{{ item.mustFill == 1 ? '*' : '' }}</span>{{ item.fieldName }}</span>
            <div class="value" @click="selectClick(item.fieldDbName, item.dict)">
              <AiMore :value="$dict.getLabel(item.dict, formData[item.fieldDbName])"/>
            </div>
          </div>
          <!-- 单选radio -->
          <div class="item" v-else-if="item.type == 'radio'">
            <span class="label"><span class="tips">{{ item.mustFill == 1 ? '*' : '' }}</span>{{ item.fieldName }}</span>
            <div class="value">
              <u-radio-group v-model="formData[item.fieldDbName]">
                <u-radio :name="item.dictValue" v-for="(item, index) in $dict.getDict(item.dict)" :key="index">
                  {{ item.dictName }}
                </u-radio>
              </u-radio-group>
            </div>
          </div>
          <!-- 开关onOff -->
          <div class="item" v-else-if="item.type == 'onOff'">
            <span class="label"><span class="tips">{{ item.mustFill == 1 ? '*' : '' }}</span>{{ item.fieldName }}</span>
            <div class="value">
              <u-switch v-model="formData[item.fieldDbName]" :active-value="1" :inactive-value="0"></u-switch>
            </div>
          </div>
          <!-- 多选checkbox -->
          <div class="textarea" v-else-if="item.type == 'checkbox'">
            <span class="label"><span class="tips">{{ item.mustFill == 1 ? '*' : '' }}</span>{{ item.fieldName }}</span>
            <div class="value">
              <u-checkbox-group>
                <u-checkbox
                    v-model="e.checked"
                    v-for="(e, i) in item.checkList" :key="i"
                    :name="item.dictValue"
                    @change="checkboxChange(indexs, index, i)"
                >{{ e.dictName }}
                </u-checkbox>
              </u-checkbox-group>
            </div>
          </div>
          <!-- 附件 -->
          <div class="textarea" v-else-if="item.type == 'upload'">
            <span class="label"><span class="tips">{{ item.mustFill == 1 ? '*' : '' }}</span>{{ item.fieldName }}</span>
            <div class="value">
              <AiUploader :multiple="true" type="image" :limit="9" placeholder="上传图片"
                          :def.sync="formData[item.fieldDbName]"
                          action="/admin/file/add2"/>
            </div>
          </div>
          <!-- 地区选择 -->
          <div class="item" v-else-if="item.type == 'area'">
            <span class="label"><span class="tips">{{ item.mustFill == 1 ? '*' : '' }}</span>{{ item.fieldName }}</span>
            <div class="value" flex>
              <AiAreaPicker @select="v=>formData[item.fieldDbName]=v" :name.sync="formData[item.fieldDbName+'_name']"
                            all :value="formData[item.fieldDbName]" :valueLevel="item.areaPattern" isForm/>
            </div>
          </div>
          <!-- 人员选择 -->
          <div class="item" v-else-if="item.type == 'user'">
            <span class="label"><span class="tips">{{ item.mustFill == 1 ? '*' : '' }}</span>{{ item.fieldName }}</span>
            <div class="value" @click="handleSelectUser(item.fieldDbName)">
              <template v-if="!formData[item.fieldDbName].length">
                <span>请选择</span>
              </template>
              <template v-else>
                已选择<em>{{ formData[item.fieldDbName].map(e => e.name).slice(0, 2).join("、") }}</em>等<em>{{
                  formData[item.fieldDbName].length
                }}</em>人
              </template>
              <u-icon name="arrow-right" color="#ddd"></u-icon>
            </div>
          </div>
          <!-- 日期选择 / 日期带时分秒选择 / 时间-时分秒选择 -->
          <div class="item" v-else-if="item.type == 'date' || item.type == 'datetime' || item.type == 'time'">
            <span class="label"><span class="tips">{{ item.mustFill == 1 ? '*' : '' }}</span>{{ item.fieldName }}</span>
            <div class="value" @click="dateClick(indexs, index)" flex>
              <AiMore v-model="formData[item.fieldDbName]"/>
            </div>
          </div>
          <!-- 居民档案选择 -->
          <div class="item" v-else-if="item.type == 'resident'">
            <span class="label"><span class="tips">{{ item.mustFill == 1 ? '*' : '' }}</span>{{ item.fieldName }}</span>
            <div class="value" flex>
              <AiPagePicker @select="v=>handleSelectResident(v,item)" single>
                <AiMore v-model="formData[item.fieldDbName + '_name']" :placeholder="item.fieldTips"/>
              </AiPagePicker>
            </div>
          </div>
          <!-- 网格选择 -->
          <div class="item" v-else-if="item.type == 'gird'">
            <span class="label"><span class="tips">{{ item.mustFill == 1 ? '*' : '' }}</span>{{ item.fieldName }}</span>
            <div class="value" flex>
              <AiPagePicker type="custom" @select="v=>handleSelectGird(v,item)" :ops="{url:'../AppGridManagement/SelectGird',label: 'girdName'}">
                <AiMore v-model="formData[item.fieldDbName + '_name']" :placeholder="item.fieldTips"/>
              </AiPagePicker>
            </div>
          </div>
        </div>
      </div>
    </div>
    <u-picker mode="time" v-model="dateShow" :params="deteParams" @confirm="dateConfirm">请选择</u-picker>
    <u-select v-model="selectShow" mode="single-column" :list="selectList" label-name="dictName" value-name="dictValue"
              @confirm="selectConfirm"></u-select>
    <u-select v-model="showType" :list="typeList" label-name="applicationName" value-name="id"
              @confirm="typeConfirm"></u-select>
    <div class="footer" @click="submit" v-if="appId">
      <div class="btn">保存</div>
    </div>
  </div>
</template>

<script>
import {mapActions, mapState} from 'vuex'

export default {
  data() {
    return {
      appId: '',
      appName: '',
      showType: false,
      typeList: [],
      formDataList: [],
      formData: {},
      pageShow: false,
      dateShow: false,
      deteParams: {},
      datePropIndex: '', //时间选择 formDataList索引
      dateIndex: '', //时间选择 formDataList 数组里面的索引
      selectName: '',
      selectList: [],
      selectShow: false,
    }
  },
  computed: {
    ...mapState(['user']),
    isEdit() {
      return !!this.$route.query.id
    }
  },
  created() {
    this.getType()
  },
  onShow() {
    if (this.isEdit) {
      document.title = "编辑人员"
      if (!this.appId) {
        let {appId: value} = this.$route.query
        this.typeConfirm([{value}]).then(() => this.getDetail())
      }
    } else {
      document.title = '新增人员'
      if (this.$route.query.appId && !this.appId) {
        let {appId: value, appName} = this.$route.query
        this.typeConfirm([{value, label: decodeURIComponent(appName)}])
      }
    }
  },
  methods: {
    ...mapActions(['selectEnterpriseContact']),
    handleSelectUser(fieldDbName) {
      this.selectEnterpriseContact({
        fromDepartmentId: 0,
        type: ["user"],
        selectedUserIds: this.form[fieldDbName]?.map(e => e.id)
      }).then(res => {
        this.form[fieldDbName] = res?.userList || []
      })
    },
    getType() {
      this.$http.post(`/app/appapplicationinfo/queryApplicationListByType`, null, {
        params: {type: 0, status: 1}
      }).then((res) => {
        if (res?.data) {
          this.typeList = res.data
        }
      })
    },
    typeConfirm(e) {
      this.appId = e[0].value
      this.appName = e[0].label
      return this.$http.post(`/app/appapplicationinfo/queryApplicationInfo?appId=${this.appId}`).then((res) => {
        if (res?.data) {
          this.formData = {}
          let data = res.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,
                fieldValue: item.defaultValue || ''
              }
            } else if (item.type == 'radio') {
              colItem = {
                ...item,
                dict: item.dictionaryCode,
                fieldValue: item.defaultValue || ''
              }
            } else if (item.type == 'checkbox') {
              colItem = {
                ...item,
                dict: item.dictionaryCode,
                fieldValue: ''
              }
              if (item.defaultValue) {
                colItem.fieldValue = item.defaultValue?.split('`')
              }

            } else if (item.type == 'onOff') {
              colItem = {
                ...item,
                fieldValue: 0
              }
            } else if (item.type == 'number') {
              colItem = {
                ...item,
                type: item.type,
                min: item.minValue || '',
                max: item.maxValue || '',
                fieldValue: Number(item.defaultValue) || 0
              }
            } else if (item.type == 'upload' || item.type == 'user') {
              colItem = {
                ...item,
                type: item.type,
                fieldValue: []
              }
            } else if (item.type == 'area') {
              colItem = {
                ...item,
                type: item.type,
                fieldValue: "",
              }
            } else {
              if (item.type == 'date') {
                item.params = {year: true, month: true, day: true, hour: false, minute: false, second: false}
              }
              if (item.type == 'datetime') {
                item.params = {year: true, month: true, day: true, hour: true, minute: true, second: true}
              }
              if (item.type == 'time') {
                item.params = {year: false, month: false, day: false, hour: true, minute: true, second: true}
              }

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

          if (dictList.length) {
            this.getDictList(dictList)
          } else {
            this.formDataList.map((item) => {
              item.map((e) => {
                if (e.type == 'onOff') { //开关
                  this.formData[e.fieldDbName] = 0
                }
                if (e.type == 'area') { //地区
                  this.formData[e.fieldDbName + '_name'] = this.user.areaName
                }
              })
            })
            this.$forceUpdate()
            this.pageShow = true
          }
        }
      })
    },
    getDictList(listName) {
      this.$dict.load(listName.join(',')).then(() => {
        this.formDataList.map((item) => {
          item.map((e) => {
            if (e.type == 'checkbox') {  //多选
              var list = this.$dict.getDict(e.dict)
              list.map((items) => {
                items.checked = false
              })
              e.checkList = list
            }
            if (e.type == 'onOff') { //开关
              this.formData[e.fieldDbName] = 0
            }
            if (e.type == 'area') { //地区
              this.formData[e.fieldDbName + '_name'] = this.user.areaName
            }
          })
        })
        this.$forceUpdate()
        this.pageShow = true
      })
    },
    selectClick(name, dictName) {
      this.selectName = name
      this.selectList = this.$dict.getDict(dictName)
      this.selectShow = true
    },
    selectConfirm(e) {
      this.formData[this.selectName] = e[0].value
    },
    checkboxChange(indexs, index, i) {
      this.formDataList[indexs][index].checkList[i].checked = !this.formDataList[indexs][index].checkList[i].checked
      this.$forceUpdate()
    },
    dateClick(indexs, index) {
      this.deteParams = this.formDataList[indexs][index].params
      this.datePropIndex = indexs
      this.dateIndex = index

      this.$nextTick(() => {
        this.dateShow = true
      })
    },
    dateConfirm(e) {
      var fieldDbName = this.formDataList[this.datePropIndex][this.dateIndex].fieldDbName
      if (this.formDataList[this.datePropIndex][this.dateIndex].type == 'date') {  //年月日
        this.formData[fieldDbName] = `${e.year}-${e.month}-${e.day}`
      }
      if (this.formDataList[this.datePropIndex][this.dateIndex].type == 'datetime') {  //年月日时分秒
        this.formData[fieldDbName] = `${e.year}-${e.month}-${e.day} ${e.hour}:${e.minute}:${e.second}`
      }
      if (this.formDataList[this.datePropIndex][this.dateIndex].type == 'time') {  //时分秒
        this.formData[fieldDbName] = `${e.hour}:${e.minute}:${e.second}`
      }
    },
    submit() {
      let isValid = true, form = JSON.parse(JSON.stringify(this.formData))
      this.formDataList.map((item) => {
        item?.map((items) => {
          if (items.type == 'checkbox') { //多选
            form[items.fieldDbName] = ''
            let list = []
            items.checkList.map((e) => {
              if (e.checked) {
                list.push(e.dictValue)
              }
            })
            form[items.fieldDbName] = list?.toString()
          }
          if (items.type == 'upload') { //附件 只传id
            let files = [];
            [form[items.fieldDbName]]?.flat()?.map(item => item?.url && files.push(item.url))
            form[items.fieldDbName] = files?.toString()
          }
          // if (items.type == 'onOff') { //开关
          //   form[items.fieldDbName] = form[items.fieldDbName] ? '1' : '0'
          // }
          if (items.type == 'area' && form[items.fieldDbName]) {
            let area = []
            area.push(form[items.fieldDbName])
            area.push(form[items.fieldDbName + '_name'])
            form[items.fieldDbName] = area.join('_')
          }
        })
      })
      this.formDataList.some((item) => {
        return item.some((items) => {
          if (items.mustFill == 1 && !form[items.fieldDbName]) {
            isValid = false
            return this.$u.toast(`${items.fieldName}为必填项`)
          }
        })
      })

      if (!isValid) return

      this.$http.post(`/app/appapplicationinfo/addOrUpdate?appId=${this.appId}`, {
        ...form
      }).then(res => {
        if (res?.code == 0) {
          this.$u.toast('提交成功')
          setTimeout(() => uni.navigateBack({
            success: () => {
              uni.$emit("selectType")
            }
          }), 1500)
        } else this.$u.toast(res?.msg || "提交失败,请联系管理员")
      }).catch(err => {
        this.$u.toast(err || "提交失败,请联系管理员")
      })
    },
    handleSelectResident(resident, item) {
      let info = resident?.[0] || {}
      this.formData = {...this.formData, ...info}
      this.formData[item.fieldDbName] = info.id
      this.formData[item.fieldDbName + "_name"] = info.name
      this.$forceUpdate()
    },
    toString(obj) {
      return obj?.toString() || "-"
    },
    handleSelectGird(gird, item) {
      let info = gird || {}
      this.formData[item.fieldDbName] = [info.id, info.girdName].join("_")
      this.formData[item.fieldDbName + "_name"] = info.girdName
      this.$forceUpdate()
    },
    getDetail() {
      let {id, appId} = this.$route.query
      return id ? this.$http.post("/app/appapplicationinfo/queryDetailById", null, {
        params: {id, appId}
      }).then(res => {
        if (res?.data) {
          this.formData = res.data
          this.$forceUpdate()
        }
      }) : Promise.resolve()
    }
  }
}
</script>

<style lang="scss" scoped>
.add {
  padding-bottom: 112px;

  .title {
    width: 100%;
    height: 96px;
    line-height: 96px;
    background: #FFF;
    font-size: 32px;
    font-weight: 500;
    color: #262B36;
    padding-right: 32px;
    box-sizing: border-box;
    overflow: hidden;

    .tips {
      display: inline-block;
      width: 8px;
      height: 32px;
      background: #4E75FE;
      box-shadow: 0 8px 24px 2px #C9D8FA;
      border-radius: 4px;
      vertical-align: middle;
      margin-right: 22px;
    }

    .select {
      float: right;
      font-size: 30px;
      color: #1365DD;
    }
  }

  .item {
    width: 100%;
    padding: 34px 32px 34px 0;
    background: #FFFFFF;
    border-bottom: 1px solid #D8DDE6;
    display: flex;
    justify-content: space-between;
    font-size: 32px;
    font-family: PingFangSC-Regular, PingFang SC;
    color: #333;
    line-height: 44px;
    box-sizing: border-box;
    position: relative;

    .value {
      .u-icon {
        margin-left: 16px;
      }

      ::v-deep .u-input {
        font-size: 32px;
      }
    }
  }

  .color-999 {
    color: #999;
  }

  .tips {
    display: inline-block;
    width: 16px;
    height: 44px;
    font-size: 32px;
    font-family: PingFangSC-Regular, PingFang SC;
    color: #F46;
    line-height: 44px;
  }

  .textarea {
    width: 100%;
    padding: 34px 32px 34px 0;
    background: #FFFFFF;
    border-bottom: 1px solid #D8DDE6;

    .label {
      display: inline-block;
      font-size: 32px;
      font-family: PingFangSC-Regular, PingFang SC;
      color: #333;
      line-height: 44px;
      margin-bottom: 8px;
    }

    .value {
      padding: 0 16px;
    }
  }

  ::v-deep .default {
    width: 160px !important;
    height: 160px !important;
  }

  .area-icon {
    vertical-align: super;
    position: absolute;
    top: 10px;
    right: 0;
  }

  .footer {
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
  }

  .btn {
    width: 100%;
    height: 112px;
    line-height: 112px;
    text-align: center;
    background: #1365DD;
    font-size: 32px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #FFF;
  }

  .line-bg {
    width: 100%;
    height: 16px;
    background: #F5F5F5;
  }

  .pad-l32 {
    padding-left: 32px;
    background-color: #fff;
  }
}
</style>
