<template>
  <!-- <div class="applyLoanForm">applyLoanForm</div> -->
  <div class="applyLoanForm">
    <view>
      <uni-forms
        class="form"
        ref="form"
        :model="form"
        :rules="rules"
        label-position="top"
        label-width="100%"
        validate-trigger="bind"
      >
        <uni-forms-item label="贷款产品" name="loanProductId">
          <uni-data-select
            v-model="form.loanProductId"
            :localdata="allLoanProduct"
            placeholder="请选择贷款产品"
          />
        </uni-forms-item>
        <uni-forms-item label="经营主体" name="baseinfoId">
          <uni-data-select
            v-model="form.baseinfoId"
            :localdata="listBaseInfo"
            placeholder="请选择经营主体"
          />
        </uni-forms-item>
        <uni-forms-item label="申请用户姓名" name="loanUserName">
          <uni-easyinput
            v-model="form.loanUserName"
            placeholder="请输入申请用户姓名"
          />
        </uni-forms-item>
        <uni-forms-item label="申请用户身份证" name="loanUserCard">
          <uni-easyinput
            v-model="form.loanUserCard"
            placeholder="请输入申请用户身份证"
          />
        </uni-forms-item>
        <uni-forms-item label="申请用户电话" name="loanUserTel">
          <uni-easyinput
            v-model="form.loanUserTel"
            placeholder="请输入申请用户电话"
          />
        </uni-forms-item>
        <uni-forms-item label="贷款金额(万元)" name="loanLimit">
          <uni-number-box
            v-model="form.loanLimit"
            placeholder="请输入贷款金额(万元)"
          />
        </uni-forms-item>
        <uni-forms-item label="上报时间" name="registrationTime">
          <uni-datetime-picker
            type="date"
            placeholder="请选择上报时间"
            v-model="form.registrationTime"
          />
        </uni-forms-item>
        <uni-forms-item label="申请资料附件" name="fileUrl">
          <uni-file-picker
            fileMediatype="all"
            limit="5"
            title="上传文件数量不能超过 5 个"
            v-model="fileUrl"
            @progress="progress"
            @select="select"
          />
        </uni-forms-item>
        <uni-forms-item label="描述" name="remark">
          <uni-easyinput v-model="form.remark" placeholder="请输入描述" />
        </uni-forms-item>
      </uni-forms>

      <view style="height: 44px">
        <button v-if="false">
          <text>{{ "测 试" }}</text>
        </button>
      </view>
    </view>

    <view v-if="true" class="foot">
      <button @click="cencel" :plain="false" class="cencel">
        <text>{{ "取 消" }}</text>
      </button>
      <!-- <button @click="text" type="primary" class="confirm"> -->
      <button @click="showConfirm" type="primary" class="confirm">
        <text>{{ "确 认" }}</text>
      </button>
    </view>
  </div>
</template>

<script>
import {
  listLoanUserApply,
  getLoanUserApply,
  delLoanUserApply,
  addLoanUserApply,
  updateLoanUserApply,
} from "@/api/financialCredit/loanUserApply";
import { getAllLoanProduct } from "@/api/financialCredit/loanProduct";
import { selectUserEntity } from "@/api/enterprise/userEntity";

export default {
  name: "applyLoanForm",
  components: {},
  props: {},
  data() {
    /**
     * 手机号码格式验证
     * @param rule 验证规则
     * @param value 需要验证的值
     * @param callback 回调函数
     */
    const validateMobile = (rule, value, callback) => {
      return new Promise((resolve, reject) => {
        var reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
        if (!reg.test(value)) {
          reject(new Error("手机号格式错误"));
        } else {
          resolve();
        }
      });
    };
    /**
     * @description : 校验身份证号是否合规（18位、15位）
     * @param        {String|Number} value
     * @return       {Boolean} true-合规 false-不合规
     */
    const checkPsidno = (rule, value, callback) => {
      return new Promise((resolve, reject) => {
        const psidno = String(value);
        // 1.校验身份证号格式和长度
        const regPsidno =
          /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[X])$)$/;
        if (!regPsidno.test(psidno)) {
          reject(new Error("身份证号格式错误"));
        }
        // 2.校验前两位的省份编码是否正确
        const province = {
          11: "北京",
          12: "天津",
          13: "河北",
          14: "山西",
          15: "内蒙古",
          21: "辽宁",
          22: "吉林",
          23: "黑龙江 ",
          31: "上海",
          32: "江苏",
          33: "浙江",
          34: "安徽",
          35: "福建",
          36: "江西",
          37: "山东",
          41: "河南",
          42: "湖北 ",
          43: "湖南",
          44: "广东",
          45: "广西",
          46: "海南",
          50: "重庆",
          51: "四川",
          52: "贵州",
          53: "云南",
          54: "西藏 ",
          61: "陕西",
          62: "甘肃",
          63: "青海",
          64: "宁夏",
          65: "新疆",
          71: "台湾",
          81: "香港",
          82: "澳门",
          91: "国外",
        };
        if (!province[Number(psidno.slice(0, 2))]) {
          reject(new Error("身份证号格式错误"));
        }
        // 3.校验出生日期
        if (psidno.length === 15) {
          // 15位号码 省（2位）市（2位）县（2位）年（2位）月（2位）日（2位）校验码（3位）
          const reg = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
          const arrSplit = psidno.match(reg);
          // 15位号码在年份前补 19 或 20
          const year =
            Number(arrSplit[2].charAt(0)) > 0
              ? "19" + arrSplit[2]
              : "20" + arrSplit[2];
          const month = arrSplit[3];
          const day = arrSplit[4];
          if (!validateBirthday(year, month, day)) {
            reject(new Error("身份证号格式错误"));
          }
        } else if (psidno.length === 18) {
          // 18位号码 省（2位）市（2位）县（2位）年（4位）月（2位）日（2位）校验码（4位）
          const reg = new RegExp(
            /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/
          );
          const arrSplit = psidno.match(reg);
          const year = arrSplit[2];
          const month = arrSplit[3];
          const day = arrSplit[4];
          if (!validateBirthday(year, month, day)) {
            reject(new Error("身份证号格式错误"));
          }
        } else {
          reject(new Error("身份证号格式错误"));
        }
        // 校验出生日期是否合理
        function validateBirthday(year, month, day) {
          year = Number(year); // 年
          month = Number(month); // 月
          day = Number(day); // 日
          const nowTime = new Date().getTime(); // 当前时间戳
          const birthTime = new Date(`${year}-${month}-${day}`).getTime(); // 获取出生日期的时间戳
          // 不能是明天出生的吧
          if (birthTime > nowTime) {
            return false;
          }
          // 一般人活不到150岁吧
          const nowYear = new Date().getFullYear();
          if (nowYear - year > 150) {
            return false;
          }
          // 不能是13月出生的吧
          if (month < 1 || month > 12) {
            return false;
          }
          // 不能是2月30号、4月31号、5月32号出生的吧
          const date = new Date(year, month, 0); // 获取当月的最后一天
          if (day < 1 || day > date.getDate()) {
            return false;
          }
          return true;
        }
        // 4.18位号码校验生成的校验码
        if (psidno.length === 18) {
          const Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; // 加权因子
          const parity = [
            "1",
            "0",
            "X",
            "9",
            "8",
            "7",
            "6",
            "5",
            "4",
            "3",
            "2",
          ]; // 校验码
          let sum = 0;
          for (let i = 0; i < 17; i++) {
            sum += Number(psidno.charAt(i)) * Wi[i];
          }
          if (parity[sum % 11] !== psidno[17]) {
            reject(new Error("身份证号格式错误"));
          }
        }
        resolve();
      });
    };
    return {
      loading: false,
      // haveEnterprise: false,
      fileUrl: [],
      allLoanProduct: [],
      listBaseInfo: [],
      businessLicenseUrl: [],
      landmarkType: [],
      form: {
        loanLimit: 0,
      },
      dictLists: {},
      rules: {
        // fullName: {
        //   rules: [
        //     {
        //       required: true,
        //       errorMessage: "请输入主体名称",
        //     },
        //   ],
        // },
        loanProductId: {
          rules: [
            {
              required: true,
              errorMessage: "保险产品不能为空",
            },
          ],
        },
        baseinfoId: {
          rules: [
            {
              required: true,
              errorMessage: "经营主体不能为空",
            },
          ],
        },
        loanUserTel: {
          rules: [
            {
              required: true,
              errorMessage: "请输入联系电话",
              validateFunction: (rule, value, data, callback) =>
                validateMobile(rule, value, data, callback),
            },
          ],
        },
        loanUserCard: {
          rules: [
            {
              required: true,
              errorMessage: "请输入身份证号",
              validateFunction: (rule, value, data, callback) =>
                checkPsidno(rule, value, data, callback),
            },
          ],
        },
      },
      address: "",
      options: {},
    };
  },
  computed: {},
  methods: {
    async getRouter(options) {
      this.$set(this.form, "loanProductId", parseInt(options.loanProductId));
      this.$set(this.form, "baseinfoId", parseInt(options.baseinfoId));
      this.$set(this.options, "id", parseInt(options.id));
    },
    text() {
      console.log(this.form);
    },
    reset() {
      this.form = {
        id: null,
        loanUser: null,
        baseinfoId: null,
        loanProductId: null,
        loanUserName: null,
        loanUserCard: null,
        loanUserTel: null,
        loanLimit: 0,
        reportTime: null,
        fileUrl: null,
        status: 0,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
    },
    listallBaseInfo() {
      selectUserEntity().then((response) => {
        const list = response.data;
        let dataList = [];
        for (const item of list) {
          let element = {};
          element["value"] = item.value;
          element["text"] = item.label;
          dataList.push(element);
        }
        this.listBaseInfo = dataList;
      });
    },
    getallLoanProduct() {
      getAllLoanProduct().then((response) => {
        const list = response.data;
        let dataList = [];
        for (const item of list) {
          let element = {};
          element["value"] = item.id;
          element["text"] = item.loanCommodity;
          dataList.push(element);
        }
        this.allLoanProduct = dataList;
      });
    },
    authenticationUrlSucces() {},
    async initializeDict() {
      this.dictByType("sys_yes_no");
    },
    dictByType(type) {
      this.getDicts(type).then((response) => {
        let dicts = [];
        for (let dict of response.data) {
          let element = {};
          element["value"] = dict.dictValue;
          element["text"] = dict.dictLabel;
          element["label"] = dict.dictLabel;
          dicts.push(element);
        }
        this.$set(this.dictLists, type, dicts);
      });
    },
    select(tempFiles) {
      let urls = [];
      for (const item of tempFiles.tempFilePaths) {
        // urls.push(tempFiles.tempFilePaths);
        urls.push(item);
      }
      this.form.fileUrl = urls;
      this.fileUrl = urls;
    },
    naviBack(isNew) {
      console.log(isNew);
      let pages = getCurrentPages(); //关于获取页面的官方文档https://uniapp.dcloud.io/api/window/window
      let prevPage = pages[pages.length - 2];
      uni.navigateBack({
        delta: 1,
        success: () => {
          if (isNew !== undefined) {
            setTimeout(function () {
              prevPage.$vm.getMsg(isNew);
            }, 200);
          }
        },
      });
    },
    cencel() {
      this.naviBack();
    },
    submitForm() {
      let form = this.form;
      let isNew =
        this.form.id === null ||
        this.form.id === undefined ||
        this.form.id === "";
      if (
        form.fileUrl === undefined ||
        form.fileUrl === [] ||
        form.fileUrl === null ||
        form.fileUrl.length === 0
      ) {
        this.form.fileUrl = "";
      } else {
        this.form.fileUrl = form.fileUrl.toString(",");
      }
      if (isNew) {
        addLoanUserApply(this.form)
          .catch((err) => {
            this.naviBack(err);
          })
          .then((response) => {
            this.naviBack(isNew);
          });
      } else {
        updateLoanUserApply(this.form)
          .catch((err) => {
            this.naviBack(err);
          })
          .then((response) => {
            this.naviBack(isNew);
          });
      }
    },
    getLoanUserApplyById() {
      this.$modal.loading("加载中，请耐心等待...");
      getLoanUserApply(this.options.id).then((response) => {
        console.log(response);
        this.form = response.data;
        this.$modal.closeLoading();
      });
    },
    showConfirm() {
      this.$refs["form"].validate().then((res) => {
        this.$cus_modal.confirm().then((conf_res) => {
          if (conf_res.confirm === true) {
            this.submitForm();
          }
        });
      });
    },
  },
  watch: {},

  // 页面周期函数--监听页面加载
  onLoad(options) {
    this.reset();
    this.getRouter(options).then(() => {
      console.log("=================options=====================");
      console.log(options);
      console.log("=================this.options=====================");
      console.log(this.options);
      if (options.id != undefined) {
        this.getLoanUserApplyById();
      }
    });
    this.initializeDict();
    this.getallLoanProduct();
    this.listallBaseInfo();
  },
  // 页面周期函数--监听页面初次渲染完成
  onReady() {},
  // 页面周期函数--监听页面显示(not-nvue)
  onShow() {},
  // 页面周期函数--监听页面隐藏
  onHide() {},
  // 页面周期函数--监听页面卸载
  onUnload() {
    const that = this
    return that.$listenOB.goBack()
  },
  // 页面处理函数--监听用户下拉动作
  // onPullDownRefresh() { uni.stopPullDownRefresh(); },
  // 页面处理函数--监听用户上拉触底
  // onReachBottom() {},
  // 页面处理函数--监听页面滚动(not-nvue)
  // onPageScroll(event) {},
  // 页面处理函数--用户点击右上角分享
  // onShareAppMessage(options) {},
};
</script>

<style lang="scss" scoped>
page {
  background: white;
}

.form {
  text-align: center;
  margin: auto;
  width: 80%;
}

.applyLoanForm {
  background-color: white;
  height: calc(100%);

  /deep/ .uni-forms-item {
    .uni-forms-item__content {
      .uni-file-picker {
        .uni-file-picker__header {
          .file-title {
            span {
              color: #ff0000a6;
            }
          }
        }
      }

      .uni-mt-5 {
        .uni-icons {
          background: #007aff21;
          line-height: 35px;
          height: 35px;
        }
      }

      .uni-select-cy {
        z-index: 1;

        .uni-select-cy-select {
          z-index: -500;
        }
      }
    }
  }

  .foot {
    width: 100vw;
    height: 44px;
    bottom: 0px;
    display: flex;
    position: fixed;
    z-index: 2;
    .cencel {
      border-radius: 0px;
      border: 0px;
      width: 50%;
      background-color: white;
    }

    .confirm {
      border-radius: 0px;
      border: 0px;
      width: 50%;
      color: white;
    }
  }
}
</style>