<template>
  <view class="shop-3-container">
    <u-navbar :autoBack="true" :safeAreaInsetTop="true" title="资金结算信息">
      <template slot="right">
        <view class="btn-login-out" @click="loginOut">退出登录</view>
      </template>
    </u-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="#4b71ff"
            width="268"
            height="125"
            uploadText="点击上传银行卡正面"
          >
          </u-upload>
          <view
            v-if="bankCardFiles.length && !form.account_number"
            class="retry_ocr"
            @click="onBankOcrretryClick"
            >点击自动识别免填卡号</view
          >
        </u-form-item>

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

          <u-form-item label="银行卡号" required prop="account_number">
            <u-input
              type="number"
              v-model="form.account_number"
              placeholder="请输入银行卡号"
              readonly
            />
          </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>
        </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"
      />
      <div class="branch_list">
        <template v-if="bankList.length">
          <view
            class="branch_list_item"
            v-for="(item, index) in bankList"
            :key="item.id"
            @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>
      </div>
    </u-popup>

    <view class="btn-content">
      <view class="myui_check_text" v-if="bankCardFiles.length"
        >检查并确认结算证件信息无误</view
      >
      <u-button
        text="提交审核"
        color="#4b71ff"
        :disabled="!bankCardFiles.length"
        @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" />
  </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";

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: {},
  data() {
    return {
      form: {
        branch_name: "",
        account_number: "",
        account_holder_name: "",
      },
      bankCardFiles: [],
      loading: false,
      branchSearchText: "",
      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"],
          },
        ],
      },
    };
  },
  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;
    this.branchBankDebounceFn = debounce(this.getBranchBankList, 500);
  },
  methods: {
    getOcrText(filePath, file, type) {
      return new Promise(async (resolve, reject) => {
        this.loading = true;

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

        if (!batchNoRes) {
          this.loading = false;
          this.bankCardOcrLoaded = true;
          reject(batchNoRes);
        }

        const formData = new FormData();
        let formDataStr = "";

        formData.append("batchNo", batchNo);
        formData.append("imgType", type);

        clearTimeout(this.orcTimeout);

        this.orcTimeout = setTimeout(async () => {
          formData.forEach((value, key) => {
            if (formDataStr !== "") {
              formDataStr += "&";
            }
            formDataStr +=
              encodeURIComponent(key) + "=" + encodeURIComponent(value);
          });

          const imgOcrRes = await imgOcrResultApi(formDataStr);

          if (imgOcrRes?.status == 200) {
            this.showBankDialog = true;
            resolve(imgOcrRes?.data);
          } else {
            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(e) {
      const item = e.file;
      const imgUrl = item.url;

      const group = {
        url: imgUrl,
      };

      console.log(e);

      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.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,
            store_area: "北京北京市东城区北京动物园",
          };

          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() {
      if (this.branchSearchText) {
        this.branchBankDebounceFn(this.branchSearchText || "中国银行");
      }

      this.showBankDialog = true;
    },

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

    async onBranchBankChange() {
      this.branchBankDebounceFn(this.branchSearchText);
    },

    loginOut() {
      this.$store.dispatch("user/LoginOut");
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .u-form-item__body {
  padding: 0 0 20rpx;
}
/deep/ .u-upload__wrap__preview,
/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%);
    }
  }

  /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;
    /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: #4b71ff;
      }
    }
  }

  .u-navbar {
    height: 88rpx;
  }

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

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

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

  .btn-login-out {
    font-size: 28rpx;
    color: #4b71ff;
  }

  .bankcard_upload {
    margin: auto;
    align-items: center;
  }
  /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;
  }
}
</style>
