<template>
  <div>
    <div class="applicant">
      <div class="title">
        <div class="icon"></div>
        <p>申请人信息</p>
      </div>
      <van-form class="main" @submit="onSubmit" ref="reportForm">
        <van-field
          v-model="form.name"
          label="姓名"
          required
          readonly
          placeholder="请输入申请人姓名"
          :rules="[{ required: true, message: '请填写姓名' }]"
        />
        <van-field
          v-model="form.idCard"
          label="身份证"
          required
          readonly
          placeholder="请输入申请人身份证号"
          :rules="[
            { required: true, message: '请填写身份证' },
            { pattern: idcardReg, message: '请输入正确内容' },
          ]"
        />
        <van-field
          v-model="form.streetName"
          label="所属街道"
          required
          placeholder="请选择区县与街道"
          readonly
          clickable
          @click="disabled ? '' : (showAreaPicker = true)"
          :rules="[{ required: true, message: '请选择所属街道', trigger: 'onChange' }]"
        />
        <van-popup v-model="showAreaPicker" position="bottom">
          <div class="popup_title">
            <p class="cancle" @click="areaCancle">取消</p>
            <p class="confirm" @click="areaConfirm">确认</p>
          </div>
          <van-tree-select
            :items="areaList"
            :active-id.sync="streetCode"
            :main-active-index.sync="areaIndex"
            @click-item="
              (data) => {
                street = data;
              }
            "
          />
        </van-popup>
        <van-field
          v-model="form.householdRegister"
          label="户籍地址"
          required
          :readonly="disabled"
          placeholder="请输入户籍地址"
          :rules="[{ required: true, message: '请填写户籍地址' }]"
        />
        <van-field
          v-model="form.mobile"
          label="联系电话"
          type="number"
          required
          :readonly="disabled"
          placeholder="请输入联系电话"
          :rules="[
            { required: true, message: '请填写联系电话' },
            { pattern: phoneReg, message: '请输入正确内容' },
          ]"
        />
        <van-field
          v-model="form.reason"
          rows="2"
          autosize
          label="困难原因"
          type="textarea"
          maxlength="300"
          placeholder="请输入困难原因"
          show-word-limit
          required
          :readonly="disabled"
          :rules="[{ required: true, message: '请输入困难原因' }]"
        />
        <div class="add-button">
          <van-button
            native-type="button"
            icon="plus"
            size="small"
            type="info"
            :disabled="disabled"
            @click="addMember"
            >家庭成员</van-button
          >
          <van-button
            native-type="button"
            icon="plus"
            size="small"
            type="primary"
            :disabled="disabled"
            style="margin-left: 20px"
            @click="addProvider"
            >赡抚养人</van-button
          >
        </div>
        <div v-for="member in form.members" :key="member.id" class="card">
          <div class="member_title">
            <p>家庭成员信息</p>
            <img
              class="delete_icon"
              src="@/assets/common/delete_icon.png"
              alt=""
              @click="disabled ? '' : delMember(member.id)"
            />
          </div>
          <div>
            <van-field
              v-model="member.name"
              label="姓名"
              required
              :readonly="disabled"
              placeholder="请输入申请人姓名"
              :rules="[{ required: true, message: '请填写姓名' }]"
            />
            <van-field
              v-model="member.idCard"
              label="身份证"
              required
              :readonly="disabled"
              placeholder="请输入申请人身份证号"
              :rules="[
                { required: true, message: '请填写身份证' },
                { pattern: idcardReg, message: '请输入正确内容' },
              ]"
            />
            <van-field
              v-model="member.mobile"
              label="联系电话"
              type="number"
              required
              :readonly="disabled"
              placeholder="请输入联系电话"
              :rules="[
                { required: true, message: '请填写联系电话' },
                { pattern: phoneReg, message: '请输入正确内容' },
              ]"
            />
            <van-field
              v-model="member.relation"
              label="关系"
              required
              placeholder="请选择关系"
              readonly
              clickable
              @click="disabled ? '' : (member.showPicker = true)"
              :rules="[{ required: true, message: '请选择关系', trigger: 'onChange' }]"
            />
            <van-popup v-model="member.showPicker" position="bottom">
              <van-picker
                show-toolbar
                :columns="relationList"
                @confirm="(value) => onConfirm(value, member)"
                @cancel="member.showPicker = false"
              />
            </van-popup>
          </div>
        </div>
        <div v-for="provide in form.providers" :key="provide.id" class="card">
          <div class="member_title provide">
            <p>赡抚养人信息</p>
            <img
              class="delete_icon"
              src="@/assets/common/delete_icon.png"
              alt=""
              @click="disabled ? '' : delProvider(provide.id)"
            />
          </div>
          <div>
            <van-field
              v-model="provide.name"
              label="姓名"
              required
              :readonly="disabled"
              placeholder="请输入申请人姓名"
              :rules="[{ required: true, message: '请填写姓名' }]"
            />
            <van-field
              v-model="provide.idCard"
              label="身份证"
              required
              :readonly="disabled"
              placeholder="请输入申请人身份证号"
              :rules="[
                { required: true, message: '请填写身份证' },
                { pattern: idcardReg, message: '请输入正确内容' },
              ]"
            />
            <van-field
              v-model="provide.mobile"
              label="联系电话"
              type="number"
              required
              :readonly="disabled"
              placeholder="请输入联系电话"
              :rules="[
                { required: true, message: '请填写联系电话' },
                { pattern: phoneReg, message: '请输入正确内容' },
              ]"
            />
            <van-field
              v-model="provide.relation"
              label="关系"
              required
              placeholder="请选择关系"
              readonly
              clickable
              @click="disabled ? '' : (provide.showPicker = true)"
              :rules="[{ required: true, message: '请选择关系', trigger: 'onChange' }]"
            />
            <van-popup v-model="provide.showPicker" position="bottom">
              <van-picker
                show-toolbar
                :columns="relationList"
                @confirm="(value) => onConfirm(value, provide)"
                @cancel="provide.showPicker = false"
              />
            </van-popup>
          </div>
        </div>
      </van-form>
    </div>
    <div class="foot" v-if="code">
      <van-button block color="#EB4E3F" type="primary" @click="handleEdit"
        >修 改</van-button
      >
    </div>
    <div class="foot">
      <div class="button" @click="submit('save')">
        <img src="@/assets/common/save_icon.png" alt="" />
        <p>保存</p>
      </div>
      <div class="button" @click="submit('next')">
        <img src="@/assets/common/next_icon.png" alt="" />
        <p>下一步</p>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import { Form, Field, Button, Popup, Picker, TreeSelect } from "vant";
import { phoneReg, idcardReg } from "@/utils/constant";
import { getArea, personalAdd, getPersonal, personalUpdate } from "@/api/guarantee";
import { decryptByDES } from "@/utils/utils";

Vue.use(Form).use(Field).use(Button).use(Popup).use(Picker).use(TreeSelect);

let keyId = 1;

export default {
  computed: {
    code() {
      return this.$store.state.guarantee.code;
    },
  },
  data() {
    return {
      identifier: "",
      userInfo: {},
      form: {
        name: "", // 姓名
        idCard: "", // 身份证
        streetName: "", // 所属街道
        street: "", // 所属街道code码
        householdRegister: "", // 户籍地址
        mobile: "", // 联系电话
        reason: "", // 困难原因
        members: [],
        providers: [],
      },
      phoneReg,
      idcardReg,
      relationList: [
        "配偶",
        "子女",
        "父母",
        "兄弟姐妹",
        "（外）祖父母",
        "（外）孙子女",
        "女婿（媳妇）",
        "其他",
      ],
      areaList: [],
      showAreaPicker: false,
      streetCode: "",
      areaIndex: 0,
      street: {},
      type: "save",
      detail: {},
      disabled: false,
    };
  },
  methods: {
    init() {
      getPersonal({ code: this.code }).then((res) => {
        let detail = res[0];
        console.log("detail:", detail);
        // 家庭成员列表
        let members = detail.familyVos.filter((item) => {
          return item.category === 0;
        });
        members = members.map((item) => {
          return {
            id: item.code,
            idCard: item.idCard,
            mobile: item.mobile,
            name: item.name,
            relation: item.relation,
            showPicker: false,
            category: item.category,
          };
        });
        // 赡养人列表
        let providers = detail.familyVos.filter((item) => {
          return item.category === 1;
        });
        providers = providers.map((item) => {
          return {
            id: item.code,
            idCard: item.idCard,
            mobile: item.mobile,
            name: item.name,
            relation: item.relation,
            showPicker: false,
            category: item.category,
          };
        });
        this.form = {
          name: detail.name,
          idCard: detail.idCard,
          streetName: detail.street,
          street: detail.streetCode,
          householdRegister: detail.householdRegister,
          mobile: detail.mobile,
          reason: detail.reason,
          members: members,
          providers: providers,
        };
      });
    },
    handleEdit() {
      this.$dialog
        .confirm({
          message: "修改申请之后，需要全部成员重新授权认证，确定修改吗?",
        })
        .then(() => {
          const { form } = this;
          let familyList = form.members.concat(form.providers).map((item) => {
            return {
              category: item.category,
              idCard: item.idCard.toUpperCase(),
              name: item.name,
              mobile: item.mobile,
              relation: item.relation,
            };
          });
          let params = {
            code: this.code,
            name: form.name,
            idCard: form.idCard,
            street: form.street,
            householdRegister: form.householdRegister,
            mobile: form.mobile,
            reason: form.reason,
            familyList: familyList,
          };
          personalUpdate(params).then(() => {
            this.$toast("修改成功");
            setTimeout(() => {
              this.$router.go(-1);
            }, 1000);
          });
        })
        .catch(() => {
          console.log("取消");
        });
    },
    onSubmit() {
      const { form, type } = this;
      console.log(type);
      let familyList = form.members.concat(form.providers).map((item) => {
        return {
          category: item.category,
          idCard: item.idCard.toUpperCase(),
          name: item.name,
          mobile: item.mobile,
          relation: item.relation,
        };
      });
      let params = {
        name: form.name,
        idCard: form.idCard,
        street: form.street,
        householdRegister: form.householdRegister,
        mobile: form.mobile,
        reason: form.reason,
        familyList: familyList,
      };
      console.log(params);
      personalAdd(params).then((res) => {
        this.$toast("保存成功");
        if (this.type === "save") {
          setTimeout(() => {
            this.$store.commit("guarantee/SET_CODE", res);
            this.$router.go(-1);
          }, 1000);
        } else {
          setTimeout(() => {
            this.$store.commit("guarantee/SET_CODE", res);
            this.$router.replace({
              name: "GuaranteeVerify",
              query: {
                identifier: 2,
              },
            });
          }, 1000);
        }
      });
    },
    addProvider() {
      this.form.providers.push({
        id: keyId,
        idCard: "",
        name: "",
        mobile: "",
        relation: "",
        category: 1,
        showPicker: false,
      });
      keyId = keyId + 1;
    },
    delProvider(id) {
      this.form.providers = this.form.providers.filter((item) => {
        return item.id !== id;
      });
    },
    addMember() {
      this.form.members.push({
        id: keyId,
        idCard: "",
        name: "",
        mobile: "",
        relation: "",
        category: 0,
        showPicker: false,
      });
      keyId = keyId + 1;
    },
    delMember(id) {
      this.form.members = this.form.members.filter((item) => {
        return item.id !== id;
      });
    },
    onConfirm(value, item) {
      item.relation = value;
      item.showPicker = false;
    },
    submit(type) {
      this.type = type;
      this.$refs.reportForm.submit(type);
    },
    areaConfirm() {
      this.form.streetName = this.street.text;
      this.form.street = this.street.id;
      this.street = {};
      this.showAreaPicker = false;
    },
    areaCancle() {
      this.street = {};
      this.streetCode = this.form.street;
      this.showAreaPicker = false;
    },
    initArea() {
      getArea().then((res) => {
        this.areaList = res.map((item) => {
          return {
            text: item.areaName,
            areaCode: item.areaCode,
            children: item.streetVo.map((street) => {
              return {
                text: street.streetName,
                id: street.streetCode,
              };
            }),
          };
        });
      });
    },
  },
  created() {
    let res = sessionStorage.getItem("ZJCD-UserInfo");
    let userInfo = JSON.parse(res);
    this.form.idCard = decryptByDES(userInfo.idCardNo, "MnuYbhGv").toUpperCase();
    this.form.name = userInfo.realName;
    this.identifier = parseInt(this.$route.query.identifier);
    // 存在code的情况下视为修改或者查看
    if (this.code) {
      this.disabled = this.identifier !== 2;
      // 非本人状态下 不可编辑只能查看 identifier !== 2
      // 是本人申请的，但是已经提交的状态下不可编辑 civilVerify !== 1 !== 3
      this.init();
    }
    this.initArea();
  },
};
</script>

<style lang="stylus" scoped>
.applicant {
  height calc(100vh - 90px)
  overflow-y auto

  .title {
    padding 30px;
    display flex;
    align-items center;
    background #ffffff;
    border-bottom 1px solid #eee

    .icon {
      width: 6px;
      height: 32px;
      background: #EB4E3F;
    }

    p {
      margin-left 10px;
      font-size: 32px;
      font-weight: 500;
      color: #333333;
    }
  }
  .main {
    .add-button {
      margin 30px 20px;
      display flex;
      align-items center
    }
    .card {
      margin 0 20px 20px;
      .member_title {
        padding 0 30px;
        height 70px;
        display flex;
        align-items center
        justify-content space-between
        background: rgba(88, 155, 255, 0.2);

        p {
          font-size: 28px;
          font-weight: 500;
          color: #589BFF;
        }

        .delete_icon {
          width 40px;
          height 40px;
        }
      }
      .provide {
        background: rgba(79, 178, 75, 0.2);

        p {
          color: #4FB24B
        }
      }
    }
    .popup_title {
      height 90px;
      padding 0 30px;
      display flex;
      align-items center;
      justify-content space-between
      border-bottom 1px solid #eee
      .confirm {
        font-size 24px;
        color #576b95
      }
      .cancle {
        font-size 24px;
        color #969799
      }
    }
  }
}
.foot {
  display flex;
  align-items center;
  justify-content space-between;

  .button {
    width 48%;
    height 90px;
    display flex;
    align-items center;
    justify-content center;
    background: #EB4E3F

    img {
      width 36px;
      height 36px;
      margin-right: 10px;
    }
    p {
      font-size: 36px;
      font-weight: 500;
      color: #FFFFFF;
    }
  }
}
</style>
