<template>
  <view class="shop-3-container">
    <!-- <u-navbar
      :autoBack="true"
      :safeAreaInsetTop="true"
      :placeholder="true"
      title="资金结算信息"
    >
      <template slot="right">
        <view class="btn-login-out" @click="loginOut">退出登录</view>
      </template>
    </u-navbar> -->
    <navBar
      title="资金结算信息"
      :statusBar="true"
      :border="false"
      :fixed="true"
      :height="'44px'"
    >
      <block slot="left">
        <u-icon
          name="arrow-left"
          color="#303133"
          size="20"
          @click="pageBack()"
        ></u-icon>
      </block>
      <block slot="right">
        <view class="btn-login-out" @click="loginOut">退出登录</view>
      </block>
    </navBar>

    <view class="from1">
      <u-form :model="form" ref="uForm" label-width="90">
        <u-form-item label="" class="bankcard_item">
          <u-upload
            class="bankcard_upload"
            @afterRead="afterRead($event, 'bankCard')"
            @delete="deletePic($event, 'bankCard')"
            accept="image"
            :fileList="bankCardFiles"
            :max-count="1"
            uploadIconColor="#fe4119"
            width="268"
            height="125"
            uploadText="点击上传银行卡正面"
            :maxSize="maxSize"
            @oversize="overSize"
          ></u-upload>
          <view
            v-if="bankCardFiles.length && !form.account_number"
            class="retry_ocr"
            @click="onBankOcrretryClick"
          >
            点击自动识别免填卡号
          </view>
        </u-form-item>

        <template
          v-if="entity_type == 1 || (bankCardFiles.length && bankCardOcrLoaded)"
        >
          <u-form-item label="开户名称" required prop="account_holder_name">
            <u-input
              v-model="form.account_holder_name"
              placeholder="请输入开户名称"
            />
          </u-form-item>

          <u-form-item label="银行卡号" required prop="account_number">
            <u-input
              type="number"
              v-model="form.account_number"
              placeholder="请输入银行卡号"
            />
          </u-form-item>

          <u-form-item
            label="开户银行"
            prop="branch_name"
            @click="onBranchDialogOpen"
            required
          >
            <u-input
              style="pointerevents: 'none'"
              class="form-input"
              v-model="form.branch_name"
              placeholder="请选择开户银行"
              @change="onBranchBankChange"
            />
            <u-icon
              style="display: inline-block; margin-left: 8rpx"
              name="arrow-down"
              size="12"
              color="aaaaaa"
            ></u-icon>
          </u-form-item>
          <view class="tips" @click="showTips = true">
            搜不到我的开户银行，怎么处理
            <u-icon
              class="icon-tips"
              name="question-circle-fill"
              color="#fe4119"
              size="18"
            ></u-icon>
          </view>
        </template>
      </u-form>
    </view>

    <u-popup
      :show="showBankDialog"
      closeable
      @open="onBranchDialogOpen"
      @close="onBranchDialogClose"
    >
      <u-input
        class="search_box"
        prefixIcon="search"
        v-model="branchSearchText"
        placeholder="搜索开户银行关键词"
        @change="onBranchBankChange"
      />
      <view class="branch_list">
        <template v-if="bankList.length">
          <view
            class="branch_list_item"
            v-for="(item, index) in bankList"
            :key="item.id + index"
            @click="onBankSelect(item, $event)"
          >
            {{ item.branch_bank_name }}
          </view>
        </template>
        <view v-else class="nodata">
          <template v-if="firstBranchBankLoad">
            <view class="tit">暂无法搜索到该银行支行</view>
          </template>
          <template v-else>
            <view class="tit">数据加载中...</view>
          </template>
        </view>
      </view>
    </u-popup>

    <view class="btn-content">
      <view class="myui_check_text" v-if="bankCardFiles.length">
        检查并确认结算证件信息无误
      </view>
      <u-button
        text="提交审核"
        color="#fe4119"
        :disabled="!form.account_number"
        @click="handleSubmit"
      ></u-button>
      <u-button
        text="上一步"
        class="myui_btn_prev"
        @click="handlePrev"
      ></u-button>
    </view>

    <u-loading-page
      :loading="loading"
      bgColor="rgba(0,0,0,0.5)"
      fontSize="32rpx"
      color="#fff"
      loadingText="数据正在加载中..."
    ></u-loading-page>

    <u-toast ref="uToast" />
    <u-popup
      :show="showTips"
      :round="10"
      :closeable="true"
      :closeIconPos="'top-right'"
      mode="bottom"
      @close="closeTips"
      @open="openTips"
    >
      <view class="popup-tips">
        <view class="popip-tips-title">提示</view>
        <view class="popip-tips-item">
          如开户地为县级市或乡镇区无法搜索到，可选择相同银行的市级支行网点
        </view>
        <view class="popip-tips-item popip-tips-item-2">
          例如：中国工商银行后加（所在地的县级市/乡镇名称） 中国工商银行桂平市
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import {
  GetMerchApply,
  GetRestartMerchApply,
  branchBankSearchApi,
} from "@/api/audit";
import { batchNoApi, imgOcrResultApi } from "../../api/upload";
import { mapState } from "vuex";
import { throttle, debounce } from "lodash";
import navBar from "@/components/uni-nav-bar/uni-nav-bar";
import { H5compressImg, getBase64Size } from "@/utils/tool.js";

const orcImgTypeConf = {
  FR_ID_CARD_FRONT: "FR_ID_CARD_FRONT",
  FR_ID_CARD_BEHIND: "FR_ID_CARD_BEHIND",
  ID_CARD_FRONT: "ID_CARD_FRONT",
  ID_CARD_BEHIND: "ID_CARD_BEHIND",
  BUSINESS_LICENCE: "BUSINESS_LICENCE",
  BANK_CARD: "BANK_CARD",
};

export default {
  components: {
    navBar,
  },
  data() {
    return {
      form: {
        branch_name: "",
        account_number: "",
        account_holder_name: "",
      },
      bankCardFiles: [],
      loading: false,
      branchSearchText: "",
      entity_type: "",
      bankCardOcrLoaded: false,
      firstBranchBankLoad: false,
      showBankDialog: false,
      branchBankDebounceFn: null,
      currentBank: {},
      currentBankFile: {},
      bankList: [],
      rules: {
        branch_name: [
          {
            required: true,
            message: "请选择银行支行",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
        ],
        account_number: [
          {
            required: true,
            message: "请输入银行卡号",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
        ],
        account_holder_name: [
          {
            required: true,
            message: "请输入开户名称",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
        ],
      },
      limitType: ["png", "jpg", "jpeg"], //允许的图片后缀
      fileMaxSize: 1 * 1024 * 1024, // 超出1M开启压缩
      maxSize: 10 * 1024 * 1024, //图片最大不能超过20M
      fileMinSize: 5 * 1024, // 最小为5KB
      showTips: false,
    };
  },
  computed: {
    ...mapState("user", ["approvalStatus"]),
  },
  onReady() {
    this.$refs["uForm"].setRules(this.rules);
  },
  onShow() {},
  beforeUnmount() {
    this.branchBankDebounceFn?.cancel();
  },
  mounted() {
    let auditItem = uni.getStorageSync("auditItem");
    this.form.account_holder_name =
      auditItem.biz_license_company || auditItem.contact_name;
    this.entity_type = auditItem.entity_type || 1;
    this.branchBankDebounceFn = debounce(this.getBranchBankList, 500);
  },
  methods: {
    pageBack() {
      uni.navigateBack();
    },
    overSize(e) {
      uni.$u.toast("上传图片大小不能超过10MB!");
    },
    compressImage(url) {
      return new Promise((reslove, reject) => {
        const tempFilePath = url; //url是选中图片的路径
        uni.compressImage({
          src: tempFilePath,
          quality: 75, //压缩的程度
          success: (res) => {
            reslove(res.tempFilePath); //压缩成功返回的路径
          },
          fail: (error) => {
            console.log("压缩失败", error);
          },
        });
      });
    },
    getOcrText(filePath, file, type) {
      return new Promise(async (resolve, reject) => {
        this.loading = true;

        //#ifdef APP-PLUS
        filePath = await this.compressImage(filePath);
        //#endif

        // 压缩图片已base64 方式上传

        //#ifdef H5
        filePath = await H5compressImg(filePath, 0.75);

        let size = getBase64Size(filePath);

        console.log("压缩后的大小为：", size);
        //#endif

        const batchNoRes = await batchNoApi(filePath, file, type);
        const batchNo = batchNoRes.batchNo;

        if (!batchNoRes) {
          this.loading = false;
          this.bankCardOcrLoaded = true;
          reject(batchNoRes);
        }
        // 兼容多端的表单数据处理方式
        let formDataStr;
        //#ifdef H5
        const formData = new FormData();
        formData.append("batchNo", batchNo);
        formData.append("imgType", type);
        formDataStr = new URLSearchParams(formData).toString();
        //#endif

        //#ifdef APP-PLUS
        formDataStr = `batchNo=${encodeURIComponent(
          batchNo
        )}&imgType=${encodeURIComponent(type)}`;
        //#endif

        clearTimeout(this.orcTimeout);

        this.orcTimeout = setTimeout(async () => {
          const imgOcrRes = await imgOcrResultApi(formDataStr);

          if (imgOcrRes?.status == 200) {
            this.showBankDialog = true;
            resolve(imgOcrRes?.data);
          } else {
            uni.showToast({
              title: "银行号图片上传错误,请重新上传",
              icon: "error",
              duration: 2000,
            });
            this.form = {
              branch_name: "",
              account_number: "",
              account_holder_name: "",
            };
            this.bankCardFiles = [];
            reject(imgOcrRes);
          }

          clearTimeout(this.orcTimeout);
          this.loading = false;
          this.bankCardOcrLoaded = true;
        }, 2000);
      });
    },

    async setFromItemWithOcr() {
      var ocr = await this.getOcrText(
        this.currentBankFile.path,
        this.currentBankFile.file,
        orcImgTypeConf.BANK_CARD
      );
      this.form.account_number = ocr.card_number;
      this.branchSearchText = ocr.issuer;
      console.log("bankCard", ocr);
    },

    async afterRead(event) {
      var item = event.file;
      const imgUrl = item.url;

      const group = {
        url: imgUrl,
      };

      this.currentBankFile = {
        file: item,
        path: imgUrl,
      };

      this.bankCardFiles.push(group);
      this.setFromItemWithOcr();
    },

    async onBankOcrretryClick() {
      this.setFromItemWithOcr();
    },

    deletePic(e) {
      this.bankCardFiles.splice(0, 1);
      this.form.account_number = "";
      this.form.branch_name = "";
      this.branchSearchText = "";
      this.currentBank = {};
      this.bankCardOcrLoaded = false;
    },

    async getBranchBankList(keyword) {
      let res = await branchBankSearchApi({
        keyword,
        pageNum: 1,
        pageSize: 1000 * 10,
      });

      this.bankList = res.data.items;
      this.firstBranchBankLoad = true;
    },

    handlePrev() {
      uni.navigateBack();
    },

    async handleSubmit() {
      if (this.entity_type == 2 && !this.bankCardFiles.length) {
        this.$refs.uToast.show({
          message: "请上传银行卡正面",
          type: "error",
          duration: 1000,
        });
        return;
      }

      this.$refs.uForm.validate().then(async (valid) => {
        if (valid) {
          let auditItem = uni.getStorageSync("auditItem");
          let params = {
            ...this.form,
            ...auditItem,
            ...this.currentBank,
            email: `${auditItem?.login_mobile}@qq.com`,
          };

          console.log("params", params);

          if (this.approvalStatus == 2) {
            params.id = uni.getStorageSync("auditId");
            let res = await GetRestartMerchApply(params);
            if (res && res.status == 200) {
              uni.removeStorageSync("locationItem");
              uni.removeStorageSync("auditItem");
              uni.removeStorageSync("typeItem");
              uni.removeStorageSync("auditId");
              uni.navigateTo({ url: "/pages/audit/checkAudit" });
            }
          } else {
            let res = await GetMerchApply(params);
            if (res && res.status == 200) {
              uni.removeStorageSync("locationItem");
              uni.removeStorageSync("auditItem");
              uni.removeStorageSync("typeItem");
              uni.removeStorageSync("auditId");
              uni.navigateTo({ url: "/pages/audit/checkAudit" });
            }
          }
        }
      });
    },

    onBankSelect(data) {
      const { district, area, branch_bank_name, branch_bank_no, clear_no } =
        data;
      this.currentBank = {
        bank_district: district,
        bank_area: area,
        bank_name: branch_bank_name,
        openning_bank_code: branch_bank_no,
        clearing_bank_code: clear_no,
      };
      this.form.branch_name = branch_bank_name;
      this.showBankDialog = false;
    },

    onBranchDialogOpen() {
      this.branchBankDebounceFn(this.branchSearchText || "广西桂平银行");
      this.showBankDialog = true;
    },

    onBranchDialogClose() {
      this.showBankDialog = false;
    },

    async onBranchBankChange() {
      this.branchBankDebounceFn(this.branchSearchText);
    },
    closeTips() {
      this.showTips = false;
    },
    openTips() {
      this.showTips = true;
    },
    loginOut() {
      this.$store.dispatch("user/LoginOut");
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
::v-deep .u-form-item__body {
  padding: 0 0 20rpx;
}
::v-deep .u-upload__wrap__preview,
::v-deep .u-upload__button {
  margin: 0;
}

.shop-3-container {
  ::v-deep .tui-dropdownlist-show {
    box-shadow: 1rpx 1rpx 20rpx rgba(100, 100, 100, 0.1);
    border: 1rpx solid rgba(100, 100, 100, 0.1);
    overflow: visible;

    .icon_close {
      position: absolute;
      bottom: -80rpx;
      left: 50%;
      transform: translateX(-50%);
    }
  }

  ::v-deep .u-popup__content__close {
    top: -90rpx;
    right: auto;
    left: 50%;
    transform: translateX(-50%);
    .u-icon__icon {
      color: #fff !important;
      border: 5rpx solid #fff;
      padding: 10rpx;
      font-size: 28rpx !important;
      line-height: 28rpx !important;
      border-radius: 100%;
    }
  }

  .search_box {
    margin: 24rpx;
    background: rgba(238, 238, 238, 0.5);
    border-radius: 100rpx;
    ::v-deep .input-placeholder {
      color: #666 !important;
    }
  }

  .branch_list {
    margin: 0 24rpx;
    height: 500rpx;
    overflow: auto;
    background: #fff;

    .branch_list_item {
      font-size: 28rpx;
      line-height: 28rpx;
      padding: 20rpx;
      border-bottom: 1rpx solid #eee;
    }

    .nodata {
      height: 500rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      font-size: 28rpx;

      .tit {
        color: #666;
        padding-bottom: 80rpx;
      }

      .tips {
        padding: 10rpx 20rpx;
        color: #fff;
        border-radius: 100rpx;
        background: $base-color;
      }
    }
  }

  .u-navbar {
    height: 88rpx;
  }

  .from1 {
    padding: 24rpx 24rpx 0rpx 36rpx;
  }

  .btn-content {
    padding: 30rpx 48rpx 88rpx;
  }

  .btn-submit {
    border-radius: 16rpx;
    background: $base-color;
    color: #fff;
  }

  .btn-login-out {
    font-size: 28rpx;
    color: $base-color;
  }

  .bankcard_upload {
    margin: auto;
    align-items: center;
  }
  ::v-deep .u-form-item__body__right {
    position: relative;
  }
  .retry_ocr {
    padding: 15rpx 24rpx;
    border-radius: 100rpx;
    color: #fff;
    background: rgba(75, 113, 255, 0.95);
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate3d(-50%, -50%, 0);
    font-size: 24rpx;
    line-height: 24rpx;
  }

  .tips {
    display: flex;
    justify-content: center;
    margin: 40rpx;
    font-size: 28rpx;
    color: #909399;

    .icon-tips {
      margin-left: 14rpx;
    }
  }

  .popup-tips {
    padding: 40rpx;
    height: 400rpx;

    .popip-tips-title {
      margin: 0 20rpx 20rpx;
      font-size: 40rpx;
      font-weight: bold;
      text-align: center;
      color: #000;
    }

    .popip-tips-item {
      margin-bottom: 40rpx;
    }

    .popip-tips-item-2 {
      color: #909399;
      font-size: 28rpx;
    }
  }
}
</style>
