<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="resi-cell-select"
            @change="handleChangeGrid"
            :disabled="formType === 'edit'"
            style="width: 250px"
          >
            <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"
            :disabled="formType === 'edit'"
            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 || 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-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 || formType === 'edit'"
            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"
            maxlength="30"
            show-word-limit
            style="width: 200px; margin-right: 20px"
            placeholder="请输入姓名	"
            :disabled="formType === 'edit'"
            v-model="fmData.name"
          >
          </el-input>

          <el-checkbox
            v-model="fmData.isWelfare"
            :disabled="formType === 'edit'"
            true-label="1"
            false-label="0"
            >享受福利</el-checkbox
          >
          <el-checkbox
            v-model="fmData.isCheck"
            true-label="1"
            false-label="0"
            :disabled="formType === 'edit'"
            @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"
            maxlength="30"
            show-word-limit
            placeholder="请输入手机号	"
            v-model="fmData.mobile"
            :disabled="formType === 'edit'"
          >
          </el-input>
        </el-form-item>

        <el-form-item
          label="证件号"
          prop="idCard"
          label-width="150px"
          style="display: block"
        >
          <el-input
            class="item_width_1"
            maxlength="30"
            placeholder="请输入身份证号或证件号"
            v-model="fmData.idCard"
            @blur="handleBlurId"
            :disabled="formType === 'edit'"
          ></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
            style="width: 120px"
            class="resi-cell-select"
            :disabled="formType === 'edit'"
          >
            <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="birthday"
          label-width="150px"
          style="display: block"
        >
          <el-date-picker
            v-model="fmData.birthday"
            type="date"
            placeholder="出生日期"
            value-format="yyyy-MM-dd"
            :disabled="formType === 'edit'"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item
          label="出生地"
          prop="birthplace"
          label-width="150px"
          style="display: block"
        >
          <el-input
            class="item_width_1"
            maxlength="50"
            show-word-limit
            placeholder="请输入出生地"
            v-model="fmData.birthplace"
          >
          </el-input>
        </el-form-item>

        <el-form-item
          label="出生人父亲姓名"
          prop="father"
          label-width="150px"
          style="display: block"
        >
          <el-input
            class="item_width_1"
            maxlength="30"
            show-word-limit
            placeholder="请输入出生人父亲姓名"
            v-model="fmData.father"
          >
          </el-input>
        </el-form-item>

        <el-form-item
          label="出生人母亲姓名"
          prop="mother"
          label-width="150px"
          style="display: block"
        >
          <el-input
            class="item_width_1"
            maxlength="30"
            show-word-limit
            placeholder="请输入出生人母亲姓名"
            v-model="fmData.mother"
          >
          </el-input>
        </el-form-item>

        <el-form-item
          label="胎次"
          prop="count"
          label-width="150px"
          style="display: block"
        >
          <el-input-number
            v-model="fmData.count"
            :min="1"
            :max="50"
            label="请输入胎次"
          ></el-input-number>
        </el-form-item>

        <el-form-item
          label="申报户口日期"
          prop="reportDate"
          label-width="150px"
          style="display: block"
        >
          <el-date-picker
            v-model="fmData.reportDate"
            placeholder="申报户口日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item
          label="户主姓名"
          prop="householderName"
          label-width="150px"
          style="display: block"
        >
          <el-input
            class="item_width_1"
            maxlength="50"
            show-word-limit
            placeholder="请输入户主姓名"
            :disabled="fmData.alreadyHaveMaster"
            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
            style="width: 120px"
            class="resi-cell-select"
          >
            <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-item
          v-if="false"
          label="备注"
          prop="remark"
          label-width="150px"
          style="display: block"
        >
          <el-input
            class="item_width_1"
            type="textarea"
            maxlength="500"
            show-word-limit
            :rows="3"
            placeholder="请输入备注，不超过500字"
            v-model="fmData.remark"
          ></el-input>
        </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 { Loading } from "element-ui"; // 引入Loading服务
import { requestPost } from "@/js/dai/request";
import formVltHelper from "dai-js/tools/formVltHelper";
import { computedCard } from "@/utils/index";
import { isCard } from "@/utils/validate";

let loading; // 加载动画

function iniFmData() {
  return {
    id: "",
    gridId: "",
    villageId: "",
    buildId: "",
    unitId: "",
    homeId: "",
    name: "",
    mobile: "",
    idCard: "",
    isWelfare: "0", //福利0否，1是
    isCheck: "0",
    isReplace: "0",
    gender: "",
    birthplace: "",
    father: "",
    mother: "",
    count: "",
    reportDate: "",
    householderName: "",
    householderRelation: "",
    alreadyHaveMaster: false,
  };
}

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

      btnDisable: false,

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

      fmData: iniFmData(),
      checkResult: {},
    };
  },
  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" },
        ],
        birthplace: [
          { 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: {
    async checkResiAvailable() {
      const {
        fmData: { idCard, isCheck },
      } = this;
      if (isCheck == "1" && isCard(idCard)) {
        const { data, code, msg } = await requestPost(
          "/epmetuser/icresiuser/checkuser",
          {
            idCard,
            agencyId: this.$store.state.user.agencyId,
          }
        );
        if (code === 0) {
          this.checkResult = data;
          if (!data.moveInstatus) {
            this.$message({
              type: "error",
              message: `请联系${data.resiAgencyName}迁出该居民后操作`,
            });
          }
        } else {
          this.$message.error(msg);
        }
      }
    },

    handleBlurId() {
      const { sex, birth, age } = computedCard(this.fmData.idCard);
      if (birth) {
        this.fmData.birthday = birth;
        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();
    },

    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);
            if (res.data) {
              this.optionsRelation = res.data;
            }
          }
        });
    },

    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);
            const { name } = res.data;
            if (name) {
              this.fmData.householderName = name;
              this.alreadyHaveMaster = true;
            } else {
              this.alreadyHaveMaster = false;
            }
          }
        });
    },

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

      this.formType = type;
      console.log(row);
      if (row) {
        // this.fmData = { ...this.fmData, ...row };
        await this.getInfo(row.id);
        this.getValiheList();
        this.getBuildList();
        this.getUniList();
        this.getHouseList();
      }
    },

    async getInfo(id) {
      const { data, code, msg } = await requestPost(
        "/epmetuser/icBirthRecord/" + id,
        {
          // id,
        }
      );
      if (code === 0) {
        this.fmData = { ...this.fmData, ...data };
      } 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: "手机号格式有误",
            });
          }
          this.submit();
        }
      });
    },

    async submit() {
      let url = "";
      if (this.formType === "add") {
        url = "/epmetuser/icBirthRecord/save";
      } else if (this.formType === "edit") {
        url = "/epmetuser/icBirthRecord/update";
      } else {
        return;
      }

      const { fmData, checkResult } = this;
      if (
        fmData.isCheck == "1" &&
        checkResult.resiHomeId != fmData.homeId &&
        checkResult.status == "0"
      ) {
        await this.$confirm(
          "居民信息中房屋信息与当前选择房屋不一致，是否更新？",
          "提示",
          {
            confirmButtonText: "更新",
            cancelButtonText: "不更新",
            type: "warning",
            center: true,
          }
        )
          .then(() => {
            this.fmData.isReplace = "1";
          })
          .catch(() => {
            this.fmData.isReplace = "0";
          });
      }

      const { data, code, msg } = await requestPost(url, 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.checkResult = {};
      this.optionsB = [];
      this.optionsH = [];
      this.optionsD = [];
      this.fmData = iniFmData();
    },
    // 开启加载动画
    startLoading() {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: "正在加载……", // 加载中需要显示的文字
        background: "rgba(0,0,0,.7)", // 背景颜色
      });
    },
    // 结束加载动画
    endLoading() {
      // clearTimeout(timer);
      if (loading) {
        loading.close();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.item_width_1 {
  width: 500px;
}
.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>
