<template>
  <div class="add">
    <div class="pad-l32">
      <div class="item">
        <span class="label"><span class="tips">*</span>类型</span>
        <div class="value" @click="showType=true">
          <span :class="appId ? '' : 'color-999'">{{appName}}</span>
          <u-icon name="arrow-right" color="#cccccc" ></u-icon>
        </div>
      </div>
      <div class="info-content" v-for="(items, indexs) in formDataList" :key="indexs">
        <div v-for="(item, index) in items" :key="index">
          <!-- input输入框 -->
          <div class="item" v-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-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-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-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-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)">
              <span :class="formData[item.fieldDbName] ? '' : 'color-999'">{{$dict.getLabel(item.dict, formData[item.fieldDbName]) || '请选择'}}</span>
              <u-icon name="arrow-right area-icon" color="#cccccc"   ></u-icon>
            </div>
          </div>
          <!-- 单选radio -->
          <div class="item" v-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-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-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-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"></AiUploader>
            </div>
          </div>
          <!-- 地区选择 -->
          <div class="item area"  v-if="item.type == 'area'">
            <span class="label"><span class="tips">{{item.mustFill == 1 ? '*' : ''}}</span>{{item.fieldName}}</span>
            <div class="value">
              <AiAreaPicker v-model="formData[item.fieldDbName]" :areaId="user.areaId" :name.sync="formData[item.fieldDbName+'_name']"></AiAreaPicker>
              <u-icon name="arrow-right area-icon" color="#cccccc"  ></u-icon>
            </div>
          </div>
          <!-- 人员选择 -->
          <div class="item" v-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="#cccccc"   ></u-icon>
            </div>
          </div>
          <!-- 日期选择 / 日期带时分秒选择 / 时间-时分秒选择 -->
          <div class="item"  v-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)">
              <span :class="formData[item.fieldDbName] ? '' : 'color-999'">{{formData[item.fieldDbName] || '请选择'}}</span>
              <u-icon name="arrow-right area-icon" color="#cccccc"   ></u-icon>
            </div>
          </div>
          <u-picker mode="time" v-model="dateShow" :params="deteParams" start-year="2010" @confirm="dateConfirm" >请选择</u-picker>
        </div>
      </div>
    </div>
    <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 { mapState, mapActions } 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,
      id: ''
    }
  },
  computed: { ...mapState(['user']) },
  created() {
    this.getType()
  },
  onShow() {
    document.title = '新增人员'
  },


  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?type=0`).then((res) => {
        if (res?.data) {
          this.typeList = res.data
        }
      })
    },
    typeConfirm(e) {
      this.appId = e[0].value
      this.appName = e[0].label
      this.$http.post(`/app/appapplicationinfo/queryApplicationInfo?appId=${this.appId}`).then((res) => {
        if (res?.data) {
          var 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) {
                var val = item.defaultValue?.split('`')
                colItem.fieldValue = val
              }

            } 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: this.user.areaId,
              }
            }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()
            console.log(this.formData)
            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()
        console.log(this.formData)
        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.dateShow = true
      this.deteParams =  this.formDataList[indexs][index].params
      this.datePropIndex = indexs
      this.dateIndex = index
    },
    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}`
      }
      console.log(e)
    },
    submit() {
      var isValid = true

      this.formDataList.map((item) => {
        if (item.length) {
          item.map((items) => {
            if (items.type == 'checkbox') { //多选
              this.formData[items.fieldDbName] = ''
              var list = []
              items.checkList.map((e) => {
                if(e.checked) {
                  list.push(e.dictValue)
                }
              })
              this.formData[items.fieldDbName] = list?.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 == 'onOff') { //开关
            //   this.formData[items.fieldDbName] = this.formData[items.fieldDbName] ? '1' : '0'
            // }
            if(items.type == 'area' && this.formData[items.fieldDbName]) {
              console.log(this.formData)
              var area = []
              area.push(this.formData[items.fieldDbName])
              area.push(this.formData[items.fieldDbName+'_name'])
              this.formData[items.fieldDbName] = area.join('_')
            }
          })
        }
      })

      this.formDataList.map((item) => {
        item.map((items) => {
          if(items.mustFill == 1 && this.formData[items.fieldDbName] === '') {
            isValid = false
            return this.$u.toast(`${items.fieldName}为必填项`)
          }
        })
      })

      if (!isValid) return

      this.$http.post(`/app/appapplicationinfo/addOrUpdate?appId=${this.appId}`, {
        ...this.formData,
        id: this.id || ''
      }).then((res) => {
        if (res.code == 0) {
          this.$u.toast('提交成功')
          uni.$emit('specialPeopleList')
          setTimeout(() => {
            uni.navigateBack()
          }, 600)
        }
      })
    },
  }
}
</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: 0px 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{
    padding: 16px 54px 16px 0;
    .label{
      display: inline-block;
      line-height: 78px!important;
    }
    .u-icon{
      vertical-align: super;
      position: absolute;
      top: 42px;
      right: 16px;
    }
  }
  ::v-deep .AiAreaPicker{
    display: inline-block;
    line-height: 78px;
    margin-top: -8px;
  }
  .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>