<template>
  <div>
    <div class="dialog-h-content scroll-h">
      <el-form
        ref="ref_form"
        :inline="true"
        :model="fmData"
        :rules="dataRule"
        :disabled="formType === 'detail'"
        class="form"
      >
        <el-form-item
          label="所属网格	"
          prop="gridId"
          label-width="150px"
          style="display: block"
        >
          <el-select
            v-model.trim="fmData.gridId"
            placeholder="请选择"
            size="small"
            clearable
            class="item_width_1"
            @change="handleChangeGrid"
          >
            <el-option
              v-for="item in optionsG"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="所属房屋	"
          prop="homeId"
          label-width="150px"
          style="display: block"
        >
          <el-select
            v-model.trim="fmData.villageId"
            placeholder="请选择小区"
            size="small"
            clearable
            class="resi-cell-select"
            @clear="handleClearVillage"
            @change="handleChangeV"
            style="margin-right: 8px; width: 120px"
          >
            <el-option
              v-for="item in optionsV"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-select
            v-model.trim="fmData.buildId"
            placeholder="楼号"
            size="small"
            clearable
            style="margin-right: 8px; width: 120px"
            class="resi-cell-select"
            :disabled="changeVDisabled"
            @clear="handleClearBuild"
            @change="handleChangeB"
          >
            <el-option
              v-for="item in optionsB"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-select
            v-model.trim="fmData.unitId"
            :disabled="changeBDisabled"
            placeholder="单元"
            size="small"
            clearable
            style="margin-right: 8px; width: 120px"
            class="resi-cell-select"
            @click="handleClearDan"
            @change="handleChangeD"
          >
            <el-option
              v-for="item in optionsD"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-select
            v-model.trim="fmData.homeId"
            :disabled="changeDDisabled"
            placeholder="房号"
            size="small"
            clearable
            @change="handleChangeH"
            style="width: 120px"
            class="resi-cell-select"
          >
            <el-option
              v-for="item in optionsH"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="姓名"
          prop="name"
          label-width="150px"
          style="display: block"
        >
          <el-input
            class="item_width_1"
            style="margin-right: 20px"
            placeholder="请输入姓名	"
            v-model="fmData.name"
          >
          </el-input>

          <el-checkbox v-model="fmData.isWelfare" true-label="1" false-label="0"
            >享受福利</el-checkbox
          >
          <el-checkbox
            v-model="fmData.isCheck"
            true-label="1"
            false-label="0"
            @change="checkResiAvailable"
            >补充居民信息</el-checkbox
          >
        </el-form-item>

        <el-form-item
          label="手机号"
          prop="mobile"
          label-width="150px"
          style="display: block"
        >
          <el-input
            class="item_width_1"
            type="number"
            maxlength="11"
            show-word-limit
            placeholder="请输入手机号	"
            v-model="fmData.mobile"
          >
          </el-input>
        </el-form-item>

        <el-form-item
          label="身份证号"
          prop="idCard"
          label-width="150px"
          style="display: block"
        >
          <el-input
            class="item_width_1"
            placeholder="请输入身份证号"
            v-model="fmData.idCard"
            @blur="handleBlurId"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="性别"
          prop="principalName"
          label-width="150px"
          style="display: block"
        >
          <el-select
            v-model.trim="fmData.gender"
            placeholder="性别"
            size="small"
            clearable
            class="item_width_1"
          >
            <el-option
              v-for="item in optionsGender"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="年龄"
          prop="age"
          label-width="150px"
          style="display: block"
        >
          <el-input
            class="item_width_1"
            type="number"
            show-word-limit
            placeholder="请输入手机号	"
            v-model="fmData.age"
          >
          </el-input>
        </el-form-item>

        <el-form-item
          label="迁入日期"
          prop="inTime"
          label-width="150px"
          style="display: block"
        >
          <el-date-picker
            v-model="fmData.inTime"
            type="datetime"
            placeholder="迁入时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            class="item_width_1"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item
          label="迁入原因"
          prop="inReason"
          label-width="150px"
          style="display: block"
        >
          <el-input
            type="textarea"
            class="item_width_2"
            placeholder="请输入迁入原因"
            v-model="fmData.inReason"
          >
          </el-input>
        </el-form-item>

        <el-form-item
          label="来源地"
          prop="sourceAddress"
          label-width="150px"
          style="display: block"
        >
          <el-cascader ref="nowArea" class="item_width_1" :props="areaProps" 
            v-model="nowAllCode" clearable @change="handleNowArea"></el-cascader>
          <!-- <el-input
            class="item_width_1"
            placeholder="请输入来源地"
            v-model="fmData.sourceAddress"
          > -->
          </el-input>
        </el-form-item>

        <el-form-item
          label="详细地址"
          prop="address"
          label-width="150px"
          style="display: block"
        >
          <el-input
            class="item_width_1"
            placeholder="请输入详细地址"
            v-model="fmData.address"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="迁移证号码"
          prop="moveNumber"
          label-width="150px"
          style="display: block"
        >
          <el-input
            class="item_width_1"
            placeholder="请输入迁移证号码"
            v-model="fmData.moveNumber"
          >
          </el-input>
        </el-form-item>

        <el-form-item
          label="户主姓名"
          prop="householderName"
          label-width="150px"
          style="display: block"
        >
          <el-input
            class="item_width_1"
            placeholder="请输入户主姓名"
            v-model="fmData.householderName"
          >
          </el-input>
        </el-form-item>

        <el-form-item
          label="与户主关系"
          prop="householderRelation"
          label-width="150px"
          style="display: block"
        >
          <el-select
            v-model.trim="fmData.householderRelation"
            placeholder="与户主关系"
            size="small"
            clearable
            class="item_width_1"
          >
            <el-option
              v-for="item in optionsRelation"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="div_btn resi-btns">
      <el-button size="small" @click="handleCancle">取 消</el-button>
      <el-button
        v-if="formType != 'detail'"
        type="primary"
        size="small"
        :disabled="btnDisable"
        @click="handleComfirm"
        >确 定</el-button
      >
    </div>
  </div>
</template>

<script>
import { requestPost } from "@/js/dai/request";
import formVltHelper from 'dai-js/tools/formVltHelper'
import { computedCard } from '@/utils/index'
import { isCard, isMobile } from '@/utils/validate'

function iniFmData() {
  return {
    gridId: '',
    villageId: '',
    buildId: '',
    unitId: '',
    homeId: '',
    name: '',
    mobile: '',
    idCard: '',
    isWelfare: '0', //福利0否，1是
    isCheck: '0',
    gender: '',
    age: '',
    inTime: '',
    inReason: '',
    sourceAddress: '',
    address: '',
    sourceAddressPathCode: '',
    sourceAddressCode: '',
    householderName: '',
    moveNumber: '',
    householderRelation: '',
    alreadyHaveMaster: false,
    isReplace: '0'
  }
}

export default {
  data() {
    return {
      formType: 'add', //表单操作类型 add新增，edit编辑，detail详情

      btnDisable: false,

      optionsV: [],
      optionsB: [],
      optionsH: [],
      optionsD: [],
      optionsG: [],
      nowAllCode: [],
      optionsGender: [
        {
          value: '1',
          label: '男'
        },
        {
          value: '2',
          label: '女'
        }
      ],
      optionsRelation: [],

      fmData: iniFmData(),
      areaProps: {
        // checkStrictly: true,
        lazy: true,
        lazyLoad: this.lzayLoadArea
      },
      userInfo: {}
    }
  },
  components: {},
  computed: {
    dataRule() {
      let checkIdCard = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入身份证'))
        } else {
          if (!isCard(value)) {
            callback(new Error('身份证号格式不正确'))
          }
          callback()
        }
      }

      return {
        gridId: [
          { required: true, message: '所属网格不能为空', trigger: 'blur' }
        ],
        homeId: [
          { required: true, message: '所属房屋不能为空', trigger: 'blur' }
        ],
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        idCard: [
          { required: true, message: '身份证号不能为空', trigger: 'blur' },
          { required: true, validator: checkIdCard, trigger: 'blur' }
        ],
        inTime: [
          { required: true, message: '迁入时间不能为空', trigger: 'blur' }
        ],
        inReason: [
          { required: true, message: '迁入原因不能为空', trigger: 'blur' }
        ],
        sourceAddress: [
          { required: true, message: '来源地不能为空', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '详细地址不能为空', trigger: 'blur' }
        ]
      }
    },

    changeVDisabled() {
      return !this.fmData.villageId
    },
    changeBDisabled() {
      return !this.fmData.buildId
    },
    changeDDisabled() {
      return !this.fmData.unitId
    }
  },
  props: {},
  watch: {},

  async mounted() {
    this.getGridList()
    this.getValiheList()
    this.getRelationList()
  },

  methods: {
    lzayLoadArea(node, resolve) {
      // this.getArea(node, resolve)
      setTimeout(() => {
        this.getArea(node, resolve)
      }, 200)
    },
    async checkResiAvailable() {
      const {
        fmData: { idCard, isResiUser }
      } = this
      if (isCard(idCard)) {
        const { data, code, msg } = await requestPost(
          '/epmetuser/icresiuser/checkuser',
          {
            idCard,
            agencyId: this.$store.state.user.agencyId
          }
        )
        if (code === 0) {
          if (!data.moveInstatus) {
            this.$message({
              type: 'error',
              message: `请联系${data.resiAgencyName}迁出该居民后操作`
            })
            this.btnDisable = true
          }
          this.userInfo = { ...data }
        } else {
          this.$message.error(msg)
        }
      }
    },
    handleNowArea(val) {
      console.log('val-----', val)
      console.log('label-----', this.$refs.nowArea.getCheckedNodes())
      if (val.length > 0) {
        const labels = this.$refs.nowArea.getCheckedNodes()[0].pathLabels
        this.fmData.sourceAddressCode = val[val.length - 1]
        this.fmData.sourceAddress = labels.join('-')
        this.fmData.sourceAddressPathCode = val.join(',')
        console.log('sourceAddress', this.fmData.sourceAddressPathCode)
        this.$refs.ref_form.clearValidate('sourceAddress')
      } else {
        this.fmData.sourceAddressCode = ''
        this.fmData.sourceAddress = ''
        this.fmData.sourceAddressPathCode = ''
      }
    },
    handleBlurId(val) {
      const { sex, age } = computedCard(this.fmData.idCard)
      if (val) {
        this.fmData.age = age
        this.fmData.gender = sex == 1 ? '1' : '2'
        this.checkResiAvailable()
      }
    },

    handleClearVillage() {
      this.fmData.buildId = ''
      this.fmData.homeId = ''
    },
    handleClearBuild() {
      this.fmData.buildId = ''
      this.fmData.unitId = ''
      this.fmData.homeId = ''
    },
    handleClearDan() {
      this.fmData.unitId = ''
      this.fmData.homeId = ''
    },
    handleChangeGrid(val) {
      console.log('val', val)
      this.fmData.villageId = ''
      this.fmData.buildId = ''
      this.fmData.unitId = ''
      this.fmData.homeId = ''
      this.getValiheList()
    },
    handleChangeV(val) {
      console.log('val', val)
      this.fmData.buildId = ''
      this.fmData.unitId = ''
      this.fmData.homeId = ''
      this.getBuildList()
    },
    handleChangeB(val) {
      console.log('val', val)
      this.fmData.unitId = ''
      this.fmData.homeId = ''
      this.getUniList()
    },
    handleChangeD(val) {
      console.log('val', val)
      this.fmData.homeId = ''
      this.getHouseList()
    },
    handleChangeH(val) {
      console.log('val', val)
      this.getHouseMaster()
    },
    async getArea (node, resolve) {

      const url = "/commonservice/areacode/nextarea"
      let params = {
        parentLevel: node.data ? node.data.level : '',
        parentAreaCode: node.data ? node.data.code : ''
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        const nodes = data.map(item => ({
          value: item.areaCode, // 
          label: item.areaName,
          code: item.areaCode,
          level: item.level,
          leaf: node.level >= 4 // 5层级
        }))
        resolve(nodes)

      } else {
        this.$message.error(msg)
      }

    },
    getRelationList() {
      const { user } = this.$store.state
      this.$http
        .post('/sys/dict/data/relationship', {
          formCode: 'resi_base_info'
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            console.log('获取查询详情成功', res.data)
            this.optionsRelation = res.data
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },

    getGridList() {
      const { user } = this.$store.state
      this.$http
        .post('/gov/org/customergrid/gridoption', {
          agencyId: user.agencyId,
          purpose: 'query'
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            console.log('获取查询详情成功', res.data)
            this.optionsG = res.data
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    getValiheList() {
      const { user } = this.$store.state
      this.$http
        .post('/gov/org/icneighborhood/neighborhoodoption', {
          gridId: this.fmData.gridId,
          agencyId: ''
          // agencyId: user.agencyId
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            console.log('获取查询详情成功', res.data)
            this.optionsV = res.data
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    getBuildList() {
      this.$http
        .post('/gov/org/icbuilding/buildingoption', {
          neighborHoodId: this.fmData.villageId
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            console.log('获取查询详情成功', res.data)
            this.optionsB = res.data
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    getUniList() {
      this.$http
        .post('/gov/org/icbuildingunit/unitoption', {
          buildingId: this.fmData.buildId
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            console.log('获取查询详情成功', res.data)
            this.optionsD = res.data
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    getHouseList() {
      this.$http
        .post('/gov/org/ichouse/houseoption', { unitId: this.fmData.unitId })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            console.log('获取查询详情成功', res.data)
            this.optionsH = res.data
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },

    getHouseMaster() {
      const { homeId } = this.fmData
      if (!homeId) return (this.alreadyHaveMaster = false)

      this.$http
        .post('/epmetuser/icresiuser/queryhousehold/' + homeId, {})
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            console.log('获取户主信息成功', res.data)
            
            if (res.data) {
              const { name } = res.data
              this.fmData.householderName = name
              this.alreadyHaveMaster = true
            } else {
              this.alreadyHaveMaster = false
            }
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },

    async initForm(type, id) {
      this.$refs.ref_form.resetFields()

      this.formType = type
      
      if (id) {
        await this.getDatail(id)
      }
      if (this.formType != 'add') {
        this.getBuildList()
        this.getUniList()
        this.getHouseList()
      }
    },
    async getDatail(moveInId) {
      let url = '/epmetuser/icMoveIn/detail'
      
      const params = {
        moveInId: moveInId || ''
      }
      const { data, code, msg } = await requestPost(url, params)
      if (code === 0) {
        this.fmData = { ...data }
        this.nowAllCode = data.sourceAddressPathCode && data.sourceAddressPathCode.split(',')
      } else this.$message.error(msg)
    },

    async handleComfirm() {
      this.btnDisable = true
      // setTimeout(() => {
      //   this.btnDisable = false
      // }, 10000)
      this.$refs['ref_form'].validate((valid, messageObj) => {
        if (!valid) {
          app.util.validateRule(messageObj)
          this.btnDisable = false
        } else {
          if (!formVltHelper.userOrMobile(this.fmData.mobile)) {
            return this.$message({
              type: 'error',
              message: '手机号格式有误'
            })
          }
          if (this.fmData.isCheck && this.userInfo && this.userInfo.resiHomeId) {
            const { user } = this.$store.state
            if (user.agencyId == this.userInfo.resiAgencyId) {
              if (this.userInfo.resiHomeId !== this.fmData.homeId) {
                this.$confirm('居民信息中房屋信息与当前选择房屋不一致，是否更新？', '提示', {
                  confirmButtonText: '更新',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  this.fmData.isReplace = '1'
                  this.submit()
                }).catch(() => {
                  this.fmData.isReplace = '0'    
                  this.submit()   
                });
                return
              }
            }
            
          } else this.submit()
          
        }
      })
    },

    async submit() {
      
      let url = ''
      if (this.formType === 'add') {
        url = '/epmetuser/icMoveIn/add'
      } else {
        url = '/epmetuser/icMoveIn/edit'

        this.fmData.orgId = this.orgId
      }

      const { data, code, msg } = await requestPost(url, this.fmData)

      if (code === 0) {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        this.resetData()
        this.$emit('dialogOk')
        this.btnDisable = false
      } else {
        this.btnDisable = false
        this.$message.error(msg)
      }
    },

    handleCancle() {
      this.resetData()
      this.$emit('dialogCancle')
    },
    resetData() {
      this.orgId = ''
      this.nowAllCode = []
      this.btnDisable = false
      this.fmData = iniFmData()
    }
  }
}
</script>

<style lang="scss" scoped>
.item_width_1 {
  width: 220px;
}
.item_width_2 {
  width: 400px;
}
.item_width_3 {
  margin-left: 10px;
  width: 200px;
}
.item_width_4 {
  width: 200px;
}

.div_map {
  margin-top: 10px;
}

.div_btn {
  // display: flex;
  // justify-content: flex-end;
}
.el-tabs {
  margin: 0 20px;
}
.el-upload__tip {
  color: rgb(155, 155, 155);
  margin: 0;
}
.form {
  margin-top: 30px;
}

.m-staffs {
  width: 468px;
  .item {
    display: flex;
    justify-content: space-around;
    margin-bottom: 7px;
  }
  .item-add {
  }
}
</style>

<style>
.el-dialog__body {
  padding: 0 10px 20px !important;
}
</style>
