<template>
  <div>
    <div class="dialog-h-content scroll-h">
      <el-form ref="ref_form"
               :inline="true"
               :model="dataForm"
               :rules="dataRule"
               :disabled="formType === 'detail'"
               class="form">

        <el-form-item label="所属网格"
                      prop="gridId" label-width="150px">
          <el-select
                  v-model.trim="gridId"
                  placeholder="请选择"
                  clearable
                  @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="所属房屋" label-width="150px" prop="villageId">
          <div class="resi-cell-value">
            <div class="resi-cell-col">
              <el-form-item prop="villageId">
                <el-select
                        v-model.trim="villageId"
                        placeholder="请选择小区"
                        clearable
                        @clear="handleClearVillage"
                        @change="handleChangeV"
                >
                  <el-option
                          v-for="item in optionsV"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="buildId">
                <el-select
                        v-model.trim="buildId"
                        placeholder="楼号"
                        style="width: 120px;"
                        :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-form-item>
              <el-form-item prop="unitId">
                <el-select
                        v-model.trim="unitId"
                        :disabled="changeBDisabled"
                        placeholder="单元"
                        style="width: 120px;"
                        @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-form-item>
              <el-form-item prop="homeId">
                <el-select
                        v-model.trim="homeId"
                        :disabled="changeDDisabled"
                        placeholder="房号"
                        style="width: 120px;"
                        @change="homeIdHandleChange"
                >
                  <el-option
                          v-for="item in optionsH"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="购房时间" prop="purchaseDate" label-width="150px">
          <el-date-picker v-model="dataForm.purchaseDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          format="yyyy-MM-dd"
                          placeholder="选择日期"
                          style="width:200px"
                          :clearable="false">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="房屋状态"
                      prop="rentFlag"
                      label-width="150px"
                      style="display: block">
          <el-radio-group v-model="rentFlag">

            <el-radio :label="1">出租</el-radio>
            <el-radio :label="2">闲置</el-radio>
            <el-radio :label="0">自住</el-radio>

          </el-radio-group>
        </el-form-item>

        <el-form-item label="房主姓名"
                      prop="ownerName"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_1"
                    placeholder="请输入房主姓名"
                    v-model="dataForm.ownerName">
          </el-input>
        </el-form-item>
        <el-form-item label="房主电话"
                      prop="ownerPhone"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_1"
                    type='number'
                    placeholder="请输入房主电话"
                    v-model="dataForm.ownerPhone">
          </el-input>
        </el-form-item>
        <el-form-item label="房主证件号"
                      prop="ownerIdCard"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_1"
                    placeholder="请输入房主证件号"
                    v-model="dataForm.ownerIdCard">
          </el-input>
        </el-form-item>
        <el-form-item label=" " prop="needUpdate" label-width="150px">
          <el-checkbox v-model="needUpdate">更新房屋信息</el-checkbox>
        </el-form-item>
      </el-form>

    </div>
    <div class="div_btn">
      <el-button size="small"
                 @click="handleCancle">取 消</el-button>
      <el-button size="small"
                 v-if="formType != 'detail'"
                 type="primary"
                 :disabled="btnDisable"
                 @click="handleComfirm">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { Loading } from 'element-ui' // 引入Loading服务
import { requestPost, requestGet } from '@/js/dai/request'


let loading // 加载动画
export default {
  data () {
    return {
      formType: 'add', //表单操作类型 add新增，edit编辑，detail详情
      btnDisable: false,

      houseId: '', //房屋ID
      houseType: '1',
      purpose: '1',
      rentFlag: 1,
      dataForm: {
        neighborHoodId: '', // 所属小区ID
        buildingId: '',//所属楼栋ID
        buildingUnitId: '',//所属单元ID
        doorName: '',//门牌号
        houseType: '',//房屋类型【楼房，平房，别墅】
        purpose: '',//房屋用途【住宅，商业，办公，工业，仓储，商住混用，其他】
        rentFlag: 1,//房屋状态【是：1，否：0】	出租1、闲置2、自住	0
        ownerPhone: '', //房主电话
        ownerName: '', //房主名字
        ownerIdCard: '', //房主证件号
        needUpdate: false,
        purchaseDate: '',
          villageId: '',
          buildId: '',
          unitId: ''

      },

      keyWords: '',
      agencyObj: {},

      optionsV: [],
      optionsB: [],
      optionsH: [],
      optionsD: [],
      optionsG: [],

      gridId: '',
      gridName: '',
      villageId: '',
      villageName: '',
      buildId: '',
      buildName: '',
      unitId: '',
      unitName: '',
      homeId: '',
      homeName: '',
      needUpdate: false

    }
  },
    computed: {
        dataRule () {
            return {
                buildingUnitId: [
                    { required: true, message: '所属单元不能为空', trigger: 'blur' },
                ],
                doorName: [
                    { required: true, message: '门牌号不能为空', trigger: 'blur' }
                ],
                houseType: [
                    { required: true, message: '房屋类型不能为空', trigger: 'blur' }
                ],
                purpose: [
                    { required: true, message: '房屋用途不能为空', trigger: 'blur' }
                ],
                rentFlag: [
                    { required: true, message: '是否出租不能为空', trigger: 'blur' }
                ],
                ownerPhone: [
                    { required: false }
                ],
                ownerName: [
                    { required: false }
                ],
                ownerIdCard: [
                    { required: false }
                ],
                villageId: [
                    { required: true, message: '所属房屋不能为空', trigger: 'blur' }
                ],
                gridId: [
                    { required: true, message: '所属网格不能为空', trigger: 'blur' }
                ],
                purchaseDate: [
                    { required: true, message: '购房时间不能为空', trigger: 'blur' }
                ]
            }
        },
        changeVDisabled() {
            return !this.villageId
        },
        changeBDisabled() {
            return !this.buildId
        },
        changeDDisabled() {
            return !this.unitId
        }

    },
    created () {
        this.getGridList()
        this.getValiheList()
    },

  methods: {
      handleCancle () {
          this.resetData()
          this.$emit('dialogCancle')

      },
    async initForm (type, row, agencyObj) {

      this.$refs.ref_form.resetFields();
      this.resetData()
      this.formType = type

    },

    async loadHouseInfo () {
      if(this.houseId === '' || this.houseId === null){
          this.$message.error('请选择房号')
          return false
      }

      const url = "/gov/org/ichouse/" + this.houseId

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

      if (code === 0) {
        // debugger
        this.dataForm = { ...data }

        this.houseType = this.dataForm.houseType
        this.purpose = this.dataForm.purpose
        this.rentFlag = parseInt(this.dataForm.rentFlag)


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

    },

      handleClearVillage() {
          this.buildId = ''
          this.homeId = ''
      },
      handleClearBuild() {
          this.buildId = ''
          this.unitId = ''
          this.homeId = ''
      },
      handleClearDan() {
          this.unitId = ''
          this.homeId = ''
      },
      handleChangeGrid(val) {
          // 网格
          this.optionsG.find((item) => {
              if (item.value === val) {
                  this.gridName = item.label
              }
          })

          console.log('val', val)
          this.villageId = ''
          this.buildId = ''
          this.unitId = ''
          this.homeId = ''
          this.getValiheList()
      },
      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.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.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.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.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('网络错误')
              })
      },
      handleChangeV(val) {
          // 小区
          this.optionsV.find((item) => {
              if (item.value === val) {
                  this.villageName = item.label
              }
          })
          console.log('val', val)
          this.buildId = ''
          this.unitId = ''
          this.homeId = ''
          this.getBuildList()
      },
      handleChangeB(val) {
          // 楼号
          this.optionsB.find((item) => {
              if (item.value === val) {
                  this.buildName = item.label
              }
          })
          console.log('val', val)
          this.unitId = ''
          this.homeId = ''
          this.getUniList()
      },
      handleChangeD(val) {
          // 单元号
          this.optionsD.find((item) => {
              if (item.value === val) {
                  this.unitName = item.label
              }
          })
          console.log('val', val)
          this.homeId = ''
          this.getHouseList()
      },
      homeIdHandleChange(val){
          // 房间号
          this.optionsH.find((item) => {
              if (item.value === val) {
                  this.homeName = item.label
              }
          })
          this.houseId = val
          this.loadHouseInfo()
      },

    async handleComfirm () {
      this.btnDisable = true
      setTimeout(() => {
        this.btnDisable = false
      }, 10000)

      this.dataForm.houseType = this.houseType
      this.dataForm.purpose = this.purpose
      this.dataForm.rentFlag = this.rentFlag

      // 小区到房号赋值
      this.dataForm.gridId = this.gridId
      this.dataForm.villageId = this.villageId
      this.dataForm.buildId = this.buildId
      this.dataForm.unitId = this.unitId
      this.dataForm.homeId = this.homeId
      this.dataForm.gridName = this.gridName
      this.dataForm.villageName = this.villageName
      this.dataForm.buildName = this.buildName
      this.dataForm.unitName = this.unitName
      this.dataForm.homeName = this.homeName
      this.dataForm.needUpdate = this.needUpdate

      this.$refs['ref_form'].validate((valid, messageObj) => {
        if (!valid) {
          this.btnDisable = false
          app.util.validateRule(messageObj)
        } else {
          this.dataForm.id = ''
          this.addRoom()
        }

      })
    },

    async addRoom () {
      const regCard = /(^\d{15}$)|(^\d{17}(\d|X)$)/; //证件号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
      const regPassport = /^[a-zA-Z]{2}\d{7}$|^[a-zA-Z]{1}\d{8}$/; //护照号，1字母8数字或2字母7数字
      if (this.dataForm.ownerIdCard && regCard.test(this.dataForm.ownerIdCard) === false && regPassport.test(this.dataForm.ownerIdCard) === false) {
        this.btnDisable = false
        this.$message({
          type: 'warning',
          message: '请输入正确的证件号'
        })
        return false;
      }
      const regPhone = /^1(3|4|5|6|7|8|9)\d{9}$/; //联系电话
      if (this.dataForm.ownerPhone && regPhone.test(this.dataForm.ownerPhone) === false) {
        this.btnDisable = false
        this.$message({
          type: 'warning',
          message: '请输入正确的联系电话'
        })
        return false;
      }

      let url = ''

      if (this.formType === 'add') {
        url = '/pli/power/rentHouse/save'
      } else {
        url = '/gov/org/house/houseupdate'
        this.dataForm.houseId = this.houseId
      }

      const { data, code, msg } = await requestPost(url, this.dataForm)
      this.btnDisable = false
      if (code === 0) {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        this.resetData()
        this.$emit('dialogOk')

      } else {

        this.$message.error(msg)
      }

    },

    resetData () {
      this.houseId = '' //房屋ID
      this.houseType = '1'
      this.purpose = '1'
      this.rentFlag = 1
      this.dataForm = {
        neighborHoodId: '', // 所属小区ID
        buildingId: '',//所属楼栋ID
        buildingUnitId: '',//所属单元ID
        doorName: '',//门牌号
        houseType: '1',//房屋类型【楼房，平房，别墅】
        purpose: '1',//房屋用途【住宅，商业，办公，工业，仓储，商住混用，其他】
        rentFlag: 0,//是否出租【是：1，否：0】
        ownerPhone: '', //房主电话
        ownerName: '', //房主名字
        ownerIdCard: '', //房主证件号
        needUpdate: false,
        purchaseDate: '',
        id: ''
      }
      this.gridId = ''
      this.villageId = ''
      this.buildId = ''
      this.unitId = ''
      this.homeId = ''
      this.gridName = ''
      this.villageName = ''
      this.buildName = ''
      this.unitName = ''
      this.homeName = ''
      this.needUpdate = false

    },
  },

  props: {}
}
</script>
<style lang="scss" scoped >
@import "@/assets/scss/modules/visual/communityManageForm.scss";
</style>
