<template>
  <!-- 只读文件 -->
  <readOnlyInfo
    v-if="isDisable"
    ref="applyInfoRef"
    applyName="sftpay"
  ></readOnlyInfo>
  <!-- 以盛付通进件模板 收付通基于它改的-->
  <view v-if="!isDisable">
    <uni-collapse ref="collapse">
      <uni-collapse-item
        :show-animation="false"
        title="主体信息"
        class="coll-title"
        :open="true"
      >
        <view class="content">
          <JeePayForm text="商户类型">
            <uni-data-checkbox
              v-model="applyDetailInfo.merchantType"
              :localdata="merchantTypeList"
              @change="mchTypeInfo"
            ></uni-data-checkbox>
          </JeePayForm>

          <template
            v-if="
              applyDetailInfo.merchantType == 2 ||
              applyDetailInfo.merchantType == 3
            "
          >
            <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"
            />
          </template>

          <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
        :show-animation="false"
        title="店铺信息"
        class="coll-title"
      >
        <view class="content">
          <JeePayForm
            text="商户简称"
            v-model:value="applyDetailInfo.mchShortName"
          />
          <JeePayForm
            text="店铺名称"
            v-model:value="applyDetailInfo.storeName"
          />
          <JeePayForm
            text="店铺链接"
            v-model:value="applyDetailInfo.storeUrl"
            tipText="链接或二维码二选一必填"
          />

          <JeePayForm text="店铺二维码">
            <JeepayUpLoad
              ocrFlag="idCard"
              :imgUrl="applyDetailInfo.storeQrCode"
              @uploadSuccess="uploadSuccess($event, 'storeQrCode')"
              @clear="clear('storeQrCode')"
            />
          </JeePayForm>

          <JeePayForm
            text="小程序AppID"
            v-model:value="applyDetailInfo.miniProgramSubAppid"
            :start="false"
          />
        </view>
      </uni-collapse-item>
      <uni-collapse-item title="结算规则" class="coll-title">
        <view class="content">
          <JeePayForm text="结算规则信息" :start="false">
            <view @click="setRulesRef.open('bottom')">{{
              setRulesText ? setRulesText : "请选择"
            }}</view>
          </JeePayForm>

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

          <JeePayForm
            text="特殊资质照"
            :start="false"
            v-if="applyDetailInfo.isNeedQualification"
          >
            <JeepayUpLoad
              :imgUrl="applyDetailInfo.qualifications"
              @uploadSuccess="uploadSuccess($event, 'qualifications')"
              @clear="clear('qualifications')"
            />
          </JeePayForm>
          <!-- 撑开高度的元素 -->
          <!-- <view style="height: 200px"></view> -->
        </view>
      </uni-collapse-item>
      <uni-collapse-item title="超级管理员" class="coll-title">
        <view class="content">
          <JeePayForm text="超管身份">
            <radio-group
              class="radio-group"
              @change="publicSelect($event, 'contactType')"
            >
              <label class="radio"
                ><radio
                  value="65"
                  :checked="applyDetailInfo.contactType == '65'"
                />经营者/法人</label
              >
              <label
                class="radio"
                v-if="
                  applyDetailInfo.merchantType == 2 ||
                  applyDetailInfo.merchantType == 3
                "
                ><radio
                  value="66"
                  :checked="applyDetailInfo.contactType == '66'"
                />经办人</label
              >
            </radio-group>
          </JeePayForm>

          <template v-if="applyDetailInfo.contactType == '66'">
            <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>

      <uni-collapse-item
        :show-animation="false"
        title="结算账户"
        class="coll-title"
      >
        <view class="content">
          <view class="item">
            <view class="title"><text class="require">*</text>账户类型</view>
            <radio-group
              class="radio-group"
              @change="publicSelect($event, 'settAccountType')"
            >
              <label
                class="radio"
                v-if="
                  applyDetailInfo.merchantType == 1 ||
                  applyDetailInfo.merchantType == 6 ||
                  applyDetailInfo.merchantType == 2
                "
                ><radio
                  value="C"
                  :checked="applyDetailInfo.settAccountType == 'C'"
                />对私</label
              >
              <label
                class="radio"
                v-if="
                  applyDetailInfo.merchantType == 2 ||
                  applyDetailInfo.merchantType == 3
                "
                ><radio
                  value="B"
                  :checked="applyDetailInfo.settAccountType == 'B'"
                />对公</label
              >
            </radio-group>
          </view>
          <JeePayForm
            text="开户名称"
            v-model:value="applyDetailInfo.settAccountName"
          />
          <JeePayForm
            text="银行账号"
            v-model:value="applyDetailInfo.settAccountNo"
          />

          <JeePayForm text="开户行">
            <view @click="openBankSelect">{{
              applyDetailInfo.accountBankNameShow
                ? applyDetailInfo.accountBankNameShow
                : "请选择"
            }}</view>
          </JeePayForm>

          <JeePayForm text="开户行省市区">
            <jeeDataPicker
              :code="codeBack.bankCode"
              :localdata="address"
              @change="publicSelect($event, 'settAccountBankBranchAreaCode')"
              paramType="arr"
            />
          </JeePayForm>

          <template v-if="applyDetailInfo.needBankBranch">
            <JeePayForm text="支行所在地区">
              <jeeDataPicker
                :code="codeBack.branchCode"
                :localdata="sftAddress"
                @change="publicSelect($event, 'bankBranchAreaCode')"
                paramType="arr"
              />
            </JeePayForm>

            <JeePayForm text="支行名称">
              <view @click="selectBranchBank">{{
                applyDetailInfo.settAccountBankBranchName
                  ? applyDetailInfo.settAccountBankBranchName
                  : "请选择"
              }}</view>
            </JeePayForm>
          </template>
        </view>
			
      </uni-collapse-item>
    </uni-collapse>

    <!-- 选择开户行组件 -->
    <sftSelectBank
      ref="sftSelectBankRef"
      :settAccountType="applyDetailInfo.settAccountType"
      @bankInfo="bankInfo"
      :ifCode="channelInfo.code"
    />

    <!-- 选择支行 -->
    <sftSelectBankBranch
      ref="sftSelectBankBranckRef"
      @bankBranckInfo="bankBranckInfo"
      :bankList="bankBranchList"
    />
  </view>

  <!-- 一级类目弹窗 -->
  <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 sftMccList"
        :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
      style="width: 100%; height: 50vh; overflow: auto; background: #fff"
      class="firstradius"
			:scroll-y="true" 
    >
      <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>
</template>

<script setup>
import { ref, reactive, toRaw, inject, nextTick } from "vue";
import address from "@/components/applyJson/address.json"; // 地址
import JeepayUpLoad from "@/components/JeepayUpLoad/JeepayUpLoad.vue"; // 图片上传
import { $bankBranchList } from "@/http/apiManager.js";
import readOnlyInfo from "../components/readOnlyInfo.vue"; // 只读文件
import tool from "@/util/tool.js"; // 工具类函数
import sftAddress from "@/components/applyJson/sftAddress.json"; // 选择支行地址用的json只到市
import JeePayForm from "@/components/applyComponents/JeePayForm.vue"; // 通用左右结构布局
import sftMcc from "@/components/applyJson/sftMcc.json"; // 行业
import termOfValidity from "@/components/applyComponents/termOfValidity.vue"; // 选择证件有效期
import jeeDataPicker from "@/components/applyComponents/dataPicker.vue"; // 通用级联选择
import ownerCard from "../components/ownerCard.vue"; // 受益人卡片组件
import sftSelectBank from "@/components/sftSelectBank/sftSelectBank.vue"; // 选择开户行
import sftSelectBankBranch from "@/components/sftSelectBank/sftSelectBankBranch.vue"; // 选择支行
import { filterDcit } from "@/hooks/dict"; // 字典
const merchantTypeList = reactive(filterDcit(["A3", "A4", "A1", "A2"])); // 商户类型
const channelInfo = inject('channelInfo')

const emit = defineEmits(["applyHandle"]);

// 商户进件详细信息（JSON类型字符串）
let applyDetailInfo = reactive({
  merchantType: "", // 商户类型 3 代表企业
  settAccountType: "", // 结算账号类型 B 对公
  companyBeneficiaryList: [],
	owner: false
});

// 状态: 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;

const ownerCardRef = ref(null);

/*
 * 选择开户银行板块
 */
const sftSelectBankRef = ref();
const sftSelectBankBranckRef = ref();
// 调起选择开户行弹窗
const openBankSelect = () => {
  if (!applyDetailInfo.settAccountType)
    return uni.showToast({
      title: "请先选择账户类型",
      icon: "none",
    });
  sftSelectBankRef.value.openHandle(applyDetailInfo.settAccountType);
};
// 接收选择的银行
const bankInfo = (val) => {
	console.log(val.bank_alias)
  applyDetailInfo.accountBankNameShow = val.bank_alias;
  applyDetailInfo.settAccountBankName = val.account_bank;
  applyDetailInfo.needBankBranch = val.need_bank_branch; // 是否需要填写分支
  applyDetailInfo.bankAliasCode = val.bank_alias_code; // 银行别名编码，请求银行分支时使用
};

let bankBranchList = ref([]); // 支行列表

// 选择支行
const selectBranchBank = () => {
  // 空值校验
  if (bankBranchList.value.length == 0)
    return uni.showToast({ title: "请先选择支行地址", icon: "none" });
  sftSelectBankBranckRef.value.open();
};

// 选择支行完毕
const bankBranckInfo = (val) =>
  (applyDetailInfo.settAccountBankBranchName = val.bank_branch_name); // 支行名称

// 上传图片成功
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] = "");

// 通用radio checkbox选择事件 回调函数
const publicSelect = (e, key) => {
  applyDetailInfo[key] = e.detail.value;
  // 如果超管身份选定为经营者法人 则固定超管姓名与身份证号为法人身份证号、姓名
  if (key == "merchantType") {
    applyDetailInfo.merchantType = Number(e.detail.value);
    if (e.detail.value == 1) {
      applyDetailInfo.settAccountType = "C"; // 微小商户，结算类型限制为 对私
      sftMccList.value = sftMcc.micro; // 切换mcc
    } else if (e.detail.value == 2) {
      sftMccList.value = sftMcc.individual;
    } else if (e.detail.value == 3) {
      sftMccList.value = sftMcc.enterprise;
    }
		setRulesText.value = '' // 重置一级类目文字
		applyDetailInfo.settlementId = '' // 重置一级类目ID 
    applyDetailInfo.mccCode = ""; // 重置二级类目
    applyDetailInfo.qualificationId = ""; // 重置二级类目
    applyDetailInfo.isNeedQualification = ""; // 是否要上传证书的标识
  } else if (key == "bankBranchAreaCode") {
    // 备注： 盛付通支行地址表，也出现了value相同的情况，需要改一下数据类型 ！！！
    // 请求支行数据
    $bankBranchList(channelInfo.mchNo, channelInfo.code, {
      cityCode: e.detail.value[1],
      bankAliasCode: applyDetailInfo.bankAliasCode,
    }).then((res) => {
      bankBranchList.value = res.bizData;
      applyDetailInfo.settAccountBankBranchName = ""; // 请求完毕赋空
    })
  }
};

/*
 * 结算规则板块
 */
let sftMccList = ref(sftMcc.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 = sftMccList.value[index].settlementId; // 给后台的一级类目
  setRulesIndex.value = index; // 选择完一级类目的下标
  setRulesText.value = sftMccList.value[index].settlementName; // 选择完一级类目的文字
  applyDetailInfo.mccCode = ""; // 重置二级类目
  applyDetailInfo.qualificationId = ""; // 重置二级类目
  applyDetailInfo.isNeedQualification = ""; // 是否要上传证书的标识
  secondList.value = sftMccList.value[index].qualification; // 二级类目列表
};

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");
};

// 发起进件
const launchApply = (isTempData) => {

  if (
    !applyDetailInfo.storeUrl &&
    !applyDetailInfo.storeQrCode &&
    !isTempData
  ) {
    return uni.showToast({
      title: "商户链接，商户二维码二选一必填",
      icon: "none",
    });
  }

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

// 只读组件信息
let applyInfoRef = ref(null);

// 行业类型，地理位置回显
let codeBack = reactive({
  bankCode: "", // 银行地址回显
  branchCode: "", //  银行支行地址回显
});

// 合并信息方法, 职能读取，和信息回显，通过此方法合并
const assignObj = (obj) => {
  Object.assign(applyDetailInfo, obj);
	
	// 受益人信息回显
	nextTick(() => {
		if (ownerCardRef.value) ownerCardRef.value.ownerInfoBack(obj.companyBeneficiaryList)
	})
	
  // 行业类型，地理位置回显
  codeBack.bankCode = obj.settAccountBankBranchAreaCode
    ? obj.settAccountBankBranchAreaCode[2]
    : null;
  codeBack.branchCode = obj.bankBranchAreaCode
    ? obj.bankBranchAreaCode[1]
    : null;
		
	// 根据商户类型 切换行业类型
	if (obj.merchantType == 1) {
		sftMccList.value = sftMcc.micro
	} else if (obj.merchantType == 2) {
		sftMccList.value = sftMcc.individual
	} else if (obj.merchantType == 3) {
		sftMccList.value = sftMcc.enterprise
	}
	
	if (obj.settlementId) {
		setRulesText.value = sftMccList.value.find(val => val.settlementId == obj.settlementId).settlementName // 结算规则信息回显(通过settlementId匹配ID)
		secondList.value = sftMccList.value.find(val => val.settlementId == obj.settlementId).qualification // 信息合并之后，要给二级类目数组赋值
	}
	
	// 为一级类目，二级类目选中的值做回显
	for (let i = 0; i < sftMccList.value.length; i++) {
		if (sftMccList.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
		}
	}	
		
  // 以下用于只读信息页
  obj.settAccountBankBranchAreaText = tool.addressBack(
    obj.settAccountBankBranchAreaCode,
    address
  );
  obj.bankBranchAreaCodeText = tool.addressBack(
    obj.bankBranchAreaCode,
    address,
    sftAddress
  );
  obj.settAccountText = obj.settAccountType == "C" ? "对私" : "对公";
  if (obj.merchantType == 1) {
    obj.merchantText = "小微商户";
  } else if (obj.merchantType == 2) {
    obj.merchantText = "个体工商户";
  } else if (obj.merchantType == 3) {
    obj.merchantText = "企业";
  } else {
    obj.merchantText = "个人卖家";
  }

  // 传值给只读组件
  if (applyInfoRef.value) applyInfoRef.value.getApplyInof(obj);
};

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>
