<template>
  <div>
    <div class="dialog-h-content scroll-h">
      <el-form ref="ref_form"
               :inline="true"
               :model="fmData"
               :rules="dataRule"
               label-width="150px"
               class="g-edit-form">
        <el-form-item label="所属网格	"
                      prop="gridId"
                      style="display: block">
          <el-select v-model.trim="fmData.gridId"
                     placeholder="请选择"
                     size="small"
                     clearable
                     class="u-edit-width-normal"
                     :disabled="formType === 'edit'"
                     @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"
                      style="display: block">

          <div>
            <el-select v-model.trim="fmData.villageId"
                       placeholder="请选择小区"
                       size="small"
                       clearable
                       class="u-edit-width-normal"
                       @clear="handleClearVillage"
                       @change="handleChangeV"
                       :disabled="formType === 'edit'">
              <el-option v-for="item in optionsV"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div>
            <el-select v-model.trim="fmData.buildId"
                       placeholder="楼号"
                       size="small"
                       clearable
                       class="u-edit-width-build"
                       :disabled="changeVDisabled || formType === 'edit'"
                       @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 || formType === 'edit'"
                       placeholder="单元"
                       size="small"
                       clearable
                       style="margin-left: 10px;"
                       class="u-edit-width-build"
                       @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 || formType === 'edit'"
                       placeholder="房号"
                       size="small"
                       clearable
                       @change="handleChangeH"
                       style="margin-left: 10px;"
                       class="u-edit-width-build">
              <el-option v-for="item in optionsH"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </div>

        </el-form-item>

        <el-form-item label="姓名"
                      prop="name"
                      style="display: block">
          <el-input class="u-edit-width-normal"
                    style="margin-right: 20px"
                    placeholder="请输入姓名	"
                    v-model="fmData.name"
                    :disabled="formType === 'edit'"
                    maxlength="30">
          </el-input>
          <div>
            <!-- <el-checkbox v-model="fmData.isWelfare"
                         true-label="1"
                         false-label="0">享受福利</el-checkbox> -->

            <template v-if="formType === 'edit'">
              <el-checkbox v-model="fmData.isCheck"
                           true-label="1"
                           false-label="0"
                           :disabled="initCheck == 1"
                           @change="checkResiAvailable">补充居民信息</el-checkbox>
            </template>

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

        <el-form-item label="联系电话"
                      prop="mobile"
                      style="display: block">
          <el-input class="u-edit-width-normal"
                    type="number"
                    maxlength="11"
                    show-word-limit
                    placeholder="请输入联系电话	"
                    :disabled="formType === 'edit'"
                    v-model="fmData.mobile">
          </el-input>
        </el-form-item>

        <el-form-item label="证件号"
                      prop="idCard"
                      style="display: block">
          <el-input class="u-edit-width-normal"
                    placeholder="请输入证件号或护照号"
                    v-model="fmData.idCard"
                    :disabled="formType === 'edit'"
                    @blur="handleBlurId"></el-input>
        </el-form-item>

        <el-form-item label="性别"
                      prop="principalName"
                      style="display: block">
          <el-select v-model.trim="fmData.gender"
                     placeholder="性别"
                     size="small"
                     clearable
                     class="u-edit-width-normal"
                     :disabled="true">
            <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"
                      style="display: block">
          <el-input class="u-edit-width-normal"
                    type="number"
                    show-word-limit
                    placeholder="请输入"
                    v-model="fmData.age"
                    :disabled="true">
          </el-input>
        </el-form-item>

        <el-form-item label="迁入日期"
                      prop="inTime"
                      style="display: block">
          <el-date-picker v-model="fmData.inTime"
                          type="date"
                          placeholder="迁入时间"
                          value-format="yyyy-MM-dd"
                          class="u-edit-width-normal"
                          :disabled="formType === 'edit'">
          </el-date-picker>
        </el-form-item>

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

        <el-form-item label="来源地"
                      prop="sourceAddress"
                      style="display: block">

          <el-cascader ref="nowArea"
                       class="u-edit-width-normal"
                       :props="areaProps"
                       v-model="nowAllCode"
                       clearable
                       @change="handleNowArea"></el-cascader>

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

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

        <el-form-item label="与户主关系"
                      prop="householderRelation"
                      style="display: block">
          <el-select v-model.trim="fmData.householderRelation"
                     placeholder="与户主关系"
                     size="small"
                     clearable
                     class="u-edit-width-normal">
            <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="m-edit-btn">
      <el-button size="small"
                 @click="handleCancle">取 消</el-button>
      <el-button type="primary"
                 size="small"
                 class="diy-button--blue"
                 :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: {},
      initCheck: null
    }
  },
  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 () {
    console.log('mounted-----我执行了')
    await this.getGridList()

    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
          } else this.btnDisable = false
          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.fmData.householderName = ''
      this.fmData.householderRelation = ''
      this.getValiheList()
    },
    handleChangeV (val) {
      console.log('val', val)
      this.fmData.buildId = ''
      this.fmData.unitId = ''
      this.fmData.homeId = ''
      this.fmData.householderName = ''
      this.fmData.householderRelation = ''
      this.getBuildList()
    },
    handleChangeB (val) {
      console.log('val', val)
      this.fmData.unitId = ''
      this.fmData.homeId = ''
      this.fmData.householderName = ''
      this.fmData.householderRelation = ''
      this.getUniList()
    },
    handleChangeD (val) {
      console.log('val', val)
      this.fmData.homeId = ''
      this.fmData.householderName = ''
      this.fmData.householderRelation = ''
      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('/actual/base/communityQuarters/listQuartersOptions', {
          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('/actual/base/communityBuilding/buildingoption', {
          quartersId: 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('/actual/base/communityBuildingUnit/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('/actual/base/communityHouse/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.getValiheList()
        this.getBuildList()
        this.getUniList()
        this.getHouseList()
      }
    },
    async getDatail (moveInId) {
      let url = '/actual/base/residentMoveInRecord/detail'

      const params = {
        moveInId: moveInId || ''
      }
      const { data, code, msg } = await requestPost(url, params)
      if (code === 0) {
        this.fmData = { ...data }
        this.initCheck = data.isCheck
        this.nowAllCode = data.sourceAddressPathCode && data.sourceAddressPathCode.split(',')
      } else this.$message.error(msg)
    },

    async handleComfirm () {

      // 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: '联系电话格式有误'
            })
          }
          this.btnDisable = true
          if (this.fmData.isCheck == '1' && 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
              }
            }
          }
          this.submit()

        }
      })
    },

    async submit () {

      let url = ''
      if (this.formType === 'add') {
        url = '/actual/base/residentMoveInRecord/add'
      } else {
        url = '/actual/base/residentMoveInRecord/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.userInfo = {}
      this.fmData = iniFmData()
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/scss/modules/management/edit-main.scss";
</style>


