<template>
  <a-drawer
    v-model:visible="vdata.visible"
    :mask-closable="false"
    title="新建"
    :body-style="{ paddingBottom: '80px' }"
    width="70%"
    class="drawer-width"
    @close="vdata.visible = false"
  >

    <a-card style="margin-bottom: 20px">
      <div class="card-top">基本信息</div>
      <a-form layout="vertical" class="edit-box" :model="vdata.saveObject" :rules="step1Rules">
        <a-row justify="space-between" type="flex">
          <a-col :span="11">
            <a-form-item  has-feedback   label="支付通道" name="ifCode">
              <a-select ref="select" v-model:value="vdata.saveObject.ifCode" placeholder="请选择支付通道">
                <a-select-option
                    v-for="item in vdata.payDefines"
                    :key="item.ifCode"
                    :value="item.ifCode"
                    :disabled="item.ifCode != 'yspay' && item.ifCode != 'zftpay'"
                >{{ item.ifName }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
<!--          <a-col :span="11">-->
<!--            <a-form-item-->
<!--                has-feedback-->
<!--                label="支付渠道"-->
<!--                name="isvNo"-->
<!--            >-->
<!--              <a-input v-model:value="vdata.saveObject.isvNo" placeholder="请输入支付渠道"></a-input>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :span="11">
            <a-form-item  label="分账类型"  name="userType">
              <a-select  ref="select"   v-model:value="vdata.saveObject.userType"  @change="getAccountType"   placeholder="请选择需要变更的类型"  >
                <a-select-option :value="0">个人</a-select-option>
                <a-select-option :value="1">门店</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="11" v-if="vdata.saveObject.userType == 0">
            <a-form-item  label="结算类型"  name="userType">
              <a-select  ref="select"   v-model:value="vdata.saveObject.settleType"     placeholder="请选择结算类型"  >
                <a-select-option value="ZFB">支付宝</a-select-option>
                <a-select-option value="BANK">银行卡</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card>
      <div class="card-top">{{vdata.saveObject.userType ==1?'门店' : '个人' }}信息</div>
      <a-form
          ref="stepForm2Ref"
          :model="vdata.saveObject"
          layout="vertical"
          :rules="step2Rules"
          class="edit-box"
      >
        <a-row  v-if="vdata.saveObject.userType ==0"  justify="space-between" type="flex">
          <a-col :span="11">
            <a-form-item label="身份证人像面照片" name="idCardFrontUrl">
              <JeepayUpload
                  v-model:src="vdata.saveObject.info.idCardFrontUrl"
                  bizType="applyment"
                  :imgSize="2"
                  ocrType="idCard"
                  @ocrScan="ocrScanSettFunc"
              />
              <span class="jeepay-tip-text">(上传图片自动识别 身份证名称 身份证号)</span>
            </a-form-item>
          </a-col>

          <a-col :span="11">
            <a-form-item label="身份证国徽面照片" name="idCardBackUrl">
              <JeepayUpload
                  v-model:src="vdata.saveObject.info.idCardBackUrl"
                  bizType="applyment"
                  :imgSize="2"
                  ocrType="idCard"
                  @ocrScan="ocrScanSettFunc"
              />
              <span class="jeepay-tip-text">(上传图片自动识别 有效期)</span>
            </a-form-item>
          </a-col>

          <a-col :span="11">
            <a-form-item has-feedback label="身份证姓名" name="idCardName">
              <a-input v-model:value="vdata.saveObject.info.idCardName" placeholder="请输入身份证姓名" />
            </a-form-item>
          </a-col>

          <a-col :span="11">
            <a-form-item has-feedback label="身份证号码" name="idCardNo">
              <a-input
                  v-model:value="vdata.saveObject.info.idCardNo"
                  placeholder="请输入身份证号码"
              />
            </a-form-item>
          </a-col>

          <a-col :span="11">
            <a-form-item has-feedback label="身份证有效期开始时间" name="idCardStartDate">
              <a-input
                  v-model:value="vdata.saveObject.info.idCardStartDate"
                  placeholder="示例：2023-10-10"
              />
              <span class="jeepay-tip-text">(示例：2023-10-10)</span>
            </a-form-item>
          </a-col>

          <a-col :span="11">
            <a-form-item has-feedback label="身份证有效期截止时间" name="idCardEndDate">
              <div>
                <a-input
                    v-model:value.trim="vdata.saveObject.info.idCardEndDate"
                    :disabled="vdata.saveObject.info.isLongTerm == 1"
                    placeholder="示例：2023-10-10, 长期勾选长期"
                    style="width: 60%;margin-right: 10px;"
                />
                <a-checkbox
                    :checked="vdata.saveObject.info.isLongTerm == 1 "
                    @change="(e) => vdata.saveObject.info.isLongTerm  = e.target.checked ? 1 : 0 "
                >长期</a-checkbox>
              </div>
              <span class="jeepay-tip-text">(示例：2023-10-10, 长期勾选长期)</span>
            </a-form-item>
          </a-col>
          <div style="width: 100%;display: contents;" v-if="vdata.saveObject.settleType == 'ZFB'">
            <a-col :span="11" >
              <a-form-item has-feedback label="个人支付宝账号" name="bankCardNo">
                <a-input v-model:value="vdata.saveObject.info.bankCardNo" placeholder="个人支付宝账号" />
              </a-form-item>
            </a-col>
          </div>
          <div style="width: 100%;display: contents;" v-if="vdata.saveObject.settleType == 'BANK'">
            <a-col :span="11">
              <a-form-item has-feedback label="结算卡数字面" name="bankCardFrontUrl">
                <JeepayUpload
                    v-model:src="vdata.saveObject.info.bankCardFrontUrl"
                    bizType="applyment"
                    :imgSize="1"
                    ocrType="bankCard"
                    @ocrScan="ocrScanFunc"
                />
                <span class="jeepay-tip-text">(上传图片自动识别 银行卡号)</span>
              </a-form-item>
            </a-col>
            <a-col :span="11">
              <a-form-item has-feedback label="结算卡背面" name="bankCardBackUrl">
                <JeepayUpload
                    v-model:src="vdata.saveObject.info.bankCardBackUrl"
                    bizType="applyment"
                    :imgSize="1"
                    ocrType="bankCard"
                    @ocrScan="ocrScanFunc"
                />
                <span class="jeepay-tip-text">(上传图片自动识别 银行卡号)</span>
              </a-form-item>
            </a-col>

            <a-col :span="11" >
              <a-form-item has-feedback label="结算银行卡账户" name="bankCardNo">
                <a-input v-model:value="vdata.saveObject.info.bankCardNo" placeholder="结算卡银行卡账户" />
              </a-form-item>
            </a-col>
            <a-col :span="11" >
              <a-form-item has-feedback label="银行预留手机号" name="phone">
                <a-input v-model:value="vdata.saveObject.info.phone" placeholder="银行预留手机号" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="开户行省市县" name="bankAreaCode">
                <JeepayAreaSelectYs
                    v-model:value="vdata.saveObject.info.bankAreaCode"  @change="changeBankAreaFunc"/>
              </a-form-item>
            </a-col>

            <a-col :span="24">
              <a-form-item label="开户支行" name="bankBranchNo">
                <a-select
                    v-model:value="vdata.saveObject.info.bankBranchNo"
                    placeholder="选择支行"
                    show-search
                    label-in-value
                    :filter-option="false"
                    @search="handleBankSearch"
                    @change="handleBankChange">
                  <a-select-option v-for="(item, index) in vdata.filteredBankInfoList" :key="index" :value="item.branchNo">
                    {{ item.branchName }}
                  </a-select-option>
                </a-select>
                <span class="jeepay-tip-text">(填写银行卡号并且选择开户行省市县后将展开支行列表)</span>
              </a-form-item>
            </a-col>
          </div>
        </a-row>

        <a-row  v-if="vdata.saveObject.userType ==1"  justify="space-between" type="flex">

          <a-col :span="24"  >
            <a-form-item label="选择门店" name="divisionNo">
              <a-select v-model:value="vdata.saveObject.divisionNo" placeholder="请选择门店" show-search @search="handleStoreChange" :filter-option="false">
                <a-select-option v-for="d in vdata.filteredApplymentInfoList" :key="d.applyId" v-model:value="d.applyId">
                  {{ d.mchShortName }} - {{ d.applyId }} - {{ d.ifName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>

    </a-card>
    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" @click="onClose()">
        <close-outlined />取消
      </a-button>
      <a-button type="primary" :loading="vdata.confirmLoading" @click="onSubmit(11,1)">
        <check-outlined />保存
      </a-button>
    </div>
  </a-drawer>
</template>
    <script setup lang="ts">
 import {message, SelectProps} from "ant-design-vue";

import {
  req,
  $bankBranchList,
  API_MCH_PAY_DEFINES,
  API_URL_MCH_APPLYMENT_LIST, API_URL_MCH_STORE_LIST, API_URL_DIVISIONSUBJECT_RECEIVER_ADD,API_URL_DIVISIONSUBJECT_RECEIVER_SAVE
} from "@/api/manage";
import { useRouter } from "vue-router";
import { debounce } from "lodash-es";
import ruleGenerator from "@/utils/ruleGenerator";

import {
  ref,
  reactive,
  getCurrentInstance,
  onMounted
} from "vue";

const router = useRouter(); //这是全部路由
// 定义父组件的传值

const props = defineProps({
  TypeJudgment: { type: String, default: "" }, //分出接受类型判断
  configMode: { type: String, default: "" },
  callbackFunc: { type: Function, default: () => ({}) },
  value: { type: String, default: "" },
  customDateRangeType: { type: String, default: "dateTime" }, // date 和 dateTime
  allTimeIsShow: { type: Boolean, default: true }, // 首页饼图，不显示全部时间
  // 首页交易统计折线图独有的时间选择项
  statisticalTimeIsShow: { type: Boolean, default: false }
});
 const {
  $infoBox,
  $access
} = getCurrentInstance()!.appContext.config.globalProperties;
const payTestBarCode = ref();
const cashOutFormModel = ref();
const vdata: any = reactive({
  recordId: null, // 更新对象ID
  visible: false, // 是否显示弹层/抽屉
  btnLoading: false,
  filteredApplymentInfoList:[] as any,
  filteredStoreIdList:[] as any,
  saveObject: {userType:0,settleType:"ZFB", info:{} as any}, // 数据对象
  mch: {
    info:{} as any
  } as any,
  bankInfoList: [],
  filteredBankInfoList: [],
  standByBankInfoList: [],
  filteredStandByBankInfoList: [],
  business: [],
  settlementMethod: [] as any,
  rateD0: 0,
  rateD1: 0
});

const step1Rules = {
  ifCode: [{ required: true, message: "支付通道", trigger: "blur" }],
  // isvNo: [{ required: true, message: "支付渠道", trigger: "blur" }],
  userType: [{ required: true, message: "分账类型", trigger: "blur" }]
};
const step2Rules = {
  userType: [{ required: true, message: "结算账号类型", trigger: "blur" }],
  idCardName: [{ required: true, message: "姓名", trigger: "blur" }],
  idCardFrontUrl: [{ required: true, message: "身份证头像面不为空", trigger: "blur" }],
  idCardBackUrl: [{ required: true, message: "身份证国徽面不为空", trigger: "blur" }],
  idCardNo: [{ required: true, message: "身份证号不为空", trigger: "blur" }],
  idCardStartDate: [{ required: true, message: "身份证有效期开始日期不为空", trigger: "blur" }],
  idCardEndDate: [{ required: true, message: "身份证有效期结束日期不为空", trigger: "blur" }],
  bankCardNo: [{ required: true, message: "银行卡号不为空", trigger: "blur" }],
  bankCardFrontUrl: [{ required: true, message: "银行卡卡号面不为空", trigger: "blur" }],
  bankCardBackUrl: [{ required: true, message: "银行卡背面不为空", trigger: "blur" }],
  bankAreaCode: [{ required: true, message: "开户行省市县不为空", trigger: "blur" }],
  bankBranchNo: [{ required: true, message: "开户支行不为空", trigger: "blur" }],
  phone: [{ required: true, message: "银行卡预留手机号不为空", trigger: "blur" }],
};

const stepForm1Ref = ref();
const stepForm2Ref = ref();
const loading = ref<boolean>(false);



function getAccountType(key) {
  vdata.saveObject.userType = key;
}
function payFefines() {
  req.list(API_MCH_PAY_DEFINES, { pageSize: -1 }).then(res => {
    vdata.payDefines = res;
  });
}

function pageRender(type,record=null) {
  // 弹层打开事件
  vdata.visible = true;
  vdata.saveObject = { userType:0,settleType:"ZFB", info:{} as any} as any
  if (stepForm2Ref.value !== undefined) {
    stepForm2Ref.value.resetFields()
  }
  storeList(null)
  // applyList(null)
}

// 图片识别的回调函数
function ocrScanFunc(orcObject: any) {
  if (orcObject) {
    // vdata.saveObject.settAccountBankName = orcObject.settAccountBankName;
    vdata.saveObject.info.bankCardNo = orcObject.settAccountNo;
  }
}

// 结算人身份证  图片识别的回调函数
function ocrScanSettFunc(orcObject: any) {
  if (orcObject?.idcardName) {
    vdata.saveObject.info.idCardName = orcObject.idcardName;
    vdata.saveObject.info.idCardNo = orcObject.idcardNo;
  }
  if (orcObject?.idcardEffectBegin) {
    vdata.saveObject.info.idCardStartDate = orcObject.idcardEffectBegin;
    vdata.saveObject.info.idCardEndDate = orcObject.idcardEffectEnd;
  }
}
function onClose () {
  vdata.visible = false
}

function onSubmit(type, refNum) {
  stepForm2Ref.value.validate().then(valid=>{
    vdata.confirmLoading = true // 显示loading
    console.log(vdata.saveObject,'vdatasaveObject')
    console.log(vdata.saveObject,'mchmchmch')
    vdata.visible = false
    vdata.confirmLoading = false // 显示loading
    return false;
    if (vdata.isAdd) {
      req.add(API_URL_DIVISIONSUBJECT_RECEIVER_ADD, vdata.saveObject).then(res => {
        message.success('添加成功')
        vdata.visible = false
        vdata.confirmLoading = false // 显示loading
        props.callbackFunc() // 刷新列表
      }).catch(res => { vdata.confirmLoading = false })
    } else {
      req.updateById(API_URL_DIVISIONSUBJECT_RECEIVER_SAVE, vdata.recordId, vdata.saveObject).then(res => {
        message.success('修改成功')
        vdata.visible = false
        vdata.confirmLoading = false // 显示loading
        props.callbackFunc() // 刷新列表
      }).catch(res => { vdata.confirmLoading = false })
    }
  })
}


// 开户行所在省市区
const changeBankAreaFunc = debounce((value) => {
  console.log(value,'valuevaluevalue')
  console.log(vdata.saveObject.settAccountBankBranchAreaCode,'settAccountBankBranchAreaCode')
  // 区编码
  if (value) {
    vdata.saveObject.settAccountBankBranchAreaCode = []
    vdata.saveObject.settAccountBankBranchAreaCode = [value[0].value,value[1].value,value[2].value]
    vdata.saveObject.settAccountBankBranchAreaName = [value[0].label,value[1].label,value[2].label]

    // 区编码
    if (vdata.saveObject?.settAccountBankBranchAreaName) {
      vdata.bankInfoList = [];
      vdata.filteredBankInfoList = [];

      const param = {
        cityCode: vdata.saveObject.settAccountBankBranchAreaName[1]
      };

      // $bankBranchList(vdata.business.mchNo, 'zftpay', param,vdata.business.isvNo).then(
      $bankBranchList('U17085019455', 'zftpay', param,'V1698312342').then(
        res => {
          if (res?.length) {
            res.forEach(element => {
              // const item = element;
              vdata.bankInfoList.push(element);
              vdata.filteredBankInfoList.push(element);
            });
          } else {
            $infoBox.message.error("该地区下未找到对应银行列表");
          }
        }
      );
    } else {
      $infoBox.message.warn("请先选择地区");
    }
  }
}, 300);

const handleBankSearch = value => {
  console.log("handBankSearch", value);
  if(!isChinese(value)){
    return false;
  }
  addCity(value)
};

function isChinese(str) {
  var reg = /[\u4e00-\u9fa5]/; // Unicode范围内的汉字编码
  return reg.test(str);
}
function addCity(value) {
  vdata.bankInfoList = []
  vdata.filteredBankInfoList = []
  const param = {
    cityCode: vdata.saveObject.settAccountBankBranchAreaName[1],
    branchName: value,
  };
  console.log(param,'mchApplymentData')
  // $bankBranchList(vdata.business.mchNo, 'zftpay', param,vdata.business.isvNo).then(
  $bankBranchList('U17085019455', 'zftpay', param,'V1698312342').then(
      res => {
        if (res?.length) {
          res.forEach(element => {
            // const item = element;
            vdata.bankInfoList.push(element);
            vdata.filteredBankInfoList.push(element);
          });
        } else {
          $infoBox.message.error("该地区下未找到对应银行列表");
        }
      }
  );
}
const handleBankChange = option => {
  console.log("handleBankChange", option);
  vdata.saveObject.bankName = vdata.filteredBankInfoList[option.key].bankName
  vdata.saveObject.branchNo = vdata.filteredBankInfoList[option.key].branchNo
  vdata.saveObject.branchName = vdata.filteredBankInfoList[option.key].branchName
  vdata.saveObject.bankAbbr = vdata.filteredBankInfoList[option.key].bankAbbr
};



const handleStoreChange = (value) => {
  // vdata.filteredApplymentInfoList = [];
  //
  // applyList(value)
  vdata.filteredStoreInfoList = [];

  storeList(value)
};
function storeList(storeName){
  let data = {
    pageSize:1000,
    state : 99
  } as any
  if(storeName){
    data.storeName  = storeName
  }

  req.list(API_URL_MCH_STORE_LIST, data).then(res => {
    vdata.filteredStoreInfoList = res.records
  })
}

//
function applyList(mchApplyName){
   let data = {
     pageSize:1000,
     state : 99
   } as any
   if(mchApplyName){
     data.mchApplyName  = mchApplyName
   }

  req.list(API_URL_MCH_APPLYMENT_LIST, data).then(res => {
    vdata.filteredApplymentInfoList = res.records
  })
}
defineExpose({
  pageRender
});
onMounted(() => {
  payFefines();
});
</script>
    <style lang="less" scoped>
.card-top {
  width: 100%;
  font-weight: 600;
  border-bottom: 1px #e2e2e2 solid;
  margin: 20px 0 20px 0;
  padding: 0 0 10px 20px;
}

.bottom-btn {
  /deep/ div {
    display: flex;
    justify-content: center;
  }
}

.typePopover {
  position: absolute;
  top: -30px;
  left: 93px;
}

.image_box {
  width: 160px;
  height: 160px;
}

.img_div {
  display: flex;
}

.img_div .ant-form-item {
  display: block !important;
  margin: 20px;
}

.account-settings-info-view > .ant-form-item-label {
  overflow: inherit !important;
}

// .ant-form-item>.ant-form-item-label{
//   overflow: inherit !important;
// }
#form_item_name {
  // width: 800px;
  // width: 200%;
}

.ant-input-disabled {
  // width: 180%;
}

.ant-input-disabled {
  margin-left: 10px !important;
}

.select_div {
  width: 500px;
}

.ant-tabs-nav-wrap {
  display: none !important;
}

.ant-tabs-nav-list {
  display: none !important;
}

.ant-tabs > .ant-tabs-nav .ant-tabs-nav-wrap,
.ant-tabs > div > .ant-tabs-nav .ant-tabs-nav-wrap {
  display: none !important;
}

.jeepay-tip-text {
  font-size: 10px;
  color: rebeccapurple;
}

.option-left {
  width: 50%;
  word-wrap: break-word;
  white-space: normal;
  word-break: break-all;
}

.option-right {
  color: rgb(153, 153, 153);
}

.option-bottom {
  word-wrap: break-word;
  white-space: normal;
  word-break: break-all;
  color: rgb(153, 153, 153);
}

.jeepay-btn-box {
  margin: 15px -12px !important;
}

.jeepay-btn-box .ant-btn {
  margin: 0 10px;
}

.moban_box {
  color: #1965ff;
  margin: 10px 0;
}

.moban_box_span {
  padding: 5px 10px;
}

.div-type {
  border: 1px solid #ebeff2;
  margin-bottom: 33px;
}
</style>
 <style lang="less" scoped>
.jeepay-tip-text::before {
  border: none !important;
}
.edit-box{
  padding: 20px 30px;
  //margin-bottom: 20px;
}
</style>