<template>
  <!-- 只读文件 -->
  <readOnlyInfo v-if="isDisable" ref="applyInfoRef" applyName="wxpay" />
  <!-- 该页码为填写信息的组件 -->
  <view v-if="!isDisable">
    <uni-collapse ref="collapse">
      <uni-collapse-item title="主体信息" class="coll-title" :open="true">
        <view class="content">
          <JeePayForm text="选择商户类型">
            <uni-data-checkbox
              v-model="applyDetailInfo.merchantType"
              :localdata="merchantTypeList"
            ></uni-data-checkbox>
          </JeePayForm>
          <JeePayForm text="营业执照照片">
            <JeepayUpLoad
              ocrFlag="license"
              :imgUrl="applyDetailInfo.licenseImg"
              @uploadSuccess="uploadSuccess($event, 'licenseImg')"
              @clear="clear('licenseImg')"
            />
          </JeePayForm>

          <JeePayForm
            text="营业执照编号"
            v-model:value="applyDetailInfo.licenseNo"
          />
          <JeePayForm
            text="商户名称全称"
            v-model:value="applyDetailInfo.mchFullName"
          />

          <JeePayForm text="法人身份证人像面照">
            <JeepayUpLoad
              ocrFlag="idCard"
              :imgUrl="applyDetailInfo.idcard1Img"
              @uploadSuccess="uploadSuccess($event, 'idcard1Img')"
              @clear="clear('idcard1Img')"
            />
          </JeePayForm>

          <JeePayForm text="法人身份证国徽面照">
            <JeepayUpLoad
              ocrFlag="idCard"
              :imgUrl="applyDetailInfo.idcard2Img"
              @uploadSuccess="uploadSuccess($event, 'idcard2Img')"
              @clear="clear('idcard2Img')"
            />
          </JeePayForm>

          <JeePayForm
            text="法人身份证姓名"
            v-model:value="applyDetailInfo.idcardName"
          />
          <JeePayForm
            text="法人身份证号"
            v-model:value="applyDetailInfo.idcardNo"
          />

          <JeePayForm
            v-if="applyDetailInfo.merchantType == 3"
            text="法人身份证居住地址"
            v-model:value="applyDetailInfo.idcardAddress"
          />

          <JeePayForm text="法人身份证起始有效期">
            <termOfValidity
              :defaultDate="applyDetailInfo.idcardEffectBegin"
              @publicSelect="publicSelect($event, 'idcardEffectBegin')"
              :isEnd="false"
            />
          </JeePayForm>

          <JeePayForm text="法人身份证结束有效期">
            <termOfValidity
              :defaultDate="applyDetailInfo.idcardEffectEnd"
              @publicSelect="publicSelect($event, 'idcardEffectEnd')"
            />
          </JeePayForm>

          <JeePayForm
            text="经营者/法人是否为受益人"
            v-if="applyDetailInfo.merchantType == '3'"
          >
            <view>
              {{ applyDetailInfo.owner ? "是" : "否" }}
              <switch
                @change="publicSelect($event, 'owner')"
                :checked="applyDetailInfo.owner"
              />
            </view>
          </JeePayForm>

        </view>
      </uni-collapse-item>
			<!-- 受益人卡片 -->
			<ownerCard
			  v-if="applyDetailInfo.merchantType == '3'"
			  ref="ownerCardRef"
			  :isOwner="applyDetailInfo.owner"
			  :ownerInfoBack="applyDetailInfo.companyBeneficiaryList"
			/>
      <uni-collapse-item title="经营信息" class="coll-title">
        <view class="content">
          <JeePayForm
            text="商户简称"
            v-model:value="applyDetailInfo.mchShortName"
          />
          <JeePayForm
            text="客服电话"
            v-model:value="applyDetailInfo.servicePhone"
          />
          <JeePayForm
            text="门店名称"
            v-model:value="applyDetailInfo.storeName"
          />

          <JeePayForm text="商户地理位置选择省市县">
            <jeeDataPicker
              :code="areaCode"
              :localdata="address"
              @change="publicSelect($event, 'areaCode')"
              paramType="arr"
            />
          </JeePayForm>

          <JeePayForm
            text="商户详细地址"
            v-model:value="applyDetailInfo.address"
          />

          <JeePayForm text="门头照">
            <JeepayUpLoad
              ocrFlag="idCard"
              :imgUrl="applyDetailInfo.storeOuterImg"
              @uploadSuccess="uploadSuccess($event, 'storeOuterImg')"
              @clear="clear('storeOuterImg')"
            />
          </JeePayForm>

          <JeePayForm text="店内环境照">
            <JeepayUpLoad
              ocrFlag="idCard"
              :imgUrl="applyDetailInfo.storeInnerImg"
              @uploadSuccess="uploadSuccess($event, 'storeInnerImg')"
              @clear="clear('storeInnerImg')"
            />
          </JeePayForm>
        </view>
      </uni-collapse-item>
      <uni-collapse-item title="结算规则" class="coll-title">
        <view class="content">
          <JeePayForm text="结算规则信息">
            <view @click="setRulesRef.open('bottom')">{{
              setRulesText ? setRulesText : "请选择"
            }}</view>
          </JeePayForm>

          <JeePayForm text="选择行业">
            <view @click="openSecond">{{
              applyDetailInfo.mccCode ? applyDetailInfo.mccCode : "请选择"
            }}</view>
          </JeePayForm>

          <!-- 该特殊资质照，并非每个行业都必填，根据 isNeedQualification 判断-->
          <JeePayForm
            text="特殊资质照"
            :start="applyDetailInfo.isNeedQualification"
          >
            <JeepayUpLoad
              ocrFlag="idCard"
              :imgUrl="applyDetailInfo.qualifications"
              @uploadSuccess="uploadSuccess($event, 'qualifications')"
              @clear="clear('qualifications')"
            />
          </JeePayForm>

          <!-- 优惠费率活动，费率值  商户不可修改 根据 isInActivities 判断是否展开 -->
          <JeePayForm text="优惠费率活动">
            <picker
              @change="activityChange"
              :value="activityIndex"
              :range="activityList"
            >
              <view class="uni-input">{{
                activityIndex == 0
                  ? "泛行业活动【优惠区间0.2%~0.6%】"
                  : "不参与活动"
              }}</view>
            </picker>
          </JeePayForm>
          <!-- 撑开高度的元素 -->
          <!-- <view style="height: 200px"></view> -->
        </view>
      </uni-collapse-item>
      <uni-collapse-item title="结算账户" class="coll-title">
        <view class="content">
          <JeePayForm text="结算账号类型">
            <uni-data-checkbox
              v-model="applyDetailInfo.settAccountType"
              :localdata="settlementTypeList"
            ></uni-data-checkbox>
          </JeePayForm>

          <JeePayForm
            text="开户名称"
            v-model:value="applyDetailInfo.settAccountName"
          />
          <JeePayForm
            text="银行卡账号"
            v-model:value="applyDetailInfo.settAccountNo"
          />

          <JeePayForm text="开户行">
            <uni-data-picker
              :localdata="data.bankList"
              v-model="applyDetailInfo.settAccountBankName"
              :value="BankName"
              @change="BankChange"
              v-slot:default="{ data, error, options }"
            >
              {{
                applyDetailInfo.settAccountBankName
                  ? applyDetailInfo.settAccountBankName
                  : "请选择"
              }}
            </uni-data-picker>
          </JeePayForm>

          <JeePayForm text="结算银行卡分支行所在地区">
            <jeeDataPicker
              :code="bankCode"
              :localdata="address"
              @change="publicSelect($event, 'settAccountBankBranchAreaCode')"
              paramType="arr"
            />
          </JeePayForm>

          <JeePayForm
            v-if="
              !applyDetailInfo.settAccountBankName ||
              applyDetailInfo.settAccountBankName == '其他银行'
            "
            text="开户行支行名称"
            v-model:value="applyDetailInfo.settAccountBankBranchName"
          />
        </view>
      </uni-collapse-item>
      <uni-collapse-item title="超管信息" class="coll-title">
        <view class="content">
          <JeePayForm text="超管身份">
            <uni-data-checkbox
              v-model="applyDetailInfo.contactType"
              :localdata="superList"
            ></uni-data-checkbox>
          </JeePayForm>
          <template v-if="applyDetailInfo.contactType == 'SUPER'">
            <JeePayForm text="超管身份证人像面照片">
              <JeepayUpLoad
                ocrFlag="idCard"
                :imgUrl="applyDetailInfo.contactIdDocCopy"
                @uploadSuccess="uploadSuccess($event, 'contactIdDocCopy')"
                @clear="clear('contactIdDocCopy')"
              />
            </JeePayForm>

            <JeePayForm text="超管身份证国徽面照片">
              <JeepayUpLoad
                ocrFlag="idCard"
                :imgUrl="applyDetailInfo.contactIdDocCopyBack"
                @uploadSuccess="uploadSuccess($event, 'contactIdDocCopyBack')"
                @clear="clear('contactIdDocCopyBack')"
              />
            </JeePayForm>

            <JeePayForm
              text="超管身份证姓名"
              v-model:value="applyDetailInfo.contactName"
            />

            <JeePayForm
              text="超管身份证号"
              v-model:value="applyDetailInfo.contactIdNumber"
            />

            <JeePayForm text="超管身份证起始有效期">
              <termOfValidity
                :defaultDate="applyDetailInfo.contactIdDocPeriodBegin"
                @publicSelect="publicSelect($event, 'contactIdDocPeriodBegin')"
                :isEnd="false"
              />
            </JeePayForm>

            <JeePayForm text="超管身份证结束有效期">
              <termOfValidity
                :defaultDate="applyDetailInfo.contactIdDocPeriodEnd"
                @publicSelect="publicSelect($event, 'contactIdDocPeriodEnd')"
              />
            </JeePayForm>

            <JeePayForm text="业务办理授权函">
              <JeepayUpLoad
                :imgUrl="applyDetailInfo.businessAuthorizationLetter"
                @uploadSuccess="
                  uploadSuccess($event, 'businessAuthorizationLetter')
                "
                @clear="clear('businessAuthorizationLetter')"
              />
            </JeePayForm>
          </template>

          <JeePayForm
            text="手机号"
            v-model:value="applyDetailInfo.contactPhone"
          />
          <JeePayForm
            text="邮箱"
            v-model:value="applyDetailInfo.contactEmail"
          />
        </view>
      </uni-collapse-item>
      <!-- 费率组件 -->
      <defaultRate
        v-if="activityIndex == 0"
        ref="defaultRateRef"
        isCheck="all"
      />
    </uni-collapse>

    <!-- 一级类目弹窗 -->
    <uni-popup ref="setRulesRef" type="bottom">
      <scroll-view
        :scroll-y="true"
        style="width: 100%; height: 50vh; overflow: auto; background: #fff"
        class="firstradius"
      >
        <view
          v-for="(item, index) in mccWxList"
          :key="index"
          :class="{ firstradius: index === 0 }"
          class="set-rules"
          @click="selectRule(index)"
        >
          <view>
            <text>{{ item.settlementName }}</text>
            <text style="color: #8c8c8c; margin-left: 20px">{{
              item.settRule
            }}</text>
          </view>
          <view>
            <image
              v-if="index === setRulesIndex"
              src="../../static/indexImg/select-radio.svg"
              mode=""
            ></image>
            <image
              v-else
              src="../../static/indexImg/un-raido.svg"
              mode=""
            ></image>
          </view>
        </view>
      </scroll-view>
    </uni-popup>

    <!-- 二级类目弹窗 -->
    <uni-popup ref="secondListRef" type="bottom">
      <scroll-view
        :scroll-y="true"
        style="width: 100%; height: 50vh; overflow: auto; background: #fff"
        class="firstradius"
      >
        <view
          v-for="(item, index) in secondList"
          :key="index"
          :class="{ firstradius: index === 0 }"
          class="set-rules"
          @click="secondListChange(index)"
        >
          <view>
            <text>{{ item.qualificationType }}</text>
            <text style="color: #8c8c8c; margin-left: 20px">{{
              item.qualifications
            }}</text>
          </view>
          <view>
            <image
              v-if="index === secondListIndex"
              src="../../static/indexImg/select-radio.svg"
              mode=""
            ></image>
            <image
              v-else
              src="../../static/indexImg/un-raido.svg"
              mode=""
            ></image>
          </view>
        </view>
      </scroll-view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, reactive, inject, nextTick } from "vue";
import address from "@/components/applyJson/address.json"; // 地址
import mccWx from "@/components/applyJson/mccWx.json"; // 行业
import defaultRate from "../components/defaultRate.vue"; // 默认费率
import JeepayUpLoad from "@/components/JeepayUpLoad/JeepayUpLoad.vue"; // 图片上传
import readOnlyInfo from "../components/readOnlyInfo.vue"; // 只读文件
import tool from "@/util/tool.js"; // 工具类函数
import JeePayForm from "@/components/applyComponents/JeePayForm.vue"; // 通用左右结构布局
import termOfValidity from "@/components/applyComponents/termOfValidity.vue"; // 选择证件有效期
import JeeDataPicker from "@/components/applyComponents/dataPicker.vue"; // 通用级联选择
import ownerCard from "../components/ownerCard.vue"; // 受益人卡片组件
import { filterDcit } from "@/hooks/dict.js"; //字典
const merchantTypeList = reactive(filterDcit(["A1", "A2"])); //商户类型
const settlementTypeList = reactive(filterDcit(["B0", "B1"])); // 结算类型
const superList = reactive(filterDcit(["L0", "L1"])); // 超管身份

const channelInfo = inject('channelInfo')

const emit = defineEmits(["applyHandle"]);
let applyInfoRef = ref(null); // 只读组件信息
let ownerCardRef = ref(null); // 受益人卡片
const defaultRateRef = ref(null); // 默认费率组件

//一些会用到的数据
const data = reactive({
  bankList: [
    { text: "工商银行", value: "工商银行" },
    { text: "交通银行", value: "交通银行" },
    { text: "招商银行", value: "招商银行" },
    { text: "民生银行", value: "民生银行" },
    { text: "中信银行", value: "中信银行" },
    { text: "浦发银行", value: "浦发银行" },
    { text: "兴业银行", value: "兴业银行" },
    { text: "光大银行", value: "光大银行" },
    { text: "广发银行", value: "广发银行" },
    { text: "平安银行", value: "平安银行" },
    { text: "北京银行", value: "北京银行" },
    { text: "华夏银行", value: "华夏银行" },
    { text: "农业银行", value: "农业银行" },
    { text: "建设银行", value: "建设银行" },
    { text: "邮政储蓄银行", value: "邮政储蓄银行" },
    { text: "中国银行", value: "中国银行" },
    { text: "宁波银行", value: "宁波银行" },
    { text: "其他银行", value: "其他银行" },
  ],
});

// 状态: 0-未发起、 1-审核中、 2-进件成功、 3-驳回待修改、 4-待验证、 5-待签约
// 状态为 1,2,4,5 开启disable  (也就是状态不为 0 3)
let isDisable = ref(false);
if (!["0", "3", "8"].includes(channelInfo.state)) isDisable.value = true;

// 商户进件详细信息（JSON类型字符串）
const applyDetailInfo = reactive({
  merchantType: "2", // 商户类型
  settAccountType: "C",
  paywayFeeList: [],
  companyBeneficiaryList: [], // 受益人列表
	owner: false
});

// 上传图片成功 含ocr识别
const uploadSuccess = (res, name) => {
  applyDetailInfo[name] = res.data; // 图片回显

  if (name == "contactIdDocCopy") {
    applyDetailInfo.contactName = res.ocrInfo.idcardName;
    applyDetailInfo.contactIdNumber = res.ocrInfo.idcardNo;
    return;
  }
  if (name == "contactIdDocCopyBack") {
    applyDetailInfo.contactIdDocPeriodBegin = res.ocrInfo.idcardEffectBegin;
    applyDetailInfo.contactIdDocPeriodEnd = res.ocrInfo.idcardEffectEnd;
    return;
  }
  Object.assign(applyDetailInfo, res.ocrInfo); // ocr信息回显
};
// 清除图片  仅前端
const clear = (name) => (applyDetailInfo[name] = "");

// 通用选择事件回调
const publicSelect = (e, key) => {
  applyDetailInfo[key] = e.detail.value;
  if (key == "merchantType") {
    // 结算规则数组 个人是individual 企业是enterprise
    e.detail.value == 2
      ? (mccWxList.value = mccWx.individual)
      : (mccWxList.value = mccWx.enterprise);
		setRulesText.value = '' // 重置一级类目文字
		applyDetailInfo.settlementId = '' // 重置一级类目ID 	
    applyDetailInfo.mccCode = ""; // 重置二级类目
    applyDetailInfo.qualificationId = ""; // 重置二级类目
    applyDetailInfo.isNeedQualification = ""; // 是否要上传证书的标识
  } else if (key == "settAccountBankBranchAreaCode") {
    // 如果银行选择的是非其他银行，则清空 settAccountBankBranchName 字段
    applyDetailInfo.settAccountBankBranchName = "";
  }
};

/*
 * 结算规则板块
 */
let mccWxList = ref(mccWx.individual); // 结算规则数组 个人是individual 企业是enterprise 默认给individual
let setRulesIndex = ref(-1); // 一级类目 默认选中项
const setRulesRef = ref(null); // 一级类目弹窗
const setRulesText = ref(""); // 结算规则回显文字

let secondList = ref([]); // 二级类目列表

// 一级类目选择完毕
const selectRule = (index) => {
  setRulesRef.value.close();
  // 结算规则变化，重置行业/特殊资质信息
  applyDetailInfo.settlementId = mccWxList.value[index].settlementId; // 给后台的一级类目
  setRulesIndex.value = index; // 选择完一级类目的下标
  setRulesText.value = mccWxList.value[index].settlementName; // 选择完一级类目的文字
  applyDetailInfo.mccCode = ""; // 重置二级类目
  applyDetailInfo.qualificationId = ""; // 重置二级类目
  applyDetailInfo.isNeedQualification = ""; // 是否要上传证书的标识
  secondList.value = mccWxList.value[index].qualification; // 二级类目列表

  // 重置费率信息
  applyDetailInfo.isInActivities = mccWxList.value[index].isInActivities; // 是否可参与优惠费率活动

  if (!applyDetailInfo.isInActivities) {
    applyDetailInfo.activitiesId = "";
  } else {
    applyDetailInfo.activitiesId = activitiesId.value;
  }
};

const secondListRef = ref(null); // 二级类目弹窗
const secondListIndex = ref(-1); // 二级类目 默认选中项
let qualifications = ref(false); // 是否展示特殊资质照
// 二级类目选择完毕
const secondListChange = (index) => {
  secondListRef.value.close();
  secondListIndex.value = index;
  applyDetailInfo.mccCode = secondList.value[index].qualificationType; // 二级文字
  applyDetailInfo.isNeedQualification =
    secondList.value[index].isNeedQualification; // 上传特殊资质照是否必填

  applyDetailInfo.qualificationId = secondList.value[index].qualificationId; // 二级类目 code码赋值
};

// 展开选择二级行业弹窗
const openSecond = () => {
  if (!secondList.value.length)
    return uni.showToast({ title: "请先选择结算规则信息", icon: "none" });
  secondListRef.value.open("bottom");
};

let activitiesId = ref("20191030111cff5b5e"); // 参加活动ID
let activityList = ref(["泛行业活动【优惠区间0.2%~0.6%】", "不参与活动"]);
let activityIndex = ref(0); // 是否参加活动
// 选择活动回调事件
const activityChange = (e) => {
  activityIndex.value = e.detail.value;

  // 当选择不参与活动时，隐藏费率板块
  e.detail.value == 0
    ? (applyDetailInfo.activitiesId = activitiesId.value)
    : (applyDetailInfo.activitiesId = "");
};

//银行选择函数
const BankChange = (e) => {
  if (e.detail.value[0].value === "其他银行")
    applyDetailInfo.settAccountBankBranchName = "";
};

// 合并信息方法, 职能读取，和信息回显，通过此方法合并
let mccCode = ref();
let areaCode = ref("");
let BankName = ref(""); // 银行位置回显
const bankCode = ref();

// 信息合并
const assignObj = (obj) => {
  Object.assign(applyDetailInfo, obj); // obj是回显的信息
	
	// 受益人信息回显
	nextTick(() => {
		if (ownerCardRef.value) ownerCardRef.value.ownerInfoBack(obj.companyBeneficiaryList)
	})
	
  // 开启只读模式，直接return以下不在进行
  if (isDisable.value) {
    obj.areaText = tool.addressBack(obj.areaCode, address); // 商户地址
    obj.bankText = tool.addressBack(obj.bankCode, address); // 分行地址
    if (applyInfoRef.value) applyInfoRef.value.getApplyInof(obj); // 传值给只读组件
    return;
  }

  mccCode.value = obj.mccCode;
  obj.areaCode ? (areaCode.value = obj.areaCode[2]) : null;

  BankName.value = obj.settAccountBankName;
  obj.settAccountBankBranchAreaCode
    ? (bankCode.value = obj.settAccountBankBranchAreaCode[2])
    : null;

  // 结算规则数组 个人是individual 企业是enterprise
  obj.merchantType == 2
    ? (mccWxList.value = mccWx.individual)
    : (mccWxList.value = mccWx.enterprise);

  if (obj.settlementId) {
    setRulesText.value = mccWxList.value.find(
      (val) => val.settlementId == obj.settlementId
    ).settlementName; // 结算规则信息回显(通过settlementId匹配ID)
  }

  if (obj.settlementId) {
    secondList.value = mccWxList.value.find(
      (val) => val.settlementId == obj.settlementId
    ).qualification; // 信息合并之后，要给二级类目数组赋值
  }

  // 为一级类目，二级类目选中的值做回显
  for (let i = 0; i < mccWxList.value.length; i++) {
    if (mccWxList.value[i].settlementId == obj.settlementId) {
      setRulesIndex.value = i;
      break;
    }
  }

  for (let i = 0; i < secondList.value.length; i++) {
    if (secondList.value[i].qualificationType == obj.mccCode) {
      secondListIndex.value = i;
      break;
    }
  }

  // 是否参加活动回显
  applyDetailInfo.activitiesId
    ? (activityIndex.value = 0)
    : (activityIndex.value = 1);
};

// 发起进件
const launchApply = (isTempData) => {
  // 微信进件特有，当选择不参与优惠费率活动时，不显示费率板块，也不校验费率
  if (activityIndex.value == 0) {
    // 拿费率组件的值
    applyDetailInfo.paywayFeeList = defaultRateRef.value.getList(isTempData)

    // 判断类型，对象类型是费率正常提交   Sting 是错误信息
    if (typeof applyDetailInfo.paywayFeeList === "string")
      return uni.showToast({
        title: applyDetailInfo.paywayFeeList, icon: "none",
      });

    // 费率必填，空值校验
    if (applyDetailInfo.paywayFeeList.length == 0 && !isTempData)
      return uni.showToast({ title: "请至少设置一项费率值", icon: "none" });
  } else {
    applyDetailInfo.paywayFeeList = "";
  }

  // 获取受益人信息
  if (applyDetailInfo.merchantType == 3) {
    applyDetailInfo.companyBeneficiaryList = ownerCardRef.value.ownerInfo();
  }
	
  emit(
    "applyHandle",
    {
      name: "wxpay",
      isTempData,
      applyDetailInfo,
      formCheck: [
        applyDetailInfo.isNeedQualification,
        applyDetailInfo.merchantType,
        applyDetailInfo.contactType,
      ],
    },
    ((applyDetailInfo.merchantType == 3) && !applyDetailInfo.owner) // 该字段为true则对受益人信息进行校验
  );
};

defineExpose({ launchApply, assignObj });
</script>

<style scoped lang="scss">
@import "../static/information.scss";
.set-rules {
  width: 100%;
  background: #fff;
  padding: 30rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  image {
    width: 40rpx;
    height: 40rpx;
    margin-left: 10rpx;
  }
}
.firstradius {
  border-top-left-radius: 10rpx;
  border-top-right-radius: 10rpx;
}
</style>
