<template>
  <view class="shop-2-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="44"
    >
      <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="shop-2-content">
      <u-subsection
        class="subsection"
        :list="list"
        :current="active"
        @change="handleSubsection"
      ></u-subsection>

      <view class="up-block" v-show="active == 0">
        <view class="up-title">营业执照信息</view>
        <u-form :model="form" class="form" ref="uForm" label-width="120">
          <u-form-item label="营业执照" prop="businessLicenseFiles">
            <u-upload
              :class="
                form.businessLicenseFiles.length == 0 ? 'shop2-2-upload' : ''
              "
              class="shop2-2-upload"
              @afterRead="afterRead($event, 'businessLicense')"
              @delete="deletePic($event, 'businessLicense')"
              accept="image"
              :fileList="form.businessLicenseFiles"
              :max-count="1"
              width="125"
              height="88"
              :maxSize="maxSize"
              @oversize="overSize"
              uploadText="点击上传营业执照"
            ></u-upload>
          </u-form-item>
          <template
            v-if="form.businessLicenseFiles.length && form.biz_license_company"
          >
            <u-form-item label="公司名称" prop="biz_license_company" required>
              <u-input
                class="form-input"
                v-model="form.biz_license_company"
                placeholder="请输入公司名称"
                clearable
              />
            </u-form-item>
            <u-form-item label="法人姓名" prop="legal_person_name" required>
              <u-input
                class="form-input"
                v-model="form.legal_person_name"
                placeholder="请输入法人姓名"
                clearable
              />
            </u-form-item>
            <u-form-item label="注册号" prop="biz_license_number" required>
              <u-input
                class="form-input"
                v-model="form.biz_license_number"
                placeholder="请输入注册号"
                clearable
              />
            </u-form-item>
            <u-form-item label="法人手机号" prop="legal_person_mobile" required>
              <u-input
                maxlength="11"
                class="form-input"
                v-model="form.legal_person_mobile"
                placeholder="请输入法人手机号"
                clearable
              />
            </u-form-item>
            <u-form-item label="经营范围" prop="biz_license_content" required>
              <u-input
                maxlength="11"
                class="form-input"
                v-model="form.biz_license_content"
                placeholder="请输入经营范围"
                clearable
              />
            </u-form-item>
            <u-form-item
              label="所属行业"
              prop="license_type"
              @click="showPicker = true"
            >
              <u-input
                style="pointer-events: none"
                class="form-input"
                v-model="license_type_name"
                placeholder="请选择所属行业"
                readonly
              />
              <u-icon
                style="display: inline-block; margin-left: 8rpx"
                name="arrow-down"
                size="12"
                color="#aaaaaa"
              ></u-icon>
            </u-form-item>
            <u-form-item label="许可证" v-if="form.license_type != 1">
              <u-upload
                :class="
                  form.specialLicenseFiles.length == 0 ? 'shop2-3-upload' : ''
                "
                @afterRead="afterRead($event, 'licenseNumber')"
                @delete="deletePic($event, 'licenseNumber')"
                accept="image"
                :uploadIcon="
                  form.specialLicenseFiles.length == 0 ? '' : 'camera-fill'
                "
                :fileList="form.specialLicenseFiles"
                :max-count="5"
                :maxSize="maxSize"
                @oversize="overSize"
                width="125"
                height="88"
              ></u-upload>
            </u-form-item>
            <u-form-item
              label="许可证编号"
              prop="license_number"
              v-if="form.license_type != 1"
            >
              <u-input
                class="form-input"
                v-model="form.license_number"
                placeholder="请输入许可证编号"
              />
            </u-form-item>
          </template>
        </u-form>
      </view>

      <view class="up-block up-block-3" v-show="active == 0">
        <view class="up-title">法人信息</view>
        <view class="up-block-3-content">
          <u-upload
            :class="fileList3.length == 0 ? 'shop2-4-upload' : ''"
            @afterRead="afterRead($event, 'idFront')"
            @delete="deletePic($event, 'idFront')"
            accept="image"
            :fileList="fileList3"
            :max-count="1"
            width="180"
            height="110"
            uploadIcon=""
            :maxSize="maxSize"
            @oversize="overSize"
          ></u-upload>
          <u-upload
            :class="fileList4.length == 0 ? 'shop2-5-upload' : ''"
            @afterRead="afterRead($event, 'idReverse')"
            @delete="deletePic($event, 'idReverse')"
            accept="image"
            :fileList="fileList4"
            :max-count="1"
            width="180"
            height="110"
            uploadIcon=""
            :maxSize="maxSize"
            @oversize="overSize"
          ></u-upload>
        </view>
        <u-form
          v-show="fileList3.length"
          :model="form"
          class="form"
          ref="uForm3"
          label-width="100"
        >
          <u-form-item
            label="身份证号码"
            prop="legal_person_id_number"
            required
          >
            <u-input
              class="form-input"
              maxlength="18"
              v-model="form.legal_person_id_number"
              placeholder="请输入身份证号码"
            />
          </u-form-item>
          <u-form-item label="身份证地址" prop="legal_person_id_addr" required>
            <u-input
              class="form-input"
              maxlength="18"
              v-model="form.legal_person_id_addr"
              placeholder="请输入身份证地址"
            />
          </u-form-item>
          <u-form-item
            v-show="fileList4.length"
            label="生效日期"
            prop="legal_person_id_number"
            @click="showStartTime = true"
            required
          >
            <u-input
              class="form-input"
              maxlength="18"
              v-model="form.legal_person_id_period_begin"
              placeholder="请选择身份证有效生日"
            />
            <u-icon
              style="display: inline-block; margin-left: 8rpx"
              name="arrow-down"
              size="12"
              color="#aaaaaa"
            ></u-icon>
          </u-form-item>
          <u-form-item
            v-show="fileList4.length"
            label="截止日期"
            prop="legal_person_id_period_end"
            required
            @click="handelShowEndTime()"
          >
            <u-input
              class="form-input"
              maxlength="18"
              v-model="form.legal_person_id_period_end"
              placeholder="请选择身份证截止日期"
            />
            <tui-radio-group class="id-radio-group" @change="handelRaddio">
              <view v-for="(item, index) in radioItems">
                <tui-radio
                  class="id-radio"
                  :key="index"
                  :checked="item.checked"
                  :value="item.value"
                  color="#07c160"
                  borderColor="#999"
                ></tui-radio>
                <text class="id-radio-text">{{ item.name }}</text>
              </view>
            </tui-radio-group>
            <u-icon
              v-if="form.legal_person_id_period_end != '长期'"
              style="display: inline-block; margin-left: 8rpx"
              name="arrow-down"
              size="12"
              color="#aaaaaa"
            ></u-icon>
          </u-form-item>
        </u-form>
      </view>

      <!--个人-->
      <view class="up-block up-block-3" v-show="active == 1">
        <view class="up-title">个人信息</view>
        <view class="up-block-3-content">
          <u-upload
            :class="fileList5.length == 0 ? 'shop2-4-upload' : ''"
            @afterRead="afterRead($event, 'personIdFront')"
            @delete="deletePic($event, 'personIdFront')"
            accept="image"
            :fileList="fileList5"
            :max-count="1"
            width="180"
            height="110"
            :upload-text="''"
            uploadIcon=""
            :maxSize="maxSize"
            @oversize="overSize"
          ></u-upload>
          <u-upload
            :class="fileList6.length == 0 ? 'shop2-5-upload' : ''"
            @afterRead="afterRead($event, 'personIdReverse')"
            @delete="deletePic($event, 'personIdReverse')"
            accept="image"
            :fileList="fileList6"
            :max-count="1"
            width="180"
            height="110"
            :upload-text="''"
            uploadIcon=""
            :maxSize="maxSize"
            @oversize="overSize"
          ></u-upload>
        </view>
        <u-form
          :model="form2"
          class="form"
          ref="uForm2"
          label-width="100"
          v-show="fileList5.length"
        >
          <u-form-item label="身份证号码" prop="individual_id_number" required>
            <u-input
              class="form-input"
              maxlength="18"
              v-model="form2.individual_id_number"
              placeholder="请输入身份证号码"
            />
          </u-form-item>
          <u-form-item label="姓名" prop="individual_id_name" required>
            <u-input
              class="form-input"
              maxlength="18"
              v-model="form2.individual_id_name"
              placeholder="请输入姓名"
            />
          </u-form-item>
          <u-form-item
            v-show="fileList6.length"
            label="生效日期"
            prop="individual_id_period_begin"
            @click="showStartTime = true"
            required
          >
            <u-input
              class="form-input"
              maxlength="18"
              v-model="form2.individual_id_period_begin"
              placeholder="请选择身份证有效生日"
            />
            <u-icon
              style="display: inline-block; margin-left: 8rpx"
              name="arrow-down"
              size="12"
              color="#aaaaaa"
            ></u-icon>
          </u-form-item>
          <u-form-item
            v-show="fileList6.length"
            label="截止日期"
            prop="individual_id_period_end"
            required
            @click="handelShowEndTime()"
          >
            <u-input
              class="form-input"
              maxlength="18"
              v-model="form2.individual_id_period_end"
              placeholder="请选择身份证截止日期"
            />
            <tui-radio-group class="id-radio-group" @change="handelRaddio">
              <view v-for="(item, index) in radioItems">
                <tui-radio
                  class="id-radio"
                  :key="index"
                  :checked="item.checked"
                  :value="item.value"
                  color="#07c160"
                  borderColor="#999"
                ></tui-radio>
                <text class="id-radio-text">{{ item.name }}</text>
              </view>
            </tui-radio-group>
            <u-icon
              v-if="form.individual_id_period_end != '长期'"
              style="display: inline-block; margin-left: 8rpx"
              name="arrow-down"
              size="12"
              color="#aaaaaa"
            ></u-icon>
          </u-form-item>
        </u-form>
      </view>
    </view>

    <view class="btn-content">
      <view class="myui_check_text">检查并确认营业证件信息无误</view>
      <u-button text="下一步" color="#fe4119" @click="handleNext"></u-button>
      <u-button
        text="上一步"
        class="myui_btn_prev"
        @click="handlePrev"
      ></u-button>
    </view>

    <u-popup
      class="shop2-popup"
      :mask="true"
      @close="closePopup"
      :show="showPopup"
      :closeable="true"
      mode="bottom"
      :mask-close-able="true"
      :safe-area-inset-bottom="true"
    >
      <view class="popup-content">
        <view class="popup-title">可上传证件类型</view>
        <view class="popup-tips">
          请根据您的主营品类上传真实有效的许可证，能够提高入驻通过的效率。目前支持的许可证如下：
        </view>
        <view class="popuo-prove-item">
          <view class="item-title">许可证</view>
          <view class="item-content">
            《食品经营许可证》丶《餐饮服务许可证》丶《食品流通许可证》丶《药品经营许可证》丶《医疗器械经营许可证》丶《互联网药品信息服务资格证书》
          </view>
        </view>
        <view class="popuo-prove-item">
          <view class="item-title">特许证件</view>
          <view class="item-content">
            《第二类医疗器械经营备案凭证》丶《上海便民饮食店临时备案公示卡》丶《兽药经营许可证》丶《动物诊疗许可证》丶《食品生产经营登记证》
          </view>
        </view>
        <view class="popuo-prove-item">
          <view class="item-title">其他证件</view>
          <view class="item-content">
            支持各种小证,因各地监管规则不一,请联系客服获取其他小证支持情况的详细。
          </view>
        </view>
        <u-button class="btn-queren" @click="showPopup = false">
          我知道了
        </u-button>
      </view>
    </u-popup>

    <u-picker
      :show="showPicker"
      :columns="columns"
      :safe-area-inset-bottom="true"
      :default-selector="[0]"
      :keyName="'name'"
      @cancel="handleCancel"
      @confirm="handleConfirm"
    ></u-picker>
    <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-toast ref="uToast" />
    <u-loading-page
      :loading="loading"
      bgColor="rgba(0,0,0,0.5)"
      fontSize="32rpx"
      color="#fff"
      loadingText="数据正在加载中..."
    ></u-loading-page>
  </view>
</template>

<script>
import { mapActions } from "vuex";
import {
  UploadFilePromise,
  batchNoApi,
  imgOcrResultApi,
} from "../../api/upload";
import navBar from "@/components/uni-nav-bar/uni-nav-bar";
import tuiRadio from "@/components/tui-radio/tui-radio.vue";
import tuiRadioGroup from "@/components/tui-radio-group/tui-radio-group.vue";
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,
    tuiRadio,
    tuiRadioGroup,
  },
  data() {
    return {
      active: 0,
      showPopup: false,
      showPicker: false,
      showStartTime: false,
      showEndTime: false,
      loading: false,
      startTime: null,
      endTime: null,
      startMinDate: 0,
      endMinDate: 0,
      endMaxDate: 0,
      list: [
        {
          name: "企业类型",
        },
        {
          name: "个人类型",
        },
      ],
      radioItems: [
        {
          name: "非长期",
          value: "1",
          checked: true,
        },
        {
          name: "长期",
          value: "2",
          checked: false,
        },
      ],
      form: {
        license_type: 1, // 所属行业
        license_image: "", // 许可证路径
        biz_license_number: "", //注册号
        biz_license_company: "", // 公司真实名字
        biz_license_image: "", // 营业执照路径
        legal_person_name: "", //法人姓名
        legal_person_mobile: "", //法人手机号
        legal_person_id_number: "", //法人身份证号
        legal_person_id_images: "", //身份证图片正面路径
        legal_person_id_images2: "", // 身份证图片反面路径
        legal_person_id_addr: "", // 身份证地址
        legal_person_id_period_begin: "", //身份证开始有效日期
        legal_person_id_period_end: "", // 身份证截止日期
        biz_license_period_begin: "",
        biz_license_period_end: "9999-12-31",
        businessLicenseFiles: [],
        specialLicenseFiles: [],
      },
      form2: {
        individual_id_number: "", // 个人身份证号码
        individual_id_images: "", // 个人身份证图片正面路径
        individual_id_images2: "", //个人身份证图片反面路径
        individual_id_name: "", //个人身份证姓名
        individual_id_addr: "", //个人身份证地址
        individual_id_period_begin: "", // 个人身份证开始有效日期
        individual_id_period_end: "", // 个人身份证截止日期
      },
      license_type_name: "",
      orcTimeout: null,
      action: "",
      limitType: ["png", "jpg", "jpeg"], //允许的图片后缀
      fileMaxSize: 1 * 1024 * 1024, // 超出1M开启压缩
      maxSize: 10 * 1024 * 1024, //图片最大不能超过10M
      fileMinSize: 5 * 1024, // 最小为5KB
      fileList: [],
      fileList2: [],
      fileList3: [],
      fileList4: [],
      fileList5: [], //个人身份证正面
      fileList6: [], //个人身份证反面
      columns: [
        [
          {
            id: 1,
            name: "无需特殊资质",
          },
          {
            id: 2,
            name: "需许可证资质",
          },
          {
            id: 3,
            name: "需特许证件资质",
          },
        ],
      ],
      rules: {
        biz_license_company: {
          required: true,
          message: "请输入公司名称",
          trigger: ["change", "blur"],
        },
        legal_person_name: {
          required: true,
          message: "请输入姓名",
          trigger: ["change", "blur"],
        },
        legal_person_mobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: ["change", "blur"],
          },
          {
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // uni.$u.test.mobile()就是返回true或者false的
              return uni.$u.test.mobile(value);
            },
            message: "手机号码不正确",
            // 触发器可以同时用blur和change
            trigger: ["blur"],
          },
        ],
        legal_person_id_addr: {
          required: true,
          message: "请输入身份证的地址",
          trigger: ["change", "blur"],
        },
        legal_person_id_number: [
          {
            required: true,
            message: "请输入身份证号",
            trigger: ["change", "blur"],
          },
          {
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // uni.$u.test.mobile()就是返回true或者false的
              return uni.$u.test.idCard(value);
            },
            message: "身份证号不正确",
            // 触发器可以同时用blur和change
            trigger: ["blur"],
          },
        ],
        legal_person_id_period_begin: [
          {
            type: "string",
            required: true,
            message: "请选择身份证开始有效日期",
            trigger: ["change"],
          },
        ],
        legal_person_id_period_end: [
          {
            type: "string",
            required: true,
            message: "请选择身份证截止日期",
            trigger: ["change"],
          },
        ],
        biz_license_content: {
          required: true,
          message: "请输入经营范围",
          trigger: ["change", "blur"],
        },
      },
      rules2: {
        individual_id_number: [
          {
            required: true,
            message: "请输入个人身份证号",
            trigger: ["change", "blur"],
          },
          {
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // uni.$u.test.mobile()就是返回true或者false的
              return uni.$u.test.idCard(value);
            },
            message: "身份证号不正确",
            // 触发器可以同时用blur和change
            trigger: ["blur"],
          },
        ],
        individual_id_name: [
          {
            required: true,
            message: "请输入姓名",
            trigger: ["change", "blur"],
          },
        ],
        individual_id_period_begin: [
          {
            type: "string",
            required: true,
            message: "请选择身份证开始有效日期",
            trigger: ["change"],
          },
        ],
        individual_id_period_end: [
          {
            type: "string",
            required: true,
            message: "请选择身份证截止日期",
            trigger: ["change"],
          },
        ],
      },
    };
  },
  onReady() {
    this.$refs["uForm"].setRules(this.rules);
    // this.$refs["uForm2"]?.setRules(this.rules2);
  },
  mounted() {
    this.license_type_name = this.columns?.[0].filter(
      (item) => item.id == this.form.license_type
    )?.[0].name;

    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();
    },
    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) => {
            console.log("压缩成功", res);
            reslove(res.tempFilePath); //压缩成功返回的路径
          },
          fail: (error) => {
            console.log("压缩失败", error);
            this.loading = false;
          },
        });
      });
    },

    async getOcrText(filePath, file, type) {
      return new Promise(async (resolve, reject) => {
        this.loading = true;
        //#ifdef APP-PLUS
        try {
          filePath = await this.compressImage(filePath);
        } catch (error) {
          console.log(error);
        }

        //#endif

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

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

        let size = getBase64Size(filePath);
        console.log("OCR上图图片压缩后为：", size);

        //#endif
        try {
          const batchNoRes = await batchNoApi(filePath, file, type);
          console.log("batchNoRes", batchNoRes);
          if (!batchNoRes) {
            this.loading = false;
            reject(batchNoRes);
          }

          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);
            console.log("imgOcrRes", imgOcrRes);
            if (imgOcrRes.status == 250) {
              switch (type) {
                case "FR_ID_CARD_FRONT":
                  uni.showToast({
                    title: "上传身份证正面图片错误,请重新上传",
                    icon: "none",
                    duration: 2000,
                  });

                  this.form.legal_person_id_images = "";
                  this.fileList3.splice(0, 1);
                  console.log(this.fileList3);
                  break;
                case "FR_ID_CARD_BEHIND":
                  uni.showToast({
                    title: "上传身份证反面图片错误,请重新上传",
                    icon: "none",
                    duration: 2000,
                  });
                  this.form.legal_person_id_images2 = "";
                  this.fileList4.splice(0, 1);
                  break;
                case "ID_CARD_FRONT":
                  uni.showToast({
                    title: "上传身份证正面图片错误,请重新上传",
                    icon: "none",
                    duration: 2000,
                  });
                  this.form2.individual_id_images = "";
                  this.fileList5.splice(0, 1);
                  break;
                case "ID_CARD_BEHIND":
                  uni.showToast({
                    title: "上传身份证反面图片错误,请重新上传",
                    icon: "none",
                    duration: 2000,
                  });
                  this.form2.individual_id_images2 = "";
                  this.fileList6.splice(0, 1);
                  break;
                case "BUSINESS_LICENCE":
                  uni.showToast({
                    title: "营业图片上传有误,请重新上传",
                    icon: "none",
                    duration: 2000,
                  });
                  this.form.biz_license_image = "";
                  this.fileList.splice(0, 1);
                  break;
              }
            }
            clearTimeout(this.orcTimeout);
            this.loading = false;
            resolve(imgOcrRes?.data);
          }, 1000);
        } catch (error) {
          console.log(error);
        }
      });
    },
    /**判断文件类型是否正确 */
    isAssetTypeAnImage(ext) {
      const str = ext.split(".")[1];
      return this.limitType.indexOf(str.toLowerCase()) !== -1;
    },
    // 上传图片
    async afterRead(event, type) {
      var item = event.file;
      var imgUrl = item.url;

      const group = {
        url: imgUrl,
      };

      switch (type) {
        case "businessLicense":
          this.form.businessLicenseFiles.push(group);
          break;
        case "licenseNumber":
          this.fileList2.push(group);
          this.form.specialLicenseFiles.push(group);
          break;
        case "idFront":
          this.fileList3.push(group);
          break;
        case "idReverse":
          this.fileList4.push(group);
          break;
        case "personIdFront":
          this.fileList5.push(group);
          break;
        case "personIdReverse":
          this.fileList6.push(group);
          break;
      }
      //#ifdef H5
      imgUrl = await H5compressImg(imgUrl, 0.75);

      let size = getBase64Size(imgUrl);

      console.log("上传图片压缩后的大小为:", size);
      //#endif

      let res = await UploadFilePromise(imgUrl);

      if (res && res.status == 200) {
        switch (type) {
          case "businessLicense":
            this.form.biz_license_image = res.data.url;
            break;
          case "licenseNumber":
            if (this.form.license_image == "") {
              this.form.license_image = String(res.data.url);
            } else {
              this.form.license_image += "," + String(res.data.url);
            }
            break;
          case "idFront":
            this.form.legal_person_id_images = res.data.url;
            break;
          case "idReverse":
            this.form.legal_person_id_images2 = res.data.url;
            break;
          case "personIdFront":
            this.form2.individual_id_images = res.data.url;
            break;
          case "personIdReverse":
            this.form2.individual_id_images2 = res.data.url;
            break;
        }
      }

      const formatDateString = (dateStr) => {
        if (dateStr.length === 8) {
          // 假设是 YYYYMMDD 格式
          const year = dateStr.substring(0, 4);
          const month = dateStr.substring(4, 6);
          const day = dateStr.substring(6, 8);
          return `${year}-${month}-${day}`;
        }
        // 如果不是8位，返回原字符串或其他默认处理
        return dateStr;
      };

      switch (type) {
        case "businessLicense":
          var ocr = await this.getOcrText(
            imgUrl,
            item,
            orcImgTypeConf.BUSINESS_LICENCE
          );
          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 || "";
          this.form.biz_license_period_begin = ocr.bizLicenseStartTime
            .replace(/年|月|日/g, "-")
            .replace(/-$/g, "")
            .replace(/-+/g, "-");
          console.log("BUSINESS_LICENCE", ocr);
          break;
        case "licenseNumber":
          break;
        case "idFront":
          var ocr = await this.getOcrText(
            imgUrl,
            item,
            orcImgTypeConf.FR_ID_CARD_FRONT
          );

          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 "idReverse":
          var ocr = await this.getOcrText(
            imgUrl,
            item,
            orcImgTypeConf.FR_ID_CARD_BEHIND
          );

          if (ocr && ocr.validity) {
            let validity = ocr.validity.split("-");
            this.startTime = validity[0];
            this.endTime = validity[1];

            this.form.legal_person_id_period_begin = formatDateString(
              this.startTime
            );
            this.form.legal_person_id_period_end = formatDateString(
              this.endTime
            );
          }

          break;
        case "personIdFront":
          var ocr = await this.getOcrText(
            imgUrl,
            item,
            orcImgTypeConf.ID_CARD_FRONT
          );

          this.form2.individual_id_name = ocr.name;
          this.form2.individual_id_number = ocr.idNumber;
          this.form2.individual_id_addr = ocr.address;
          console.log("personIdFront", ocr);
          break;
        case "personIdReverse":
          var ocr = await this.getOcrText(
            imgUrl,
            item,
            orcImgTypeConf.ID_CARD_BEHIND
          );

          if (ocr && ocr.validity) {
            let validity = ocr.validity.split("-");
            this.startTime = validity[0];
            this.endTime = validity[1];

            this.form2.individual_id_period_begin = formatDateString(
              this.startTime
            );
            this.form2.individual_id_period_end = formatDateString(
              this.endTime
            );
          }
          console.log("personIdFront", ocr);
          break;
      }
    },
    deletePic(e, type) {
      switch (type) {
        case "businessLicense":
          this.form.businessLicenseFiles.splice(0, 1);
          break;
        case "licenseNumber":
          this.form.specialLicenseFiles.splice(e.index, 1);
          let arr = this.form.license_image.split(",");
          arr.splice(e.index, 1);
          this.form.license_image = arr.join(",");
          break;
        case "idFront":
          this.fileList3.splice(0, 1);
          this.form.legal_person_id_number = "";
          this.form.legal_person_id_images = "";
          this.form.legal_person_id_addr = "";
          break;
        case "idReverse":
          this.fileList4.splice(0, 1);
          this.form.legal_person_id_images2 = "";
          this.form.legal_person_id_period_begin = "";
          this.form.legal_person_id_period_end = "";
          break;
        case "personIdFront":
          this.fileList5.splice(0, 1);
          this.form2.individual_id_number = "";
          this.form2.individual_id_images = "";
          this.form2.individual_id_name = "";
          this.form2.individual_id_addr = "";
          break;
        case "personIdReverse":
          this.fileList6.splice(0, 1);
          this.form2.individual_id_period_begin = "";
          this.form2.individual_id_period_end = "";
          break;
      }
    },
    handleSubsection(e) {
      this.active = e;
      // this.form.businessLicenseFiles = [];
      // this.form.specialLicenseFiles = [];
      // this.fileList3 = [];
      // this.fileList4 = [];
      // this.fileList5 = [];
      // this.fileList6 = [];
      this.minDate = 0;
      if (e == 1) {
        this.$refs.uForm2.setRules(this.rules2);
        this.form.legal_person_id_period_begin = "";
        this.form.legal_person_id_period_end = "";
      } else {
        this.individual_id_period_begin = "";
        this.individual_id_period_end = "";
      }
    },
    handlePopup() {
      this.showPopup = true;
    },
    closePopup() {
      this.showPopup = false;
    },
    handleNext() {
      let auditItem = uni.getStorageSync("auditItem");

      if (this.active == 0) {
        this.$refs.uForm.validate().then((valid) => {
          if (!this.form.biz_license_image) {
            this.$refs.uToast.show({
              message: "请上营业执照片",
              type: "error",
              duration: 2000,
            });
            return;
          }

          // if (!this.form.license_image) {
          //   this.$refs.uToast.show({
          //     message: "请上许可证照片",
          //     type: "error",
          //     duration: 2000,
          //   });
          //   return;
          // }

          if (!this.form.legal_person_id_images) {
            this.$refs.uToast.show({
              message: "请上身份证图片正面照片",
              type: "error",
              duration: 2000,
            });
            return;
          }

          if (!this.form.legal_person_id_images2) {
            this.$refs.uToast.show({
              message: "请上身份证图片反面照片",
              type: "error",
              duration: 2000,
            });
            return;
          }

          if (valid) {
            auditItem = {
              ...auditItem,
              ...this.form,
            };

            auditItem.entity_type = this.active + 1;
            // auditItem.license_type = this.licenseType.id;
            // auditItem.license_image = JSON.stringify(this.form.specialLicenseFiles.join(","));

            uni.setStorageSync("auditItem", auditItem);

            uni.navigateTo({
              url: "/pages/audit/shop3",
            });
          }
        });
      } else {
        this.$refs.uForm2.validate().then((valid) => {
          if (!this.form2.individual_id_images) {
            this.$refs.uToast.show({
              message: "请上身份证图片反面照片",
              type: "error",
              duration: 2000,
            });
            return;
          }

          if (!this.form2.individual_id_images2) {
            this.$refs.uToast.show({
              message: "请上身份证图片反面照片",
              type: "error",
              duration: 2000,
            });
            return;
          }

          if (valid) {
            auditItem = {
              ...auditItem,
              ...this.form2,
            };

            auditItem.entity_type = this.active + 1;

            uni.setStorageSync("auditItem", auditItem);

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

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

    handleCancel() {
      this.showPicker = false;
    },

    handleConfirm(e) {
      this.form.license_type = e.value[0].id;
      this.license_type_name = e.value[0].name;
      this.licenseType = e.value[0];

      this.showPicker = false;
    },
    handelShowEndTime() {
      if (
        this.form.legal_person_id_period_end == "长期" ||
        this.form2.individual_id_period_end == "长期"
      )
        return;
      this.showEndTime = true;
    },
    handelStartTime(e) {
      this.startTime = e.value;
      this.showStartTime = false;
      if (this.active == 0) {
        this.form.legal_person_id_period_begin = uni.$u.timeFormat(
          this.startTime,
          "yyyy-mm-dd"
        );
      } else {
        this.form2.individual_id_period_begin = uni.$u.timeFormat(
          this.startTime,
          "yyyy-mm-dd"
        );
      }
    },
    handelEndTime(e) {
      this.endTime = e.value;
      this.showEndTime = false;
      if (this.active == 0) {
        this.form.legal_person_id_period_end = uni.$u.timeFormat(
          this.endTime,
          "yyyy-mm-dd"
        );
      } else {
        this.form2.individual_id_period_end = uni.$u.timeFormat(
          this.endTime,
          "yyyy-mm-dd"
        );
      }
    },
    handelRaddio(e) {
      if (e && e.detail.value == 2) {
        if (this.active == 0) {
          this.form.legal_person_id_period_end = "长期";
        } else {
          this.form2.individual_id_period_end = "长期";
        }
      } else {
        if (this.active == 0) {
          this.form.legal_person_id_period_end = "";
        } else {
          this.form2.individual_id_period_end = "";
        }
      }
    },
    loginOut() {
      this.$store.dispatch("user/LoginOut");
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
page {
  background: #f2f2f2;
}
.shop-2-container {
  // background: #f2f2f2;
  // height: 100vh;

  .u-navbar {
    height: 88rpx;
  }

  .subsection {
    height: 80rpx;
  }

  .up-block {
    background: #fff;
    padding: 24rpx 24rpx;
    margin-bottom: 20rpx;

    .up-title {
      font-weight: bold;
      margin-bottom: 40rpx;
    }
  }

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

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

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

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

  .up-block-2 {
    // margin: 20rpx 0;
    padding: 24rpx 24rpx 24rpx 32rpx;
  }

  .up-block-3-content {
    display: flex;
  }

  .shop-2-content {
    margin-top: 20rpx;
  }

  .shop2-popup {
    .popup-content {
      padding: 0 24rpx;
      height: 540px;

      .popup-title {
        font-weight: bold;
        text-align: center;
        height: 90rpx;
        line-height: 90rpx;
        font-size: 36rpx;
      }

      .popup-tips {
        margin: 24rpx 0;
        font-weight: 500;
      }

      .popuo-prove-item {
        margin: 48rpx 0;
        padding: 24rpx;
        border-radius: 24rpx;
        border: 1px solid #ccc;

        .item-title {
          margin-bottom: 16rpx;
          font-size: 28rpx;
          font-weight: bold;
        }

        .item-content {
          font-size: 24rpx;
        }
      }
    }

    .btn-queren {
      background: $base-color;
      color: #fff;
    }
  }

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

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

  .color_red {
    color: red;
  }

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

  ::v-deep.u-upload__deletable {
    width: 40rpx;
    height: 40rpx;

    .uicon-close {
      font-size: 28rpx !important;
      top: 8rpx !important;
    }
  }
}
</style>
