<template>
  <!-- 只读文件 -->
  <readOnlyInfo
    v-if="isDisable"
    ref="applyInfoRef"
    applyName="shengpay"
  ></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>

          <JeePayForm text="选择行业MCC">
            <jeeDataPicker
              :code="codeBack.mccCode"
              :localdata="mcc"
              @change="publicSelect($event, 'mccCode')"
              paramType="last"
            />
          </JeePayForm>

          <JeePayForm
            text="商户联系人姓名"
            v-model:value="applyDetailInfo.contactName"
          />
          <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">
          <JeePayForm
            text="商户简称"
            v-model:value="applyDetailInfo.mchShortName"
          />

          <template v-if="applyDetailInfo.merchantType != 1">
            <!-- 营业执照信息 小微不填 企业/个体工商户必填 -->
            <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="营业执照起始有效期">
              <termOfValidity
                :defaultDate="applyDetailInfo.licenseEffectBegin"
                @publicSelect="publicSelect($event, 'licenseEffectBegin')"
                :isEnd="false"
              />
            </JeePayForm>

            <JeePayForm text="营业执照有效期截止">
              <termOfValidity
                :defaultDate="applyDetailInfo.licenseEffectEnd"
                @publicSelect="publicSelect($event, 'licenseEffectEnd')"
              />
            </JeePayForm>
          </template>

          <JeePayForm
            text="商户名称全称"
            v-model:value="applyDetailInfo.mchFullName"
          />
          <JeePayForm
            text="请输入商户详细地址"
            v-model:value="applyDetailInfo.address"
          />

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

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

          <JeePayForm text="收银台照片">
            <JeepayUpLoad
              :imgUrl="applyDetailInfo.storeCashierImg"
              @uploadSuccess="uploadSuccess($event, 'storeCashierImg')"
              @clear="clear('storeCashierImg')"
            />
          </JeePayForm>

          <JeePayForm text="店内环境照">
            <JeepayUpLoad
              :imgUrl="applyDetailInfo.storeInnerImg"
              @uploadSuccess="uploadSuccess($event, 'storeInnerImg')"
              @clear="clear('storeInnerImg')"
            />
          </JeePayForm>
        </view>
      </uni-collapse-item>
      <uni-collapse-item
        :show-animation="false"
        title="证件信息"
        class="coll-title"
      >
        <view class="content">
          <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
            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="法人手持身份证照片" :start="false">
            <JeepayUpLoad
              :imgUrl="applyDetailInfo.idcardInHandImg"
              @uploadSuccess="uploadSuccess($event, 'idcardInHandImg')"
              @clear="clear('idcardInHandImg')"
            />
          </JeePayForm>

        </view>
      </uni-collapse-item>
			<!-- 受益人卡片 -->
			<ownerCard
			  v-if="applyDetailInfo.merchantType == '3'"
			  ref="ownerCardRef"
			  @setLegalInfo="setLegalInfo"
			  :legalBtn="true"
				:isShengft="true"
			/>
      <uni-collapse-item
        :show-animation="false"
        title="联系人证件信息(联系人法人不一致时必填)"
        class="coll-title"
      >
        <view class="content">
          <JeePayForm text="商户联系人身份证人像面照片" :start="nameResult">
            <JeepayUpLoad
              ocrFlag="idCard"
              :imgUrl="applyDetailInfo.contactIdcard1Img"
              @uploadSuccess="uploadSuccess($event, 'contactIdcard1Img')"
              @clear="clear('contactIdcard1Img')"
            />
          </JeePayForm>

          <JeePayForm text="商户联系人身份证国徽面照片" :start="nameResult">
            <JeepayUpLoad
              ocrFlag="idCard"
              :imgUrl="applyDetailInfo.contactIdcard2Img"
              @uploadSuccess="uploadSuccess($event, 'contactIdcard2Img')"
              @clear="clear('contactIdcard2Img')"
            />
          </JeePayForm>

          <JeePayForm
            text="商户联系人身份证号"
            v-model:value="applyDetailInfo.contactIdcardNo"
            :start="nameResult"
          />

          <JeePayForm text="商户联系人身份证起始有效期" :start="nameResult">
            <termOfValidity
              :defaultDate="applyDetailInfo.contactIdcardEffectBegin"
              @publicSelect="publicSelect($event, 'contactIdcardEffectBegin')"
              :isEnd="false"
            />
          </JeePayForm>

          <JeePayForm text="商户联系人身份证结束有效期" :start="nameResult">
            <termOfValidity
              :defaultDate="applyDetailInfo.contactIdcardEffectEnd"
              @publicSelect="publicSelect($event, 'contactIdcardEffectEnd')"
            />
          </JeePayForm>

          <JeePayForm
            text="商户联系人身份证居住地址"
            v-model:value="applyDetailInfo.contactIdcardAddress"
            :start="nameResult"
          />

          <JeePayForm text="业务办理授权函图片" :start="nameResult">
            <JeepayUpLoad
              ocrFlag="idCard"
              :imgUrl="applyDetailInfo.contactWxAuthImg"
              @uploadSuccess="uploadSuccess($event, 'contactWxAuthImg')"
              @clear="clear('contactWxAuthImg')"
            />
          </JeePayForm>
        </view>
      </uni-collapse-item>
      <uni-collapse-item
        :show-animation="false"
        title="账号信息"
        class="coll-title"
      >
        <view class="content">
          <JeePayForm text="结算账号类型">
            <uni-data-checkbox
              v-model="applyDetailInfo.settAccountType"
              :localdata="settlementTypeList"
            ></uni-data-checkbox>
          </JeePayForm>

          <JeePayForm
            :text="
              applyDetailInfo.settAccountType == 'B'
                ? '开户许可证照片'
                : '结算银行卡照片'
            "
          >
            <JeepayUpLoad
              ocrFlag="bankCard"
              :imgUrl="applyDetailInfo.settAccountLicenseImg"
              @uploadSuccess="uploadSuccess($event, 'settAccountLicenseImg')"
              @clear="clear('settAccountLicenseImg')"
            />
          </JeePayForm>

          <JeePayForm
            :text="
              applyDetailInfo.settAccountType == 'B'
                ? '对公账户名称'
                : '持卡人姓名'
            "
            v-model:value="applyDetailInfo.settAccountName"
          />

          <JeePayForm
            :text="
              applyDetailInfo.settAccountType == 'B' ? '对公账号' : '银行卡号'
            "
            v-model:value="applyDetailInfo.settAccountNo"
          />

          <!-- 以下几个 开户银行名称、支行所在地、支行名称、对公结算必填 -->
          <template v-if="applyDetailInfo.settAccountType == 'B'">
            <JeePayForm
              text="开户银行名称"
              v-model:value="applyDetailInfo.settAccountBankName"
            />

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

            <JeePayForm
              text="开户银行卡支行名称"
              v-model:value="applyDetailInfo.settAccountBankBranchName"
            />
          </template>

          <!-- 企业类型 && 结算到个人 -->
          <template
            v-if="
              applyDetailInfo.settAccountType == 'C' &&
              applyDetailInfo.merchantType == 3
            "
          >
            <JeePayForm
              text="对公账户名称"
              v-model:value="applyDetailInfo.companyAccountName"
            />
            <JeePayForm
              text="对公账户银行卡号"
              v-model:value="applyDetailInfo.companyAccountNo"
            />
            <JeePayForm
              text="对公账户开户银行名称"
              v-model:value="applyDetailInfo.companyAccountBankName"
            />

            <JeePayForm text="对公账户开户支行所在地区">
              <jeeDataPicker
                :code="codeBack.branchCode"
                :localdata="address"
                @change="
                  publicSelect($event, 'companyAccountBankBranchAreaCode')
                "
                paramType="arr"
              />
            </JeePayForm>

            <JeePayForm
              text="对公账户开户支行名称"
              v-model:value="applyDetailInfo.companyAccountBankBranchName"
            />

            <JeePayForm text="开户许可证照片">
              <JeepayUpLoad
                :imgUrl="applyDetailInfo.companyAccountLicenseImg"
                @uploadSuccess="
                  uploadSuccess($event, 'companyAccountLicenseImg')
                "
                @clear="clear('companyAccountLicenseImg')"
              />
            </JeePayForm>
          </template>

          <!-- 企业性质 && 对私结算 && 结算到非法人银行卡时 需要传以下信息 -->
          <template
            v-if="
              (applyDetailInfo.merchantType == 2 ||
                applyDetailInfo.merchantType == 3) &&
              applyDetailInfo.settAccountType == 'C' &&
              applyDetailInfo.settAccountName != applyDetailInfo.idcardName
            "
          >
            <JeePayForm
              text="持卡人身份证号"
              v-model:value="applyDetailInfo.settAccountIdcardNo"
            />
            <JeePayForm text="持卡人身份证人像照">
              <JeepayUpLoad
                ocrFlag="idCard"
                :imgUrl="applyDetailInfo.settAccountIdcard1Img"
                @uploadSuccess="uploadSuccess($event, 'settAccountIdcard1Img')"
                @clear="clear('settAccountIdcard1Img')"
              />
            </JeePayForm>

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

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

            <JeePayForm text="持卡人身份证结束有效期">
              <termOfValidity
                :defaultDate="applyDetailInfo.settAccountIdcardEffectEnd"
                @publicSelect="
                  publicSelect($event, 'settAccountIdcardEffectEnd')
                "
              />
            </JeePayForm>
          </template>
        </view>
      </uni-collapse-item>

      <!-- 盛付通费率组件 -->
      <defaultRate ref="defaultRateRef"  @autoPos="autoPosHandle" />
			
			<!-- pos产品开通组件 -->
			<autoPos ref="autoPosRef" v-if="vdata.isAutoPos" />
			
    </uni-collapse>
  </view>
	
	<!-- 自主签约组件 -->
	<signing v-if="channelInfo.state == 2" />
	
</template>

<script setup>
import { ref, reactive, toRaw, computed, inject, nextTick } from "vue";
import address from "@/components/applyJson/address.json"; // 地址
import mcc from "@/components/applyJson/mcc.json"; // 行业
import JeepayUpLoad from "@/components/JeepayUpLoad/JeepayUpLoad.vue"; // 图片上传
import defaultRate from "../../components/defaultRate.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"; // 字典
import signing from '../../components/signing.vue' // 自主签约组件
import autoPos from './pos.vue' // pos产品开通

const merchantTypeList = reactive(filterDcit(["A0", "A1", "A2"])); // 商家类型
const settlementTypeList = reactive(filterDcit(["B3", "B4"])); // 结算类型

const channelInfo = inject('channelInfo')

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

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

const vdata = reactive({
	isAutoPos: true, // 是否展示pos产品开通组件
	wayCodeList: [], // 渠道名称列表
})

// 判断渠道名称中，是否包含 auto-pos
const posHandle = list => {
	list.forEach(item => vdata.wayCodeList.push(item))
	return vdata.wayCodeList.includes('AUTO_POS')
}

// 费率组件内部 开启或关闭auto-pos的回调
const autoPosHandle = flag => {
	vdata.isAutoPos = flag
	if (!flag) applyDetailInfo.posListStr = [] // pos信息重置
}

let autoPosRef = ref(null) // pos产品开通组件

let ownerCardRef = ref(null); // 受益人卡片
let defaultRateRef = ref(null); // 费率组件

// 将法人信息传递给受益人
const setLegalInfo = (index) => {
  ownerCardRef.value.getLegalInfo(
    {
      idcard1Img: applyDetailInfo.idcard1Img ? applyDetailInfo.idcard1Img : "",
      idcard2Img: applyDetailInfo.idcard2Img ? applyDetailInfo.idcard2Img : "",
      idcardNo: applyDetailInfo.idcardNo ? applyDetailInfo.idcardNo : "",
      idcardName: applyDetailInfo.idcardName ? applyDetailInfo.idcardName : "",
      idcardAddress: applyDetailInfo.idcardAddress
        ? applyDetailInfo.idcardAddress
        : "",
      idcardEffectEnd: applyDetailInfo.idcardEffectEnd
        ? applyDetailInfo.idcardEffectEnd
        : "",
      idcardEffectBegin: applyDetailInfo.idcardEffectBegin
        ? applyDetailInfo.idcardEffectBegin
        : "",
    },
    index
  );
};

// 法人与商户联系人不一致时，联系人证件信息必填（判断二者姓名）(加上*号)
let nameResult = computed(() => {
  return !(applyDetailInfo.contactName === applyDetailInfo.idcardName);
});

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

// 通用选择函数
const publicSelect = (e, key) => {
  applyDetailInfo[key] = e.detail.value;
};

// 上传图片成功
const uploadSuccess = (res, name) => {
  applyDetailInfo[name] = res.data;
  if (res.ocrInfo && Object.keys(res.ocrInfo).length < 1) return false;
  // OCR图片识别  idCard-身份证 idcard1Img，idcard2Img  license-营业执照 licenseImg
  // ocr识别返回的字段与当前字段不一致时，走以下判断
  if (name == "settAccountIdcard2Img") {
    applyDetailInfo.settAccountIdcardEffectBegin =
      res.ocrInfo.idcardEffectBegin; // 持卡人有效期
    applyDetailInfo.settAccountIdcardEffectEnd = res.ocrInfo.idcardEffectEnd; // 持卡人有效期end
    return;
  }
  if (name == "contactIdcard1Img") {
    // 商户联系人身份证人像面照片回显
    applyDetailInfo.contactIdcardNo = res.ocrInfo.idcardNo;
    applyDetailInfo.contactIdcardAddress = res.ocrInfo.idcardAddress;
    return;
  }
  if (name == "contactIdcard2Img") {
    // 商户联系人身份证国徽面照片回显
    applyDetailInfo.contactIdcardEffectBegin = res.ocrInfo.idcardEffectBegin;
    applyDetailInfo.contactIdcardEffectEnd = res.ocrInfo.idcardEffectEnd;
    return;
  }
  Object.assign(applyDetailInfo, res.ocrInfo); // ocr信息回显，字段一致直接合并
};
// 清除图片  仅前端
const clear = (name, url) => (applyDetailInfo[name] = "");

// 发起进件  注意后面的formCheck参数，表单校验要用
const launchApply = (isTempData) => {
	
  // 有费率的进件渠道，要在发起进件之前，获取所选择的费率信息
	applyDetailInfo.paywayFeeList = defaultRateRef.value.getList(isTempData)
	if (applyDetailInfo.paywayFeeList.length <= 0 && !isTempData) {
		return uni.showToast({
			title: '请至少包含一个签约产品， 若无产品请先配置服务商相关底价信息。', icon: 'none'
		})
	}

	// pos信息
	if (vdata.isAutoPos) {
		applyDetailInfo.posListStr = autoPosRef.value.getPosInfo(isTempData)
		
		// pos组件内校验失败ruturn false了，所以这里也不能进行下一步了
		if (!applyDetailInfo.posListStr) return
	}
	
  // 获取受益人信息
  if (applyDetailInfo.merchantType == 3) {
    applyDetailInfo.companyBeneficiaryList = ownerCardRef.value.ownerInfo();
  }

  emit(
    "applyHandle",
    {
      name: "shengpay",
      isTempData,
      applyDetailInfo,
      formCheck: [
        applyDetailInfo.merchantType,
        applyDetailInfo.settAccountType,
        applyDetailInfo.settAccountName,
        applyDetailInfo.idcardName,
        toRaw(nameResult.value),
      ],
    },
    applyDetailInfo.merchantType == 3 // 该字段为true则对受益人信息进行校验
  );
};

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

// 行业类型，地理位置回显
let codeBack = reactive({
  areaCode: "", // 商户地理位置回显
  bankCode: "", // 银行地址回显
  mccCode: "", // 行业回显
  branchCode: "", //  企业类型 && 结算到个人 银行支行地址回显
});

// 合并信息方法, 职能读取，和信息回显，通过此方法合并
const assignObj = (obj) => {
  Object.assign(applyDetailInfo, obj);
	posHandle(obj.paywayFeeList) // 费率信息中存在 AUTO_POS， 则打开pos组件
	// 受益人信息回显
	nextTick(() => {
		// 受益人组件信息回显 
		if (ownerCardRef.value) ownerCardRef.value.ownerInfoBack(obj.companyBeneficiaryList)
		
		// pos信息组件信息回显
		if (autoPosRef.value) autoPosRef.value.merge(JSON.parse(obj.posListStr))
	})
	
  if (!isDisable.value) {
		ownerCardRef.value.ownerInfoBack(obj.companyBeneficiaryList); // 受益人信息回显
    // 行业类型，地理位置回显
    codeBack.areaCode = obj.areaCode ? obj.areaCode[2] : obj.areaCode;
    codeBack.bankCode = obj.settAccountBankBranchAreaCode
      ? obj.settAccountBankBranchAreaCode[2]
      : null;
    codeBack.mccCode = obj.mccCode;
    codeBack.branchCode = obj.companyAccountBankBranchAreaCode
      ? obj.companyAccountBankBranchAreaCode[2]
      : null;
  }

  // 以下用于只读信息页
  let mccInfo; // 行业文字回显
  for (var i = 0; i < mcc.length; i++) {
    mccInfo = mcc[i].children.find((val) => val.value == obj.mccCode);
    if (mccInfo) break;
  }
  obj.mccText = mccInfo ? mccInfo.text : ""; // 行业码转文字
  obj.areaText = tool.addressBack(obj.areaCode, address); // 地址码转文字
  obj.settAccountBankBranchAreaText = tool.addressBack(
    obj.settAccountBankBranchAreaCode,
    address
  );
  obj.settAccountText = obj.settAccountType == "C" ? "对私" : "对公";
  obj.merchantText =
    obj.merchantType == 1
      ? "小微企业"
      : obj.merchantType == 2
      ? "个体工商户"
      : "企业";
	// pos信息
	let posInfoList = JSON.parse(obj.posListStr)
	if (posInfoList && posInfoList.length > 0) {
		posInfoList.forEach(item => {
			item.areaText = tool.addressBack(item.terminalCityId, address)
		})
	}
	obj.posInfoList = posInfoList		
			
  // 传值给只读组件
  if (applyInfoRef.value) applyInfoRef.value.getApplyInof(obj);
};

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

<style scoped lang="scss">
@import "../../static/information.scss";
</style>
