<template>
  <ai-detail>
    <template #title>
      <ai-title
        :title="params.id ? '编辑吸毒人员' : '新增吸毒人员'"
        isShowBottomBorder
        isShowBack
        @onBackClick="onBack(true)">
      </ai-title>
    </template>
    <template #content>
      <ai-card title="基本信息">
        <template slot="content">
          <el-form ref="formData" class="ai-form" :rules="rules" :model="formData" label-width="110px" size="small">
            <div v-for="(item, index) in filedList" :key="index" :style="item.grid == 1 ? 'width: 100%;' : 'width: 50%;'">
              <el-form-item :label="item.label" :prop="item.formDbName" style="width: 100%">
                <template v-if="item.type == 'select'">
                  <ai-select v-model="formData[item.formDbName]" :placeholder="item.fieldName" :selectList="dict.getDict(item.dict)" :disabled="item.disable == 1" />
                </template>
                <template v-else-if="item.type == 'radio'">
                  <el-radio-group v-model="formData[item.formDbName]" :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>
                <template v-else-if="item.type == 'gird'">
                  <el-input disabled v-model="formData[item.formDbName]" :maxlength="200" size="small" placeholder="请选择选择网格">
                    <template slot="append">
                      <el-button size="small" @click="showGrid = true">选择网格</el-button>
                    </template>
                  </el-input>
                </template>
                <template v-else-if="item.type == 'onOff'">
                  <el-switch v-model="formData[item.formDbName]" active-color="#26f" inactive-color="#ddd" active-value="1" inactive-value="0" :disabled="item.disable == 1"></el-switch>
                </template>
                <template v-else-if="item.type == 'checkbox'">
                  <el-checkbox-group v-model="formData[item.formDbName]" :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.formDbName]" :disabled="item.disable == 1" />
                </template>
                <template v-else-if="item.type == 'input' || item.type == 'name' || item.type == 'phone'">
                  <el-input v-model="formData[item.formDbName]" :placeholder="'请输入'+ item.label" clearable :disabled="item.disable == 1"
                            :maxlength="item.maxLength" show-word-limit></el-input>
                </template>
                <template v-else-if="item.type == 'number'">
                  <el-input-number v-model="formData[item.formDbName]" :label="'请输入'+item.label" :disabled="item.disable == 1" :precision="item.decimalPlaces" :max="item.maxValue" :min="item.minValue"></el-input-number>
                </template>
                <template v-else-if="item.type == 'textarea' || item.type == 'text'">
                  <el-input v-model="formData[item.formDbName]" :placeholder="'请输入'+item.label" 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.formDbName]"
                    type="date"
                    style="width: 100%"
                    placeholder="请选择"
                    :disabled="item.disable == 1"
                    value-format="yyyy-MM-DD">
                  </el-date-picker>
                </template>
                <template v-else-if="item.type == 'datetime'">
                  <el-date-picker v-model="formData[item.formDbName]" type="datetime" placeholder="选择日期时间" :disabled="item.disable == 1"
                                  value-format="yyyy-MM-DD HH-mm-ss"></el-date-picker>
                </template>
                <template v-else-if="item.type == 'area'">
                  <ai-area-select
                    placeholder="请选择地区"
                    clearable
                    always-show
                    :instance="instance"
                    v-model="formData[item.formDbName]"
                    @fullname="v => formData.areaName = v"
                  />
                </template>
              </el-form-item>
            </div>
          </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>
      </ai-card>
    </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
  },
  data() {
    var regPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入电话'))
      } else {
        const reg = /^[0-9]{3,11}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的电话号码'))
        }
      }
    }

    var controlPhone = (rule, value, callback) => {
      if (!value) {
        callback()
      } else {
        const reg = /^[0-9]{3,11}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的电话号码'))
        }
      }
    }

    let IdNumberPass = (rule, value, callback) => {
      if (value) {
        if (this.idCardNoUtil.checkIdCardNo(value)) {
          callback();
        } else {
          callback(new Error('身份证号格式错误'))
        }
      } else {
        callback(new Error('请输入身份证号'))
      }
    }
    return {
      showGrid: false,
      formData: {
        girdName: '',
        name: '',
        idNumber: '',
        girdId: '',
        placeTime: '',
        phone: '',
        areaId: '',
        address: '',
        areaName: '',
        firstTime: '',
        status: '',
        debug: '',
        control: '',
        controlName: '',
        controlPhone: '',
        crime: ''
      },
      treeObj: {
        treeList: [],
        defaultProps: {
          children: "girdList",
          label: "girdName",
        },
        checkedKeys: [],
      },
      areaId: '',
      filedList: [
        {
          label: '姓名',
          type: 'input',
          formDbName: 'name',
          mustFill: 1,
          fieldTips: '请输入姓名'
        },
        {
          label: '身份证号',
          type: 'input',
          formDbName: 'idNumber',
          mustFill: 1,
          fieldTips: '请输入身份证号',
          rules: { required: true, validator: IdNumberPass, trigger: 'blur' }
        },
        {
          label: '联系电话',
          type: 'input',
          formDbName: 'phone',
          mustFill: 1,
          fieldTips: '请输入联系电话',
          rules: { required: true, validator: regPhone, trigger: 'blur' }
        },
        {
          label: '所属区域',
          type: 'area',
          formDbName: 'areaId',
          mustFill: 1,
          grid: 1,
          fieldTips: '请选择所属区域'
        },
        {
          label: '详细地址',
          type: 'input',
          grid: 1,
          formDbName: 'address',
          maxLength: 20
        },
        {
          label: '所属网格',
          type: 'gird',
          grid: 1,
          formDbName: 'girdName'
        },
        {
          label: '初次发现日期',
          type: 'date',
          formDbName: 'firstTime',
        },
        {
          label: '吸毒状态',
          type: 'select',
          dict: 'appSpecialDrug',
          formDbName: 'status',
        },
        {
          label: '戒毒情况',
          type: 'select',
          dict: 'appSpecialDebug',
          formDbName: 'debug',
        },
        {
          label: '管控情况',
          type: 'select',
          dict: 'appSpecialControl',
          formDbName: 'control',
        },
        {
          label: '管控人姓名',
          type: 'input',
          formDbName: 'controlName'
        },
        {
          label: '管控人联系方式',
          type: 'input',
          grid: 1,
          formDbName: 'controlPhone',
          rules: { validator: controlPhone, trigger: 'blur' }
        },
        {
          label: '有无犯罪史',
          type: 'select',
          dict: 'isReflection',
          formDbName: 'crime'
        }
      ]
    }
  },
  computed: {
    ...mapState(['user']),
    rules() {
      let rules = {}
      this.filedList.map(e => {
        rules[e.formDbName] = []
        if (e.mustFill == 1) {
          rules[e.formDbName]?.push({required: true, message: e.fieldTips})
        }
        if (e.rules) {
          rules[e.formDbName].push(e.rules)
        }
      })
      return rules
    }
  },

  created () {
    if (this.params.id) {
      this.dict.load(this.filedList.filter(v => v.dict).map(v => v.dict)).then(() => {
        this.getDetail()
      })
    } else {
      this.getGridList()
      this.dict.load(this.filedList.filter(v => v.dict).map(v => v.dict))
    }
  },

  methods: {
    getFormData() {
      this.initForm(this.configs)
    },

    getCheckedTree() {
      if (this.$refs.tree.getCheckedNodes().length > 1) {
        return this.$message.error('不能选择多个网格')
      }

      const gird = this.$refs.tree.getCheckedNodes()

      if (gird.length) {
        this.formData.girdName = gird[0].girdName
        this.formData.girdId = gird[0].id
      } else {
        this.formData.girdName = ''
        this.formData.girdId = ''
      }
      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)
      })
    },

    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])
          }
        }
      })
    },

    format (list) {
      return list.map(item => {
        if (item.girdList && item.girdList.length) {
          item.girdList = this.format(item.girdList)
        }

        return item
      })
    },

    getDetail() {
      this.instance.post(`/app/appspecialdrug/queryDetailById?id=${this.params.id}`).then((res) => {
        if (res.data) {
          this.formData = res.data
          this.getGridList()
        }
      })
    },

    submit() {
      this.$refs.formData?.validate((valid) => {
        if (valid) {
          this.filedList.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/appspecialdrug/addOrUpdate`, {
            ...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: '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>
