<template>
  <div style="height: 100vh">
    <NavHeader
      color="#0687D2"
      title="人才父母惠老关怀申请"
      @back="$router.go(-1)"
    />
    <van-form
      :readonly="type == 'view'"
      @submit="submitFun"
      validate-trigger="onSubmit"
      ref="form"
      scroll-to-error
    >
      <div :class="{ section: type !== 'view', viewSection: type == 'view' }">
        <van-field
          :disabled="type == 'edit' || type == 'continue'"
          v-model="form.name"
          label="姓名"
          required
          placeholder="请填写姓名"
          :rules="[{ required: true, message: '请填写姓名' }]"
        />
        <van-field
          :disabled="type == 'edit' || type == 'continue'"
          v-model="form.phone"
          label="手机号"
          required
          placeholder="请填写手机号"
          :rules="[{ required: true, message: '请填写手机号' }]"
        />
        <van-field
          v-model="form.jurisdiction"
          label="工作单位税务登记所在地的辖区"
          @click="pickerShow('pickerJurisdiction')"
          required
          readonly
          placeholder="请选择工作单位税务登记所在地的辖区"
          :rules="[
            {
              required: true,
              message: '请选择工作单位税务登记所在地的辖区',
              trigger: 'onChange',
            },
          ]"
        />
        <van-field
          required
          label="《镇江市区人才父母惠老关怀服务申请表》"
          :rules="[
            {
              required: true,
              message: '请上传《镇江市区人才父母惠老关怀服务申请表》',
            },
          ]"
        >
          <template #input>
            <van-uploader
              :deletable="type !== 'view'"
              :after-read="afterRead"
              :max-count="1"
              v-model="form.registration"
            />
          </template>
          <template #button v-if="type !== 'view'">
            <span
              @click="
                download(
                  'https://www.smart-zj.cn:55901/image/惠老关怀申请登记表.docx'
                )
              "
              class="down-text"
              >下载申请登记表</span
            >
          </template>
        </van-field>
        <template v-if="showBank">
          <van-field
            v-model="form.openBank"
            label="开户银行"
            required
            placeholder="请填写开户银行"
            :rules="[{ required: true, message: '请填写开户银行' }]"
          />
          <van-field
            v-model="form.bankAccount"
            label="银行账号"
            required
            placeholder="请填写银行账号"
            :rules="[{ required: true, message: '请填写银行账号' }]"
          />
        </template>
        <div
          class="parent-info"
          v-for="(ele, index) in form.parentList"
          :key="index"
          v-show="ele.isShow"
        >
          <van-icon
            v-if="index > 0 && type !== 'view' && type !== 'continue'"
            @click="deleteParentList(index)"
            name="close"
            color="#ff0000"
            class="info-close"
          />
          <van-field
            v-model="ele.parentName"
            label="父母姓名"
            required
            placeholder="请填写父母姓名"
            :rules="[{ required: true, message: '请填写父母姓名' }]"
          />
          <van-field
            v-model="filterDis[ele.discount]"
            required
            readonly
            @click="pickerShow('pickerParentDiscount', ele)"
            label="惠老类型"
            placeholder="请选择惠老类型"
            :rules="[
              {
                required: true,
                message: '请选择惠老类型',
              },
            ]"
          />
          <van-field
            v-model="filterType[ele.parentType]"
            label="关系"
            required
            readonly
            @click="pickerShow('pickerParentType', ele)"
            placeholder="请填写与您的关系"
            :rules="[
              {
                required: true,
                message: '请填写与您的关系',
              },
            ]"
          />
          <van-field
            v-model="ele.parentAge"
            required
            readonly
            @click="pickerShow('pickerParentAge', ele)"
            label="年龄"
            placeholder="请填写父母年龄"
            :rules="[
              {
                required: true,
                message: '请填写父母年龄',
              },
            ]"
          />
          <van-field
            v-model="ele.idCard"
            required
            label="身份证号码"
            placeholder="请填写父母身份证号码"
            :rules="[{ required: true, message: '请填写父母身份证号码' }]"
          />
          <!-- 新增 start  居家养老上门服务申请模块 -->
          <template v-if="ele.discount === 1">
            <van-field
              v-model="ele.serviceAddress"
              label="上门服务地址"
              required
              placeholder="请填写上门服务地址(具体到门牌号)"
              :rules="[{ required: true, message: '请填写上门服务地址' }]"
            />
          </template>
          <!-- 居家  end -->
          <!-- 新增start   入住养老机构补贴模块 -->
          <template v-if="ele.discount === 2">
            <van-field
              v-model="ele.subsidyAmount"
              label="补贴额度"
              placeholder="请填写补贴额度"
            />
            <van-field
              v-model="ele.institution"
              label="现入住养老机构名称"
              required
              placeholder="请填写现入住养老机构名称"
              :rules="[{ required: true, message: '请填写现入住养老机构名称' }]"
            />
            <van-field
              required
              label="与养老机构签订的入住协议或合同"
              :rules="[
                {
                  required: true,
                  message: '请上传与养老机构签订的入住协议或合同',
                },
              ]"
            >
              <template #input>
                <van-uploader
                  accept=".pdf,.docx,.doc"
                  :deletable="type !== 'view'"
                  :max-count="1"
                  :after-read="afterRead"
                  v-model="ele.agreement"
                  @click-preview="previewAll(ele.agreement)"
                />
              </template>
            </van-field>
          </template>
          <!-- 新增end -->
          <van-field
            required
            label="身份证照片(个人信息页)正面"
            :rules="[
              {
                required: true,
                message: '请上传身份证照片(个人信息页)正面',
              },
            ]"
          >
            <template #input>
              <van-uploader
                :deletable="type !== 'view'"
                :after-read="afterRead"
                :max-count="1"
                v-model="ele.idCardPicture"
              />
            </template>
          </van-field>
          <van-field
            required
            label="身份证照片(个人信息页)反面"
            :rules="[
              {
                required: true,
                message: '请上传身份证照片(个人信息页)反面',
              },
            ]"
          >
            <template #input>
              <van-uploader
                :deletable="type !== 'view'"
                :after-read="afterRead"
                :max-count="1"
                v-model="ele.idCardThePicture"
              />
            </template>
          </van-field>
          <!--类型、关系、年龄弹窗-->
          <van-popup v-model="ele.pickerParentAge" position="bottom">
            <van-picker
              title="年龄"
              :columns="age"
              @confirm="
                (value) =>
                  onConfirmArr(ele, value, 'parentAge', 'pickerParentAge')
              "
              show-toolbar
              @cancel="ele.pickerParentAge = false"
            />
          </van-popup>
          <van-popup v-model="ele.pickerParentDiscount" position="bottom">
            <van-picker
              title="惠老类型"
              :columns="server"
              @confirm="
                (value) =>
                  onConfirmArr(
                    ele,
                    value,
                    'discount',
                    'pickerParentDiscount',
                    1
                  )
              "
              show-toolbar
              @cancel="ele.pickerParentDiscount = false"
            />
          </van-popup>
          <van-popup v-model="ele.pickerParentType" position="bottom">
            <van-picker
              title="关系"
              :columns="parentTypeOption"
              @confirm="
                (value) =>
                  onConfirmArr(ele, value, 'parentType', 'pickerParentType', 1)
              "
              show-toolbar
              @cancel="ele.pickerParentType = false"
            />
          </van-popup>
        </div>
        <div
          class="more-parent"
          v-if="
            form.parentList.length <= 1 &&
            type !== 'view' &&
            type !== 'continue'
          "
        >
          <van-button
            type="primary"
            icon="plus"
            color="#0687D2"
            size="small"
            @click="addParentInfo"
            >继续添加父母信息</van-button
          >
        </div>
        <van-popup v-model="pickerJurisdiction" position="bottom" round>
          <van-cascader
            v-model="cascaderValue"
            title="工作单位税务登记所在地的辖区"
            :options="jurisdictionOptions"
            @close="pickerJurisdiction = false"
            @finish="onMattersFinish"
          />
        </van-popup>
      </div>
      <van-button
        block
        color="#0687D2"
        native-type="submit"
        v-if="type !== 'view'"
      >
        提交
      </van-button>
    </van-form>
  </div>
</template>
<script>
import NavHeader from "@/components/NavHeader";
import Vue from "vue";
import {
  Form,
  Field,
  Popup,
  Picker,
  Uploader,
  Button,
  Icon,
  Cascader,
} from "vant";
import { uploadFile } from "@/api/talents";
import { get } from "@/api/talents";
import {
  mattersGet,
  mattersParentUpdate,
  mattersParentAdd,
  mattersSuperAdditionParent,
  mattersArea,
} from "@/api/policy";
import { decryptByDES } from "@/utils/utils";

Vue.use(Form)
  .use(Field)
  .use(Popup)
  .use(Picker)
  .use(Uploader)
  .use(Button)
  .use(Icon)
  .use(Cascader);

export default {
  components: { NavHeader },
  name: "policy-care-add",
  data() {
    return {
      form: {
        matterType: 4, // 人才父母关怀
        name: "", // 姓名
        userId: null, // 用户id
        talentCode: null, // 人才吗code
        phone: null, // 手机号
        guideId: null, // 事项id
        departmentCode: null, // 部门id
        areaCode: "", // 区域code
        streetCode: "", // 街道code
        registration: [], // 镇江市区人才父母惠老关怀申请表
        openBank: "", // 开户银行
        bankAccount: "", // 银行账号
        // 入住养老服务补贴类型的参数
        parentList: [
          // 父母信息列表
          {
            isShow: true, // 继续追加判断标识
            id: 1,
            jurisdiction: "", // 辖区
            parentName: null, // 父母名字
            parentAge: null, // 父母年龄
            parentType: null,
            idCard: null, // 身份证号码
            discount: null, // 服务类型
            idCardThePicture: [], // 身份证照片正反面
            idCardPicture: [],
            // 居住上门养老字段
            serviceAddress: "", // 上门服务地址
            // 入住养老字段
            subsidyAmount: "", // 补贴金额
            institution: "", // 入住养老机构名称
            agreement: [], // 与养老机构签订的入驻协议或合同
            // 控制选择框
            pickerParentAge: false,
            pickerParentType: false,
            pickerParentDiscount: false,
          },
        ],
      },
      showBank: false, // 是否展示银行信息
      userInfo: null,
      //  工作单位税务登记所在地的辖区
      cascaderValue: "",
      jurisdictionOptions: [],
      pickerJurisdiction: false,
      // 关系vmodel展示
      filterType: {
        1: "父亲",
        2: "母亲",
        3: "配偶父亲",
        4: "配偶母亲",
      },
      // 类型vmodel展示
      filterDis: {
        1: "居住养老上门服务",
        2: "入住养老机构服务补贴",
      },
      parentTypeOption: [
        { text: "父亲", value: 1, disabled: false },
        { text: "母亲", value: 2, disabled: false },
        { text: "配偶父亲", value: 3, disabled: false },
        { text: "配偶母亲", value: 4, disabled: false },
      ],
      // 用于重置关系用，省去遍历操作
      ogTypeList: [
        { text: "父亲", value: 1, disabled: false },
        { text: "母亲", value: 2, disabled: false },
        { text: "配偶父亲", value: 3, disabled: false },
        { text: "配偶母亲", value: 4, disabled: false },
      ],
      server: [
        {
          value: 1,
          text: "居住养老上门服务",
        },
        {
          value: 2,
          text: "入住养老机构服务补贴",
        },
      ],
      type: "add", //add新增、edit修改、view查看、continue继续追加
    };
  },
  computed: {
    age() {
      let arr = [];
      for (let i = 60; i < 130; i++) {
        arr.push(i);
      }
      return arr;
    },
  },
  watch: {
    "form.parentList": {
      immediate: true,
      deep: true,
      handler(val, old) {
        console.log("查看类型变化", val, old);
        // 判断是否展示银行信息
        this.chargeShowBank(val);
        // 当是1个以上的信息时做限制操作
        if (val.length > 1) {
          this.chargeData(val);
        } else {
          // 重置关系数组
          this.parentTypeOption = this.ogTypeList;
        }
      },
    },
  },
  methods: {
    onMattersFinish({ selectedOptions }) {
      this.form.areaCode = selectedOptions[0].value;
      localStorage.setItem("areaCode", this.form.areaCode);
      this.form.streetCode = selectedOptions[1].value;
      localStorage.setItem("streetCode", this.form.streetCode);
      this.pickerJurisdiction = false;
      this.form.jurisdiction = selectedOptions
        .map((option) => option.text)
        .join("/");
    },
    // 判断是否展示银行信息
    chargeShowBank(data) {
      let count = 0;
      if (data && data.length > 0) {
        data.map((res) => {
          // isShow字段判断是否有隐藏展示、页面展示只针对于全展示内容
          if (res.discount == 2 && res.isShow == true) {
            count = 1;
          }
        });
      }
      if (count) {
        this.showBank = true;
      } else {
        this.showBank = false;
      }
    },
    // 去除银行信息、提交时候判断
    clearBankInfo(data) {
      let count = 0;
      data.parentList.map((res) => {
        if (res.discount == 2) {
          count = 1;
        }
      });
      // 全部是居住的类型去除银行信息、其余保持不变
      if (!count) {
        data.openBank = "";
        data.bankAccount = "";
      }
      return data;
    },
    // 打开弹窗
    pickerShow(name, item) {
      if (this.type == "view") {
        return false;
      } else {
        if (item) {
          if (name == "pickerParentType") {
            item.parentType = "";
          }
          item[name] = true;
        } else {
          this[name] = true;
        }
      }
    },
    // 查看pdf
    previewAll(item) {
      if (item && item.length > 0) {
        let url = item[0].url;
        if (url.indexOf("doc") != -1 || url.indexOf("pdf") != -1) {
          this.download(item[0].url);
        } else {
          return;
        }
      } else {
        return;
      }
    },
    // 限制操作
    chargeData(val) {
      let arr = [];
      let garr = [];
      let darr = [];
      val.map((res) => {
        if (res.discount) {
          arr.push(Number(res.discount));
        }
        if (res.parentType) {
          garr.push(Number(res.parentType));
        }
      });
      if (garr.length == 0) {
        darr = [];
      } else if (arr.includes(1)) {
        if (garr.includes(1) || garr.includes(2)) {
          darr = [1, 2];
        } else {
          darr = [3, 4];
        }
      } else if (arr.includes(2)) {
        darr = garr;
      }
      console.log(darr);
      let newData = JSON.parse(JSON.stringify(this.parentTypeOption));
      newData.map((res) => {
        if (darr.includes(res.value)) {
          res.disabled = true;
        } else {
          res.disabled = false;
        }
      });
      this.parentTypeOption = newData;
    },
    // 提交按钮操作
    submitFun() {
      let params = JSON.parse(JSON.stringify(this.form));
      console.log("params-----------", params);
      params.registration = params.registration[0].url; // 镇江市区人才父母惠老关怀申请表
      params.areaCode = localStorage.getItem("areaCode");
      params.streetCode = localStorage.getItem("streetCode");
      // 判断是否去除银行卡号等信息
      this.clearBankInfo(params);
      // 只需要对应展示的父母关系
      params.parentList = params.parentList.filter((res) => {
        return res.isShow == true;
      });
      params.parentList.forEach((element) => {
        // 去除多余字段
        delete element.id;
        delete element.basicCode;
        delete element.pickerParentAge;
        delete element.pickerParentDiscount;
        delete element.pickerParentType;
        delete element.isShow;
        delete element.openBank;
        delete element.bankAccount;
        // 重构图片
        element.idCardPicture = element.idCardPicture[0].url; // 反面
        element.idCardThePicture = element.idCardThePicture[0].url; // 正面
        // 居住清空入住字段
        if (element.discount == 1) {
          element.agreement = "";
          element.subsidyAmount = "";
          element.institution = "";
        }
        // 入住清空居住字段
        if (element.discount == 2) {
          element.serviceAddress = "";
          element.agreement = element.agreement[0].url; // 与入住养老机构签订
        }
      });
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "提交中...",
      });
      let fun =
        this.type == "add"
          ? mattersParentAdd
          : this.type == "continue"
          ? mattersSuperAdditionParent
          : mattersParentUpdate;
      if (this.type == "edit") {
        let editParam = {};
        editParam.code = this.$route.query.code;
        editParam.areaCode = params.areaCode;
        editParam.streetCode = params.streetCode;
        editParam.registration = params.registration;
        editParam.openBank = params.openBank;
        editParam.bankAccount = params.bankAccount;
        editParam.parentList = params.parentList;
        params = editParam;
      }
      console.log(JSON.stringify(params));
      fun({ appId: "1234", ...params }).then((res) => {
        if (res) {
          this.$toast("操作成功");
          setTimeout(() => {
            this.$router.go(-1);
          }, 500);
        } else {
          this.$toast("操作失败");
        }
      });
    },
    // 删除父母信息
    deleteParentList(index) {
      this.form.parentList.splice(index, 1);
    },
    //下载 镇江市区人才父母惠老关怀服务申请登记表
    download(url) {
      console.log("url--", url);

      if (window.android !== undefined) {
        window.android.downLoadFile(url);
      } else {
        window.webkit &&
          window.webkit.messageHandlers.downLoadFile.postMessage(
            `${url}|showNav`
          );
      }
    },
    // 增加父母信息
    addParentInfo() {
      this.form.parentList.push({
        isShow: true,
        id: 2,
        jurisdiction: "", // 辖区
        parentName: null, // 父母名字
        parentAge: null, // 父母年龄
        parentType: null,
        idCard: null, // 身份证号码
        discount: null, // 服务类型
        idCardThePicture: [], // 身份证照片正反面
        idCardPicture: [], // 身份证照片正反面
        // 居住上门养老字段
        serviceAddress: "", // 上门服务地址
        // 入住养老字段
        subsidyAmount: "", // 补贴金额
        institution: "", // 入住养老机构名称
        agreement: [], // 与养老机构签订的入驻协议或合同
        // 控制选择框
        pickerParentAge: false,
        pickerParentType: false,
        pickerParentDiscount: false,
      });
    },
    // 年龄、关系、类型选择确认
    onConfirmArr(ele, value, name, pickerName, type) {
      ele[name] = type == 1 ? value.value : value;
      ele[pickerName] = false;
      if (name == "discount") {
        // 每次选择类型清空所有的关系
        ele.parentType = "";
        // 入住获取补贴
        if (value.value == 2) {
          this.getButie(ele);
        }
      }
    },
    afterRead(file) {
      file.status = "uploading";
      file.message = "上传中...";
      let param = new FormData();
      param.append("file", file.file);
      uploadFile(param)
        .then((res) => {
          file.status = "done";
          file.message = "上传成功";
          file.url = res;
        })
        .catch((/*err*/) => {
          file.status = "failed";
          file.message = "上传失败";
        });
    },
    // 获取补贴
    getButie(item) {
      get({ appId: "1234", talentCode: this.form.talentCode, idCard: this.userInfo.idCardNo ? decryptByDES(this.userInfo.idCardNo, "MnuYbhGv") : null }).then((res) => {
        if (res && res.categoryName) {
          if (res.categoryName == "A") {
            item.subsidyAmount = 2000;
          } else if (res.categoryName == "B") {
            item.subsidyAmount = 800;
          } else if (res.categoryName == "C") {
            item.subsidyAmount = 600;
          } else if (res.categoryName == "D") {
            item.subsidyAmount = 400;
          } else if (res.categoryName == "E") {
            item.subsidyAmount = 200;
          } else {
            item.subsidyAmount = "";
          }
        } else {
          item.subsidyAmount = "";
        }
      });
    },
    // 初始化数据
    initData() {
      mattersGet({
        appId: "1234",
        code: this.$route.query.code,
        matterType: 4,
      }).then((res) => {
        res.data.registration = [{ url: res.data.registration }];
        res.data.parentList.map((item) => {
          if (this.type == "continue") {
            item.isShow = false;
          } else {
            if (res.data.code == item.basicCode) {
              item.isShow = true;
            } else {
              item.isShow = false;
            }
          }
          item.idCardPicture = [{ url: item.idCardPicture }];
          item.idCardThePicture = [{ url: item.idCardThePicture }];
          if (item.discount == 2) {
            item.agreement = [{ url: item.agreement }];
          } else {
            item.agreement = [];
          }
          item.pickerParentAge = false;
          item.pickerParentType = false;
          item.pickerParentDiscount = false;
        });
        res.data.jurisdiction = res.data.areaName + "/" + res.data.streetName;
        this.form = res.data;
        console.log(this.form);
        if (this.type == "continue") {
          this.form.registration = [];
          this.addParentInfo();
        }
      });
    },
  },
  created() {
    mattersArea({ appId: "1234", pageNum: 1, pageSize: 10 }).then((res) => {
      res.list = JSON.parse(
        JSON.stringify(res.list)
          .replace(/areaCode/g, "value")
          .replace(/areaName/g, "text")
          .replace(/streetName/g, "text")
          .replace(/streetCode/g, "value")
          .replace(/streetVOS/g, "children")
      );
      this.jurisdictionOptions = res.list;
    });
    let res = sessionStorage.getItem("ZJCD-UserInfo");
    this.userInfo = JSON.parse(res) || {};
    this.form.name = this.userInfo.realName;
    this.form.phone = this.userInfo.mobileNo;
    this.form.userId = this.userInfo.userId;
    this.form.departmentCode = this.$route.query.departmentCode;
    this.form.guideId = this.$route.query.guideId;
    this.form.talentCode = this.$route.query.talentCode;
    this.type = this.$route.query.type;
    if (this.type !== "add") {
      this.initData();
    }
  },
};
</script>
<style lang="stylus" scoped>
.van-uploader__upload input
  margin: 0
  padding: 0
  width: 100%
.section
  height: calc(100vh - 176px)
  overflow-y: auto
.viewSection
  height: calc(100vh - 90px)
  overflow-y: auto
.parent-info
  margin: 30px 0 5px
  position: relative
  .info-close
    position: absolute !important
    right: 1px
    font-size: 60px
    top: -30px
    z-index: 222
.more-parent
  display: flex
  justify-content: center
  margin: 30px auto
.down-text
  font-size: 20px
  color: #6077e8
</style>
