<template>
  <form @submit="formSubmit" class="form-container">
    <view class="form-step" v-if="pageType != '3'">
      <view class="step-title">第三步：结算卡信息</view>
      <view class="step-tip">共三步</view>
    </view>
    <view class="form-list">
      <view class="form-list-title" v-if="pageType != '3'">
        <text>结算卡信息</text>
      </view>
      <view class="form-item u-flex-center-sb">
        <view class="form-label"
          ><text class="required">*</text>银行卡类型：</view
        >
        <view class="form-value" @click.stop="openSheet">
          <template v-if="formData.accountType">
            <text
              v-for="item in listType"
              :key="item.value"
              v-show="item.value == formData.accountType"
              >{{ item.name }}</text
            >
            <text class="iconfont rotate" v-if="pageType != '3'">&#xe671;</text>
          </template>
          <text class="placeholder" v-else>请选择(必填)</text>
        </view>
      </view>
      <view class="form-item">
        <view class="form-label"
          ><text class="required">*</text>银行卡照片正面：</view
        >
        <view class="form-value upload-view">
          <uploadImg
            name="cardFrontUrl"
            v-model="formData.cardFrontUrl"
            :uploadImgCount="1"
            :imgCount="1"
            key="cardFrontUrl"
            :type="disabled ? 'view' : 'add'"
            @result="uploadImgResult($event, 1)"
          />
        </view>
      </view>

      <view class="form-item">
        <view class="form-label"
          ><text class="required">*</text>银行卡照片反面：</view
        >
        <view class="form-value upload-view">
          <uploadImg
            name="cardBackUrl"
            v-model="formData.cardBackUrl"
            :uploadImgCount="1"
            :imgCount="1"
            key="cardBackUrl"
            :type="disabled ? 'view' : 'add'"
          />
        </view>
      </view>
      <view class="form-item u-flex-center-sb">
        <view class="form-label"
          ><text class="required">*</text>银行卡开户名：</view
        >
        <view class="form-value">
          <input
            :disabled="disabled"
            name="accountHolderName"
            placeholder="请输入（必填）"
            v-model="formData.accountHolderName"
            placeholder-style="color: #cccccc"
          />
        </view>
      </view>

      <view class="form-item u-flex-center-sb">
        <view class="form-label"><text class="required">*</text>卡号：</view>
        <view class="form-value">
          <input
            :disabled="disabled"
            name="bankCardNumber"
            placeholder="请输入（必填）"
            v-model="formData.bankCardNumber"
            placeholder-style="color: #cccccc"
          />
        </view>
      </view>

      <!-- 对公 -->
      <template v-if="formData.accountType == 'corporate'">
        <view class="form-item u-flex-center-sb">
          <view class="form-label"
            ><text class="required">*</text>银行总行：</view
          >
          <view class="form-value">
            <input
              :disabled="disabled"
              name="bankName"
              placeholder="请输入（必填）"
              v-model="formData.bankName"
              placeholder-style="color: #cccccc"
            />
          </view>
        </view>

        <view class="form-item u-flex-center-sb">
          <view class="form-label"
            ><text class="required">*</text>支行名称：</view
          >
          <view class="form-value">
            <input
              :disabled="disabled"
              name="subBranchName"
              placeholder="请输入（必填）"
              v-model="formData.subBranchName"
              placeholder-style="color: #cccccc"
            />
          </view>
        </view>

        <view class="form-item u-flex-center-sb">
          <view class="form-label"
            ><text class="required">*</text>银行卡开户地：</view
          >
          <view class="form-value" @click="openAreaSelect(2)">
            <!-- <input placeholder="" v-model="formData.region" /> -->
            <text v-if="formData.bankProvinceName">{{
              formData.bankProvinceName +
              formData.bankCityName +
              formData.bankAreaName
            }}</text>
            <text class="placeholder" v-else>请选择(必填)</text>
          </view>
        </view>

        <view class="form-item">
          <view class="form-label"
            ><text class="required">*</text>开户许可证：</view
          >
          <view class="form-value upload-view">
            <uploadImg
              name="openLicenseUrl"
              v-model="formData.openLicenseUrl"
              :uploadImgCount="1"
              :imgCount="1"
              key="openLicenseUrl"
              :type="disabled ? 'view' : 'add'"
            />
          </view>
        </view>
      </template>

      <template
        v-if="
          formData.accountType == 'for_private_legal_entities' ||
          formData.accountType == 'for_private_non_legal_entities'
        "
      >
        <view
          class="form-item u-flex-center-sb"
          v-if="formData.accountType == 'for_private_non_legal_entities'"
        >
          <view class="form-label"
            ><text class="required">*</text>开户地点：</view
          >
          <view class="form-value" @click="openAreaSelect(2)">
            <!-- <input placeholder="" v-model="formData.region" /> -->
            <text v-if="formData.bankProvinceName">{{
              formData.bankProvinceName +
              formData.bankCityName +
              formData.bankAreaName
            }}</text>
            <text class="placeholder" v-else>请选择(必填)</text>
          </view>
        </view>

        <view class="form-item">
          <view class="form-label"
            ><text class="required">*</text>结算人身份证人像面：</view
          >
          <view class="form-value upload-view">
            <uploadImg
              name="settlementIdCardFrontUrl"
              v-model="formData.settlementIdCardFrontUrl"
              :uploadImgCount="1"
              :imgCount="1"
              key="settlementIdCardFrontUrl"
              :type="disabled ? 'view' : 'add'"
              @result="uploadImgResult($event, 2)"
            />
          </view>
        </view>

        <view class="form-item">
          <view class="form-label"
            ><text class="required">*</text>结算人身份证国徽面：</view
          >
          <view class="form-value upload-view">
            <uploadImg
              name="settlementIdCardBackUrl"
              v-model="formData.settlementIdCardBackUrl"
              :uploadImgCount="1"
              :imgCount="1"
              key="settlementIdCardBackUrl"
              :type="disabled ? 'view' : 'add'"
              @result="uploadImgResult($event, 3)"
            />
          </view>
        </view>

        <view class="form-item u-flex-center-sb">
          <view class="form-label"
            ><text class="required">*</text>持卡人姓名：</view
          >
          <view class="form-value">
            <input
              :disabled="disabled"
              name="settlementName"
              placeholder="请输入（必填）"
              v-model="formData.settlementName"
              placeholder-style="color: #cccccc"
            />
          </view>
        </view>

        <view class="form-item u-flex-center-sb">
          <view class="form-label"
            ><text class="required">*</text>身份证号码：</view
          >
          <view class="form-value">
            <input
              :disabled="disabled"
              name="settlementIdCard"
              placeholder="请输入（必填）"
              v-model="formData.settlementIdCard"
              placeholder-style="color: #cccccc"
            />
          </view>
        </view>

        <view class="form-item u-flex-center-sb">
          <view class="form-label"
            ><text class="required">*</text>身份证起始有效期：</view
          >
          <view class="form-value" @click="openCalendar(1)">
            <text v-if="formData.settlementIdValidStart">{{
              formData.settlementIdValidStart
            }}</text>
            <text class="placeholder" v-else>请选择(必填)</text>
          </view>
        </view>

        <view class="form-item u-flex-center-sb">
          <view class="form-label"
            ><text class="required">*</text>身份证结束有效期：</view
          >
          <view class="form-value" @click="openCalendar(2)">
            <text v-if="formData.settlementIdValidEnd">{{
              formData.settlementIdValidEnd
            }}</text>
            <text class="placeholder" v-else>请选择(必填)</text>
          </view>
        </view>

        <view class="form-item u-flex-center-sb">
          <view class="form-label"
            ><text class="required">*</text>持卡人手机号：</view
          >
          <view class="form-value">
            <input
              :disabled="disabled"
              name="settlementPhone"
              placeholder="请输入（必填）"
              v-model="formData.settlementPhone"
              placeholder-style="color: #cccccc"
              type="number"
              maxlength="11"
            />
          </view>
        </view>

        <view
          class="form-item"
          v-if="formData.accountType == 'for_private_non_legal_entities'"
        >
          <view class="form-label"
            ><text class="required">*</text>授权委托书<text class="required"
              >（请保证所填信息真实性）</text
            >：</view
          >
          <view class="form-value upload-view">
            <uploadImg
              name="authorizationLetterUrl"
              v-model="formData.authorizationLetterUrl"
              :uploadImgCount="1"
              :imgCount="1"
              key="authorizationLetterUrl"
              :type="disabled ? 'view' : 'add'"
            />
            <view class="download-tips" v-if="pageType != '3'">
              请先下载并填写<text
                class="text"
                @click="openDocument(downloadUrl)"
                >《授权委托书》</text
              >
            </view>
          </view>
        </view>
      </template>
    </view>

    <view class="form-btn" v-if="pageType != '3'">
      <view class="checkbox-group-view" v-if="!disabled">
        <uv-checkbox-group
          v-model="checkAggrement"
          shape="circle"
          labelColor="#0090ff"
          iconSize="20rpx"
        >
          <uv-checkbox label="勾选注册协议及隐私声明" :name="1"></uv-checkbox>
        </uv-checkbox-group>
      </view>
      <view class="u-flex-center-sb">
        <button class="u-btn-two previous-step" @click="emit('setStep')">
          上一步
        </button>
        <button v-if="!disabled" class="u-btn-two" form-type="submit">
          立即提交
        </button>
      </view>
    </view>
  </form>
  <!-- 银行卡类型选择器 -->
  <uv-action-sheet
    ref="actionSheetRef"
    :actions="listType"
    @select="sheetSelect"
  >
  </uv-action-sheet>

  <!-- 日历组件 -->
  <uv-calendars ref="calendarsRef" @confirm="calendarsConfirm" />
</template>

<script setup name="settlementInfo">
import { reactive, ref, watch, onMounted } from "vue";
import {
  queryAuthorizationTemplateUrl_Api,
  ocrBank_Api,
  ocrIdcard_Api,
} from "@/api/index.js";
import { openDocument } from "@/util/fileDownload.js";
const emit = defineEmits(["formSubmit", "openAreaSelect", "setStep"]);
const props = defineProps({
  disabled: {
    type: Boolean,
    default: false,
  },
  formData: {
    type: Object,
    default: () => ({}),
  },
  pageType: {
    type: String,
    default: "",
  },
});
const disabled = ref(props.disabled || false);
const formData = reactive({
  accountType: "corporate",
  ...props.formData,
}); // 结算信息
const checkAggrement = ref([1]); // 是否同意协议

watch(
  () => props.formData,
  (newValue) => {
    Object.assign(formData, newValue);
  },
  { deep: true }
);
watch(
  () => props.disabled,
  (newValue) => {
    disabled.value = newValue;
  }
);
const actionSheetRef = ref(null); // 银行卡类型选择器
const listType = [
  { name: "对公", value: "corporate" },
  { name: "对私法人", value: "for_private_legal_entities" },
  { name: "对私非法人", value: "for_private_non_legal_entities" },
];
const openSheet = () => {
  if (disabled.value) return;
  actionSheetRef.value.open();
};
// 银行卡类型选择触发
const sheetSelect = (item) => {
  Object.assign(formData, { accountType: item.value });
};

// 授权委托书下载链接
const downloadUrl = ref("");
const getAuthorizationTemplateUrl = () => {
  queryAuthorizationTemplateUrl_Api().then((res) => {
    // console.log(res);
    downloadUrl.value = res.data || "";
  });
};
// 打开区域选择
const openAreaSelect = (type) => {
  emit("openAreaSelect", type);
};

// 日历组件
const calendarsRef = ref(null);
let calendarsType = null;
const openCalendar = (type) => {
  calendarsType = type;
  calendarsRef.value.open();
};
// 日历选择确认
const calendarsConfirm = (e) => {
  console.log(e);
  if (calendarsType == 1) {
    formData.settlementIdValidStart = e.fulldate || "";
  } else {
    formData.settlementIdValidEnd = e.fulldate || "";
  }
};

// 表单提交
const formSubmit = () => {
  if (!formData.accountType) {
    uni.$uv.toast("请选择账户类型");
    return false;
  }
  if (!formData.cardFrontUrl) {
    uni.$uv.toast("请上传银行卡照片正面");
    return false;
  }

  if (!formData.cardBackUrl) {
    uni.$uv.toast("请上传银行卡照片反面");
    return false;
  }

  if (!formData.accountHolderName) {
    uni.$uv.toast("请输入银行卡开户名");
    return false;
  }
  if (!formData.bankCardNumber) {
    uni.$uv.toast("请输入卡号");
    return false;
  }

  if (formData.accountType == "corporate") {
    if (!formData.bankName) {
      uni.$uv.toast("请输入银行总行");
      return false;
    }
    if (!formData.subBranchName) {
      uni.$uv.toast("请输入支行名称");
      return false;
    }
    if (!formData.bankProvinceName) {
      uni.$uv.toast("请选择银行卡开户地");
      return false;
    }
    if (!formData.openLicenseUrl) {
      uni.$uv.toast("请上传开户许可证");
      return false;
    }
  } else {
    if (
      formData.accountType == "for_private_non_legal_entities" &&
      !formData.bankProvinceName
    ) {
      uni.$uv.toast("请选择开户地点");
      return false;
    }
    if (!formData.settlementIdCardFrontUrl) {
      uni.$uv.toast("请上传结算人身份证人像面");
      return false;
    }
    if (!formData.settlementIdCardBackUrl) {
      uni.$uv.toast("请上传结算人身份证国徽面");
      return false;
    }
    if (!formData.settlementName) {
      uni.$uv.toast("请输入持卡人姓名");
      return false;
    }
    if (!formData.settlementIdCard) {
      uni.$uv.toast("请输入身份证号码");
      return false;
    }
    if (!formData.settlementIdValidStart) {
      uni.$uv.toast("请输入身份证起始有效期");
      return false;
    }
    if (!formData.settlementIdValidEnd) {
      uni.$uv.toast("请输入身份证结束有效期");
      return false;
    }
    if (!formData.settlementPhone) {
      uni.$uv.toast("请输入持卡人手机号");
      return false;
    }
    if (
      !formData.authorizationLetterUrl &&
      formData.accountType == "for_private_non_legal_entities"
    ) {
      uni.$uv.toast("请上传授权委托书");
      return false;
    }
  }
  if (!checkAggrement.value || checkAggrement.value.length == 0) {
    uni.$uv.toast("请勾选注册协议及隐私声明");
    return false;
  }
  emit("formSubmit", formData);
};
// 更新表单数据
const updateForm = (form) => {
  Object.assign(formData, form);
};

const formatDate = (dateString) => {
  // 创建一个新的日期对象
  const date = new Date(
    dateString.slice(0, 4),
    dateString.slice(4, 6) - 1,
    dateString.slice(6)
  );
  // 转换为ISO格式的字符串
  return date.toISOString().slice(0, 10);
};

// 识别图片
const uploadImgResult = (list, type) => {
  if (list && list.length > 0) {
    let objs = {
      imgHttpUrl: list[list.length - 1],
      front: type == 3 ? 0 : 1,
    };
    setTimeout(() => {
      let url = type == 1 ? ocrBank_Api : ocrIdcard_Api;
      url(objs).then((res) => {
        if (res.code == 200 && res.data) {
          if (type == 1) {
            formData.bankName = res.data.bankName;
            formData.bankCardNumber = res.data.cardNo;
          } else if (type == 2) {
            formData.settlementName = res.data.name;
            formData.settlementIdCard = res.data.idNo;
          } else {
            formData.settlementIdValidStart = formatDate(res.data.issuingTime);
            formData.settlementIdValidEnd = formatDate(res.data.overdueTime);
          }
        }
      });
    }, 100);
  }
};

onMounted(() => {
  getAuthorizationTemplateUrl();
});

defineExpose({
  updateForm,
});
</script>

<style lang="scss" scoped>
.u-btn-two.previous-step {
  background: #ffffff;
  color: #999999;
  border: 1rpx solid #999999; /* Changed from border: 1rpx solid #e5e5e5; */
  margin-right: 40rpx;
}

.download-tips {
  font-size: 28rpx;
  .text {
    color: #0090ff;
  }
}

.rotate {
  transform: rotate(90deg);
  display: inline-block;
  margin-left: 5rpx;
}
</style>
