<template>
  <view class="checkAudit-container">
    <!-- <u-navbar
      :autoBack="true"
      :placeholder="true"
      :safeAreaInsetTop="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>
    <favorite-loading
      class="checkAudit-loading"
      v-show="showLoading"
      :color="'#fe4119'"
      text=""
      animation="spinner15"
    ></favorite-loading>
    <view v-show="!showLoading && !isContractSigningaPageTo">
      <!--平台审核和拉卡全部通过-->
      <view class="" v-if="isPassAudit">
        <view class="img-pass"></view>
        <view class="tips">
          {{ auditInfo.approval_remark }}
          <br />
          欢迎入驻小发同城，美好生活由此开启
        </view>
      </view>
      <!--平台审核失败驳回-->
      <view class="" v-if="[2].includes(auditInfo.approval_status)">
        <view class="img"></view>
        <view class="tips">很遗憾，您无法入驻我们的商城</view>
        <view class="refusal-cause">
          拒绝原因：{{ auditInfo.approval_remark }}
        </view>
      </view>
      <!--审核中-->
      <view
        class=""
        v-if="
          [3].includes(auditInfo.approval_status) &&
          !auditInfo.lkl_ec_result_url
        "
      >
        <view class="img-await"></view>
        <view class="tips">审核中，1-7个工作日内答复，请耐心等待</view>
      </view>
      <!--暂无记录-->
      <view class="" v-if="auditInfo.approval_status == 4">
        <view class="img-no-audit"></view>
        <view class="tips">暂无申请记录！</view>
      </view>
      <!--初步审核通过，签署合同成功-->
      <view
        class=""
        v-if="
          auditInfo.approval_status == 5 &&
          auditInfo.has_ec_signed == 2 &&
          auditInfo.lkl_ec_result_url
        "
      >
        <view class="img-pass-audit"></view>
        <view class="tips">
          "恭喜您通过初步审核！请于24小时内完成合同签署，以便我们继续推进后续流程。（温馨提示：本邀请将于24小时后失效）"
        </view>
      </view>
      <!--签署合同-->
      <view
        class="contract-content"
        v-if="
          auditInfo.approval_status == 5 &&
          auditInfo.has_ec_signed == 2 &&
          auditInfo.lkl_ec_result_url
        "
      >
        <view class="contract-tips">您还没有签署，请签署</view>
        <u-button class="btn-submit" @click="skipuContract">立即签署</u-button>
      </view>
      <!--签署合同成功-->
      <view
        class=""
        v-if="
          [21].includes(auditInfo.approval_status) &&
          auditInfo.has_ec_signed == 1
        "
      >
        <view class="img-pass-audit"></view>
        <view class="tips">
          合同签署完成，商家信息正在提交审核，请耐心等待。
        </view>
      </view>
      <!--签署合同失败-->
      <view
        class=""
        v-if="
          [21].includes(auditInfo.approval_status) &&
          auditInfo.has_ec_signed == 2
        "
      >
        <view class="img"></view>
        <view class="tips">
          抱歉，系统未能完成处理，请联系客服进一步审核后重试。
        </view>
        <u-button class="btn-admin-service" @click="skipuAdminService">
          联系客服
        </u-button>
      </view>
      <!--进件成功-->
      <view
        class=""
        v-if="
          auditInfo.approval_status == 5 &&
          auditInfo.has_apply_mer == 1 &&
          auditInfo.store_status == 2
        "
      >
        <view class="img-shop-init"></view>
        <view class="tips">
          系统正在初始化店铺，预计很快完成，请您稍后再来探索。
        </view>
      </view>
      <!--进件失败-->
      <view
        class=""
        v-if="
          [21].includes(auditInfo.approval_status) &&
          auditInfo.has_ec_signed == 1 &&
          auditInfo.has_apply_mer == 2
        "
      >
        <view class="img"></view>
        <view class="tips">
          抱歉，系统未能完成处理，请联系客服进一步审核后重试。
        </view>
        <u-button class="btn-admin-service" @click="skipuAdminService">
          联系客服
        </u-button>
      </view>
      <!--店铺创建成功-->
      <view
        class=""
        v-if="
          auditInfo.approval_status == 5 &&
          auditInfo.has_apply_mer == 1 &&
          auditInfo.has_apply_split == 2 &&
          auditInfo.store_status == 1
        "
      >
        <view class="img-independent-account"></view>
        <view class="tips">店铺创建成功，系统正在处理分账业务申请</view>
      </view>
      <!--创建店铺失败-->
      <view
        class=""
        v-if="
          [21].includes(auditInfo.approval_status) &&
          auditInfo.has_ec_signed == 1 &&
          auditInfo.has_apply_mer == 1 &&
          auditInfo.store_status == 2
        "
      >
        <view class="img"></view>
        <view class="tips">
          店铺创建未成功，请联系客服协助处理，我们将尽快为您解决。
        </view>
        <u-button class="btn-admin-service" @click="skipuAdminService">
          联系客服
        </u-button>
      </view>
      <!--分账业务申请成功-->
      <view
        class=""
        v-if="
          auditInfo.approval_status == 5 &&
          auditInfo.has_apply_mer == 1 &&
          auditInfo.store_status == 1 &&
          auditInfo.has_apply_split == 1 &&
          auditInfo.has_bind_receiver == 2
        "
      >
        <view class="img-shop-init"></view>
        <view class="tips">分账业务申请已通过，系统正在处理接收方绑定</view>
      </view>
      <!--分账业务申请失败-->
      <view
        class=""
        v-if="
          [21].includes(auditInfo.approval_status) &&
          auditInfo.has_ec_signed == 1 &&
          auditInfo.has_apply_mer == 1 &&
          auditInfo.store_status == 1 &&
          auditInfo.has_apply_split == 2
        "
      >
        <view class="img"></view>
        <view class="tips">
          分账业务处理遇到小问题，需要客服再次确认哦~请稍后联系他们完成审核后重试。
        </view>
        <u-button class="btn-admin-service" @click="skipuAdminService">
          联系客服
        </u-button>
      </view>
      <!--分账接收方绑定结果成功-->
      <view
        class=""
        v-if="
          [1, 5].includes(auditInfo.approval_status) &&
          auditInfo.has_apply_mer == 1 &&
          auditInfo.store_status == 1 &&
          auditInfo.has_apply_split == 1 &&
          auditInfo.has_bind_receiver == 1
        "
      >
        <view class="img-shop-init"></view>
        <view class="tips">分账接收方绑定成功，入驻流程即将完成</view>
      </view>
      <!--分账接收方绑定失败-->
      <view
        class=""
        v-if="
          [21].includes(auditInfo.approval_status) &&
          auditInfo.has_ec_signed == 1 &&
          auditInfo.has_apply_mer == 1 &&
          auditInfo.store_status == 1 &&
          auditInfo.has_apply_split == 1 &&
          auditInfo.has_bind_receiver == 2
        "
      >
        <view class="img"></view>
        <view class="tips">
          很抱歉，您的分账请求未能通过审核，请联系我们的客服人员获取帮助。
        </view>
        <u-button class="btn-admin-service" @click="skipuAdminService">
          联系客服
        </u-button>
      </view>
      <view class="time" v-if="auditInfo.approval_status != 4">
        申请时间：{{ auditInfo.created_at }}
      </view>
      <u-form :model="form" class="form" ref="uForm" label-width="70">
        <u-form-item
          :label="item.label"
          :prop="item.key"
          required
          v-for="(item, index) of auditInfo.approval_invalid_col"
          :key="index"
          v-show="item.show"
          :class="item.class"
          @click="handerFormItem(item)"
        >
          <u-input
            v-if="item.type != 'upload'"
            :style="item.style"
            class="form-input"
            v-model="form[item.key]"
            :placeholder="item.placeholder"
            :readonly="item.isReadonly"
            :maxlength="item.maxLength"
          />
          <u-icon
            v-if="item.type == 'select'"
            slot="right"
            style="display: inline-block; margin-left: 8rpx"
            name="arrow-right"
            size="12"
            color="#aaaaaa"
          ></u-icon>
          <u-upload
            v-if="item.type == 'upload'"
            :class="item.imgUrlArr.length == 0 ? item.class : ''"
            :uploadIcon="
              item.imgUrlArr.length == 0 && item.key != 'bankcard_item'
                ? ''
                : 'camera-fill'
            "
            @afterRead="afterRead($event, item)"
            @delete="deletePic($event, item)"
            accept="image"
            :fileList="item.imgUrlArr"
            :max-count="item.imgUpMaxCount || 1"
            :width="item.imgWidth"
            :height="item.imgHeight"
            :upload-text="item.uploadText"
            :uploadIconColor="item.uploadIconColor"
            :maxSize="maxSize"
            @oversize="overSize"
          ></u-upload>
          <tui-radio-group
            v-if="
              [
                'legal_person_id_period_end',
                'individual_id_period_end',
              ].includes(item.key)
            "
            class="id-radio-group"
            @change="handelRaddio"
          >
            <view v-for="(item, index) in radioItems" :key="index">
              <tui-radio
                class="id-radio"
                :checked="item.checked"
                :value="item.value"
                color="#07c160"
                borderColor="#999"
              ></tui-radio>
              <text class="id-radio-text">{{ item.name }}</text>
            </view>
          </tui-radio-group>
          <view
            v-if="
              item.key == 'bankcard_item' &&
              item.imgUrlArr.length &&
              !item.account_number
            "
            class="retry_ocr"
            @click="onBankOcrretryClick"
          >
            点击自动识别免填卡号
          </view>
        </u-form-item>
      </u-form>
      <view class="btn-content" v-if="auditInfo.approval_status == 2">
        <u-button class="btn-submit" @click="getRestartMerchApply">
          重新提交
        </u-button>
      </view>
      <u-picker
        :show="showPicker"
        :columns="columns"
        :safe-area-inset-bottom="true"
        :default-selector="[0]"
        :keyName="'name'"
        @cancel="handleCancel"
        @confirm="handleConfirm"
      ></u-picker>
      <u-toast ref="uToast" />
      <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>
      <u-datetime-picker
        :show="showStartTime"
        v-model="startTime"
        mode="date"
        :minDate="startMinDate"
        @cancel="showStartTime = false"
        @confirm="handelStartTime"
      ></u-datetime-picker>
      <u-datetime-picker
        :show="showEndTime"
        v-model="endTime"
        :minDate="endMinDate"
        :maxDate="endMaxDate"
        mode="date"
        @confirm="handelEndTime"
        @cancel="showEndTime = false"
      ></u-datetime-picker>
      <u-loading-page
        :loading="loading"
        bgColor="rgba(0,0,0,0.5)"
        fontSize="32rpx"
        color="#fff"
        loadingText="数据正在加载中..."
      ></u-loading-page>
    </view>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
import config from "./formConfig";
import {
  GetAuditInfo,
  GetBankList,
  GetRestartMerchApply,
  branchBankSearchApi,
} from "../../api/audit";
import { throttle, debounce } from "lodash";
import { GetAccountDashboard } from "../../api/user";
import {
  UploadFilePromise,
  batchNoApi,
  imgOcrResultApi,
} from "../../api/upload";
import { mapState } from "vuex";
import favoriteLoading from "@/components/favorite-loading/favorite-loading.vue";
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 {
  name: "checkAudit",
  components: {
    favoriteLoading,
    navBar,
  },
  data() {
    return {
      showLoading: true,
      showStartTime: false,
      showEndTime: false,
      startTime: null,
      endTime: null,
      startMinDate: 0,
      endMinDate: 0,
      endMaxDate: 0,
      formConfig: JSON.parse(JSON.stringify(config.formConfig)),
      form: {},
      auditInfo: {
        license_type: 1,
        approval_status: 4,
        created_at: "2099-02-17 09:25:53",
        approval_remark: "",
        approval_invalid_col: [],
      },
      manageTypeItem: {},
      columns: [
        [
          {
            id: 1,
            name: "无需特殊资质",
          },
          {
            id: 2,
            name: "需许可证资质",
          },
          {
            id: 3,
            name: "需特许证件资质",
          },
        ],
      ],
      radioItems: [
        {
          name: "非长期",
          value: "1",
          checked: true,
        },
        {
          name: "长期",
          value: "2",
          checked: false,
        },
      ],
      showPicker: false,
      bankCardOcrLoaded: false,
      firstBranchBankLoad: false,
      showBankDialog: false,
      bankList: [],
      branchSearchText: "",
      branchBankDebounceFn: null,
      currentBank: {},
      currentBankFile: {},
      loading: false,
      maxSize: 20 * 1024 * 1024, //图片最大不能超过20M
      fileMinSize: 5 * 1024, // 最小为5KB
    };
  },
  computed: {
    ...mapState("user", ["userInfo"]),
    ...mapState("audit", ["isContractSigningaPageTo"]),
    isPassAudit() {
      let info = this.auditInfo;

      return (
        info.approval_status == 1 &&
        info.store_status == 1 &&
        info.has_ec_signed == 1 &&
        info.has_apply_mer == 1 &&
        info.has_apply_split == 1 &&
        info.has_apply_receiver == 1 &&
        info.has_bind_receiver == 1
      );
    },
  },
  watch: {
    isContractSigningaPageTo: {
      handler: function (val, oldVal) {
        if (val) {
          uni.showLoading({
            title: "店铺创建中，请稍等...",
            mask: true,
          });

          setTimeout(() => {
            uni.hideLoading();
            this.$store.commit("audit/BACK_PAGE", false);
            this.getAuditInfo();
          }, 40000);
        }
      },
      // immediate: true,
      // deep: true, // 深度监听
    },
  },
  onShow() {
    this.getAuditInfo();
    this.getBankList();
  },
  beforeUnmount() {
    this.branchBankDebounceFn?.cancel();
  },
  mounted() {
    this.branchBankDebounceFn = debounce(this.getBranchBankList, 500);

    const date19300520 = new Date("1930-05-20T00:00:00Z");
    this.startMinDate = date19300520.getTime();

    const date = new Date();
    date.setFullYear(date.getFullYear() + 20);
    this.endMaxDate = date.getTime();

    const data2 = new Date();
    data2.setFullYear(data2.getFullYear() + 5);
    this.endMinDate = data2.getTime();
  },
  methods: {
    pageBack() {
      uni.navigateBack();
    },
    async getAuditInfo() {
      if (this.isContractSigningaPageTo) return;

      var params = {};

      params.mobile = this.userInfo.user_mobile.startsWith("+86")
        ? this.userInfo.user_mobile.replace("+86", "")
        : this.userInfo.user_mobile;

      let res = await GetAuditInfo(params);
      if (res && res.status == 200) {
        this.auditInfo = res.data || {
          license_type: 1,
          approval_status: 4,
          created_at: "2099-02-17 09:25:53",
          approval_remark: "",
          approval_invalid_col: [],
        };

        if (this.isPassAudit) {
          uni.switchTab({
            url: "/pages/order/order",
          });
          return;
        }

        if (!res.data || res.data.approval_status == 4) {
          this.showLoading = false;
          return;
        }

        if (this.auditInfo.contract_download_url) {
          uni.setStorageSync(
            "contractDownloadUrl",
            this.auditInfo.contract_download_url
          );
        }

        if (this.auditInfo.approval_invalid_col.includes("all")) {
          uni.setStorageSync("auditId", res.data.id);

          uni.navigateTo({
            url: "/pages/audit/shop1",
          });
          return;
        }

        if (
          this.auditInfo.approval_status == 1 &&
          this.auditInfo.signed_status == 2 &&
          this.auditInfo.store_status == 1
        ) {
          let result = await GetAccountDashboard();
          if (result && result.status == 200) {
            uni.setStorageSync("accountDashboard", result.data);
            uni.setStorageSync("auditInfo", res.data);
            uni.switchTab({
              url: "/pages/order/order",
            });
          }
        }

        let arr = JSON.parse(res.data.approval_invalid_col);

        const arr2 = this.formConfig.reduce((acc, item) => {
          if (arr.includes(item.key)) {
            this.form[item.key] = "";

            if (item.key == "license_type") {
              this.form[item.key] = this.columns[0][0].name;
            }

            acc.push(item);
          }

          return acc;
        }, []);

        this.auditInfo.approval_invalid_col = arr2;

        this.auditInfo.approval_invalid_col.forEach((item) => {
          if (
            ["account_holder_name", "account_number", "branch_name"].includes(
              item.key
            ) &&
            this.auditInfo.entity_type == 1
          ) {
            item.show = true;
          }
        });

        let typeItem = uni.getStorageSync("typeItem");

        if (typeItem) {
          this.manageTypeItem = typeItem;
          this.form.biz_category = typeItem.bizSecondCategory.name;
        }

        let locationItem = uni.getStorageSync("locationItem");

        if (locationItem) {
          this.form.mapAddress =
            locationItem.administrativeRegion.label[0] +
            locationItem.administrativeRegion.label[1] +
            locationItem.administrativeRegion.label[2];

          this.form.store_address = locationItem.selectAddress.name;
        }
      }

      this.showLoading = false;
    },
    async getBankList() {
      let res = await GetBankList();
      if (res && res.status == 200) {
        this.bankList[0] = res.data;
      }
    },
    //formItem 点击事件
    handerFormItem(item) {
      if (!item.type == "select") return;

      switch (item.key) {
        case "mapAddress":
          uni.navigateTo({
            url: "/pages/audit/mapAddress",
          });
          break;
        case "biz_category":
          uni.navigateTo({
            url: "/pages/audit/businessType",
          });
          break;
        case "license_type":
          this.showPicker = true;
          break;
        case "branch_name":
          this.showBankDialog = true;
          break;
        case "legal_person_id_period_begin":
          this.showStartTime = true;
          break;
        case "individual_id_period_begin":
          this.showStartTime = true;
          break;
        case "legal_person_id_period_end":
          this.showEndTime = true;
          break;
        case "individual_id_period_end":
          this.showEndTime = true;
          break;
      }
    },
    overSize(e) {
      uni.$u.toast("上传图片大小不能超过20MB!");
    },

    //上传图片
    async afterRead(e, item) {
      const fileImg = e.file;
      const imgUrl = fileImg.url;

      const group = {
        url: imgUrl,
      };
      item.imgUrlArr.push(group);

      let res = await UploadFilePromise(imgUrl);

      if (res && res.status == 200) {
        switch (item.key) {
          case "biz_license_image":
            this.form.biz_license_image = res.data.url;
            break;
          case "license_image":
            if (this.form.license_image == "") {
              this.form.license_image = String(res.data.url);
            } else {
              this.form.license_image += "," + String(res.data.url);
            }
            break;
          case "front_facade_image":
            this.form.front_facade_image = res.data.url;
            break;
          case "environment_image":
            this.form.environment_image = res.data.url;
            break;
          case "legal_person_id_images":
            this.form.legal_person_id_images = res.data.url;
            break;
          case "legal_person_id_images2":
            this.form.legal_person_id_images2 = res.data.url;
            break;
          case "individual_id_images":
            this.form.individual_id_images = res.data.url;
            break;
          case "individual_id_images2":
            this.form.individual_id_images2 = res.data.url;
            break;
        }
      }
      switch (item.key) {
        // 营业执照
        case "biz_license_image":
          var ocr = await this.getOcrText(
            imgUrl,
            fileImg,
            orcImgTypeConf.BUSINESS_LICENCE
          );
          this.auditInfo.approval_invalid_col.forEach((item) => {
            if (
              [
                "biz_license_company",
                "legal_person_name",
                "biz_license_number",
                "legal_person_mobile",
                "biz_license_content",
              ].includes(item.key)
            ) {
              item.show = true;
            }
          });
          this.form.biz_license_company = ocr.bizLicenseCompanyName;
          this.form.legal_person_name = ocr.bizLicenseOwnerName;
          this.form.biz_license_number = ocr.bizLicenseCreditCode;
          this.form.biz_license_content = ocr.bizLicenseScope || "";
          console.log("BUSINESS_LICENCE", ocr);
          break;
        case "license_number":
          break;
        // 法人身份证正面
        case "legal_person_id_images":
          var ocr = await this.getOcrText(
            imgUrl,
            fileImg,
            orcImgTypeConf.FR_ID_CARD_FRONT
          );
          this.auditInfo.approval_invalid_col.forEach((item) => {
            if (
              ["legal_person_id_number", "legal_person_id_addr"].includes(
                item.key
              )
            ) {
              item.show = true;
            }
          });
          this.form.legal_person_name = ocr.name;
          this.form.legal_person_id_number = ocr.idNumber;
          this.form.legal_person_id_addr = ocr.address;
          console.log("ID_CARD_FRONT", ocr);
          break;
        // 法人身份证反面
        case "legal_person_id_images2":
          var ocr = await this.getOcrText(
            imgUrl,
            item,
            orcImgTypeConf.FR_ID_CARD_BEHIND
          );
          this.auditInfo.approval_invalid_col.forEach((item) => {
            if (
              [
                "legal_person_id_period_begin",
                "legal_person_id_period_end",
              ].includes(item.key)
            ) {
              item.show = true;
            }
          });
          if (ocr && ocr.validity) {
            let validity = ocr.validity.split("-");
            this.startTime = validity[0];
            this.endTime = validity[1];

            this.form.legal_person_id_period_begin = this.startTime;
            this.form.legal_person_id_period_end = this.endTime;
          }
          break;
        // 个人身份证正面
        case "individual_id_images":
          var ocr = await this.getOcrText(
            imgUrl,
            fileImg,
            orcImgTypeConf.ID_CARD_FRONT
          );
          this.auditInfo.approval_invalid_col.forEach((item) => {
            if (
              [
                "individual_id_number",
                "individual_id_name",
                "individual_id_addr",
              ].includes(item.key)
            ) {
              item.show = true;
            }
          });
          this.form.individual_id_number = ocr.idNumber;
          this.form.individual_id_name = ocr.name;
          this.form.individual_id_addr = ocr.address;
          this.form.console.log("personIdFront", ocr);
          break;
        // 个人身份证反面
        case "individual_id_images2":
          var ocr = await this.getOcrText(
            imgUrl,
            fileImg,
            orcImgTypeConf.ID_CARD_BEHIND
          );
          if (ocr && ocr.validity) {
            this.auditInfo.approval_invalid_col.forEach((item) => {
              if (
                [
                  "individual_id_period_begin",
                  "individual_id_period_end",
                ].includes(item.key)
              ) {
                item.show = true;
              }
            });

            let validity = ocr.validity.split("-");
            this.startTime = validity[0];
            this.endTime = validity[1];
            this.form.individual_id_period_begin = this.startTime.replace(
              /\./g,
              "-"
            );
            this.form.individual_id_period_end = this.endTime.replace(
              /\./g,
              "-"
            );
          }
          break;
        // 银行
        case "bankcard_item":
          this.currentBankFile = {
            file: fileImg,
            path: imgUrl,
          };

          this.setFromItemWithOcr(this.currentBankFile);
          break;
      }
    },
    // 上传删除图片
    deletePic(e, item) {
      if (item.key == "license_image") {
        item.imgUrlArr.splice(e.index, 1);
        let arr = this.form[item.key].split(",");
        arr.splice(e.index, 1);
        this.form[item.key] = arr.join(",");
      } else {
        item.imgUrlArr.splice(0, 1);
      }

      if (item.key == "bankcard_item") {
        this.form.account_number = "";
        this.form.bank_name = "";
        this.branchSearchText = "";
        this.currentBank = {};
        this.bankCardOcrLoaded = false;

        if (this.auditInfo.entity_type == 2) {
          this.auditInfo.approval_invalid_col.forEach((item) => {
            if (
              ["account_holder_name", "account_number", "bank_name"].includes(
                item.key
              )
            ) {
              item.show = false;
            }
          });
        }
      }

      if (item.key == "biz_license_image") {
        this.auditInfo.approval_invalid_col.forEach((item) => {
          if (
            [
              "biz_license_company",
              "legal_person_name",
              "biz_license_number",
              "legal_person_mobile",
              "biz_license_content",
            ].includes(item.key)
          ) {
            item.show = false;
          }
        });
        this.form.biz_license_company = "";
        this.form.legal_person_name = "";
        this.form.biz_license_number = "";
        this.form.legal_person_mobile = "";
        this.form.biz_license_content = "";
      }

      if (item.key == "legal_person_id_images") {
        this.auditInfo.approval_invalid_col.forEach((item) => {
          if (
            ["legal_person_id_number", "legal_person_id_addr"].includes(
              item.key
            )
          ) {
            item.show = false;
          }
        });

        this.form.legal_person_id_number = "";
        this.form.legal_person_id_addr = "";
      }
      // 个人身份证正面
      if (item.key == "individual_id_images") {
        this.auditInfo.approval_invalid_col.forEach((item) => {
          if (
            [
              "individual_id_number",
              "individual_id_name",
              "individual_id_addr",
            ].includes(item.key)
          ) {
            item.show = false;
          }
        });

        this.form.individual_id_number = "";
        this.form.individual_id_name = "";
        this.form.individual_id_addr = "";
      }
      // 个人身份证反面
      if (item.key == "individual_id_images2") {
        this.auditInfo.approval_invalid_col.forEach((item) => {
          if (
            ["individual_id_period_begin", "individual_id_period_end"].includes(
              item.key
            )
          ) {
            item.show = false;
          }
        });

        this.form.individual_id_period_begin = "";
        this.form.individual_id_period_end = "";
      }
    },
    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);
          },
        });
      });
    },
    // 营业执照 和 身份证 OCR识别
    getOcrText(filePath, file, type) {
      return new Promise(async (resolve, reject) => {
        //#ifdef APP-PLUS
        filePath = await this.compressImage(filePath);
        //#endif

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

        //#ifdef H5
        filePath = await H5compressImg(filePath, 0.75);
        let size = getBase64Size(filePath);
        console.log("OCR上图图片压缩后为：", size);
        //#endif

        const batchNoRes = await batchNoApi(filePath, file, type);
        const batchNo = batchNoRes.batchNo;
        // 兼容多端的表单数据处理方式
        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);
          clearTimeout(this.orcTimeout);
          resolve(imgOcrRes?.data);
        }, 1000);
      });
    },
    async getBranchBankList(keyword) {
      let res = await branchBankSearchApi({
        keyword,
        pageNum: 1,
        pageSize: 1000 * 10,
      });

      this.bankList = res.data.items;
      this.firstBranchBankLoad = true;
    },
    getBankOcrText(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);
        }

        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 onBankOcrretryClick() {
      this.setFromItemWithOcr(this.currentBankFile);
    },
    handleCancel() {
      this.showPicker = false;
    },
    handleConfirm(e) {
      this.form.license_type = e.value[0].name;
      if (e.value[0].id != 1) {
        this.auditInfo.approval_invalid_col.forEach((item) => {
          if (["license_image", "license_number"].includes(item.key)) {
            item.show = true;
          }
        });
      } else {
        this.auditInfo.approval_invalid_col.forEach((item) => {
          if (["license_image", "license_number"].includes(item.key)) {
            item.show = false;
          }
        });
      }

      this.showPicker = false;
    },
    handleBankCancel() {
      this.showActionSheet = false;
    },
    handleBankConfirm(e) {
      this.form.bank_name = e.value[0].bank_name;
      this.showActionSheet = false;
    },
    skipuAdminService() {
      let item = {
        user_friend_id: 36,
        user_id: 10001,
        friend_id: 10001,
        friend_note: "",
        user_friend_addtime: "2025-05-09 10:03:33",
        friend_state: 2,
        friend_invite: 2,
        username: "系统客服",
        avatar:
          "https://media-mall-prod-1259811287.cos.ap-guangzhou.myqcloud.com/media/media/plantform/20250307/c4cab676e06a49b282c2cbbe481f0fa1.png",
        sign: "",
        level_name: "v1",
        user_nickname: "系统客服",
        user_avatar:
          "https://media-mall-prod-1259811287.cos.ap-guangzhou.myqcloud.com/media/media/plantform/20250307/c4cab676e06a49b282c2cbbe481f0fa1.png",
        user_sign: "",
        user_level_name: "v1",
        rid: 2,
        id: 776395489,
      };

      uni.navigateTo({
        url: `/pages/IM/IMmsgContent?item=${JSON.stringify(item)}`,
      });
    },
    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.form.bank_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);
    },
    async setFromItemWithOcr(currentBankFile) {
      var ocr = await this.getBankOcrText(
        currentBankFile.path,
        currentBankFile.file,
        orcImgTypeConf.BANK_CARD
      );

      if (ocr && ocr.card_number) {
        this.auditInfo.approval_invalid_col.forEach((item) => {
          if (
            ["account_holder_name", "account_number", "bank_name"].includes(
              item.key
            ) &&
            this.auditInfo.entity_type == 2
          ) {
            item.show = true;
          }
        });
        this.form.account_number = ocr.card_number;
        this.branchSearchText = ocr.issuer;
        console.log("bankCard", ocr);
      }
    },
    // 重新审核
    async getRestartMerchApply() {
      console.log(this.auditInfo);

      this.form.id = this.auditInfo.id;

      let approval_invalid_col = this.auditInfo.approval_invalid_col;

      let isValidata = true;

      approval_invalid_col.forEach((item) => {
        if (this.form[item.key] == "") {
          this.$refs.uToast.show({
            message: item.ruleMessage,
            type: "error",
            duration: 1000,
          });
          isValidata = false;
        }
      });

      if (!isValidata) return;

      if (this.form.mapAddress) {
        let locationItem = uni.getStorageSync("locationItem");
        this.form.store_longitude = locationItem.selectAddress.location.lng;
        this.form.store_latitude = locationItem.selectAddress.location.lat;
        this.form.province_id = locationItem.administrativeRegion.value[0];
        this.form.city_id = locationItem.administrativeRegion.value[1];
        this.form.county_id = locationItem.administrativeRegion.value[2];
        this.form.store_address =
          locationItem.administrativeRegion.label[0] +
          locationItem.administrativeRegion.label[1] +
          locationItem.administrativeRegion.label[2] +
          this.form.store_address;
        this.form.store_area =
          locationItem.administrativeRegion.label.join("/");
        this.form.store_district =
          locationItem.administrativeRegion.value.join("/");
      }

      if (this.form.biz_category) {
        this.form.biz_category = this.manageTypeItem.bizCategory.id;
        this.form.biz_second_category =
          this.manageTypeItem.bizSecondCategory.id;
      }

      if (this.form.license_type) {
        let licenseTypeItem = this.columns[0].find(
          (item) => item.name == this.license_type.license_type
        );
        this.form.license_type = licenseTypeItem.id;
      }

      if (Object.keys(this.currentBank).length > 0) {
        this.form = { ...this.form, ...this.currentBank };
      }

      let res = await GetRestartMerchApply(this.form);
      if (res && res.status == 200) {
        uni.removeStorageSync("locationItem");
        uni.removeStorageSync("auditItem");
        uni.removeStorageSync("typeItem");
        await this.getAuditInfo();
      } else {
        if (this.form.license_type) {
          let licenseTypeItem = this.columns[0].find(
            (item) => item.id == this.form.license_type
          );
          this.form.license_type = licenseTypeItem.name;
        }
      }
    },
    handelStartTime(e) {
      this.startTime = e.value;
      this.showStartTime = false;
      if (this.auditInfo.entity_type == 1) {
        this.form.legal_person_id_period_begin = uni.$u.timeFormat(
          this.startTime,
          "yyyy-mm-dd"
        );
      } else {
        this.form.individual_id_period_begin = uni.$u.timeFormat(
          this.startTime,
          "yyyy-mm-dd"
        );
      }
    },
    handelEndTime(e) {
      this.endTime = e.value;
      this.showEndTime = false;
      if (this.auditInfo.entity_type == 1) {
        this.form.legal_person_id_period_end = uni.$u.timeFormat(
          this.endTime,
          "yyyy-mm-dd"
        );
      } else {
        this.form.individual_id_period_end = uni.$u.timeFormat(
          this.endTime,
          "yyyy-mm-dd"
        );
      }
    },
    handelRaddio(e) {
      if (e && e.detail.value == 2) {
        if (this.auditInfo.entity_type == 1) {
          this.form.legal_person_id_period_end = "长期";
        } else {
          this.form.individual_id_period_end = "长期";
        }
      } else {
        if (this.auditInfo.entity_type == 1) {
          this.form.legal_person_id_period_end = "";
        } else {
          this.form.individual_id_period_end = "";
        }
      }
    },
    skipuContract() {
      uni.navigateTo({
        url: `/pages/audit/contractSigning?url=${this.auditInfo.lkl_ec_result_url}`,
      });
    },
    loginOut() {
      this.$store.dispatch("user/LoginOut");
    },
  },
};
</script>

<style lang="scss">
@import "@/styles/variables.scss";

.checkAudit-container {
  .checkAudit-loading {
    margin: 70% auto;
    display: flex;
  }

  .form {
    padding: 48rpx 16rpx;
    background: #fff;
  }

  padding: 0 24rpx;
  .img {
    margin: 0 auto;
    margin-top: 16%;
    width: 320rpx;
    height: 220rpx;
    background-image: url("../../static/no-audit.png");
    background-size: 100% 100%;
  }

  .img-await {
    margin: 0 auto;
    margin-top: 17%;
    margin-bottom: 20%;
    width: 320rpx;
    height: 240rpx;
    background-image: url("../../static/await.png");
    background-size: 100% 100%;
  }

  .img-pass {
    margin: 0 auto;
    margin-top: 17%;
    margin-bottom: 20%;
    width: 320rpx;
    height: 320rpx;
    background-image: url("../../static/pass.png");
    background-size: 100% 100%;
  }

  .img-no-audit {
    margin: 0 auto;
    margin-top: 17%;
    margin-bottom: 20%;
    width: 600rpx;
    height: 600rpx;
    background-image: url("../../static/no-data.png");
    background-size: 100% 100%;
  }

  .img-pass-audit {
    margin: 0 auto;
    margin-top: 17%;
    margin-bottom: 20%;
    width: 400rpx;
    height: 400rpx;
    background-image: url("../../static/pass.png");
    background-size: 100% 100%;
  }

  .img-shop-init {
    margin: 0 auto;
    margin-top: 17%;
    margin-bottom: 20%;
    width: 400rpx;
    height: 400rpx;
    background-image: url("../../static/shop-init.png");
    background-size: 100% 100%;
  }

  .img-independent-account {
    margin: 0 auto;
    margin-top: 17%;
    margin-bottom: 20%;
    width: 400rpx;
    height: 400rpx;
    background-image: url("../../static/independent-account.png");
    background-size: 100% 100%;
  }

  .tips {
    margin-bottom: 24rpx;
    text-align: center;
    color: #040404;
    font-weight: 500;
    font-size: 36rpx;
  }

  .refusal-cause {
    margin: 48rpx 0;
  }

  ::v-deep.upload-1 {
    .u-upload__button {
      // background: url("../../static/shenhe-bg1.png");
      background-image: url("../../static/shenhe-bg1.png");
      background-size: 100%;
    }
  }

  ::v-deep.upload-2 {
    .u-upload__button {
      // background: url("../../static/shenhe-bg1.png");
      background-image: url("../../static/shenhe-bg2.png");
      background-size: 100%;
    }
  }

  ::v-deep.upload-3 {
    .u-upload__button {
      // background: url("../../static/shenhe-bg1.png");
      background-image: url("../../static/business-license-bg.png");
      background-size: 100% 100%;
    }
  }

  ::v-deep.upload-4 {
    .u-upload__button {
      // background: url("../../static/shenhe-bg1.png");
      background-image: url("../../static/permit-bg.png");
      background-size: 100% 100%;
    }
  }

  ::v-deep.upload-5 {
    .u-upload__button {
      // background: url("../../static/shenhe-bg1.png");
      background-image: url("../../static/id-bg-1.png");
      background-size: 100% 100%;
    }
  }

  ::v-deep.upload-6 {
    .u-upload__button {
      // background: url("../../static/shenhe-bg1.png");
      background-image: url("../../static/id-bg-2.png");
      background-size: 100% 100%;
    }
  }

  .bankcard_upload {
    position: relative;
    margin: auto;
    align-items: center;
  }

  .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;
      }
    }
  }

  .time {
    text-align: center;
  }

  .btn-content {
    position: relative;
    bottom: 24rpx;
    width: 94%;
    padding: 48rpx 24rpx;
  }

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

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

  .retry_ocr {
    position: absolute;
    top: 50%;
    left: 60%;
    padding: 15rpx 24rpx;
    width: 40%;
    line-height: 24rpx;
    font-size: 24rpx;
    text-align: center;
    color: #fff;
    transform: translate3d(-50%, -50%, 0);
    background: rgba(75, 113, 255, 0.95);
    border-radius: 100rpx;
  }

  .contract-content {
    padding: 0 15%;
    text-align: center;
    margin-bottom: 60rpx;

    .contract-tips {
      margin-bottom: 60rpx;
    }
  }

  .id-radio-group {
    display: flex;
    justify-content: space-between;
    margin-right: 20rpx;
    width: 240rpx;
  }

  .btn-admin-service {
    width: 60%;
    border-radius: 16rpx;
    background: $base-color;
    color: #fff;
  }
}
</style>
