<template>
  <a-modal
    v-model:visible="vdata.isShow"
    :title="'发起结算'"
    placement="right"
    :closable="true"
    width="80%"
    style="margin-top: -70px"
    :mask-closable="false"
    @ok="handleOkFunc"
    @close="onClose"
    class="modal-div-box"
  >
    <!-- <a-modal :confirmLoading="confirmLoading"> -->

    <a-form
      ref="infoFormModel"
      :model="vdata.saveObject"
      layout="vertical"
      :rules="rules"
      style="padding-bottom:50px"
    >
      <a-row justify="space-between" type="flex">
<!--        <a-col :span="10">-->
<!--          <a-form-item label="任务:" name="taskId">-->
<!--            <a-select  v-model:value="vdata.saveObject.taskId" placeholder="请选择任务" show-search :filter-option="false">-->
<!--              <a-select-option v-for="(item, index) in vdata.filteredTaskInfoList" :key="index" :value="item.id">-->
<!--                {{ item.taskName }} - [{{item.id}}]-->
<!--              </a-select-option>-->
<!--            </a-select>-->
<!--          </a-form-item>-->
<!--        </a-col>-->

        <a-col :span="10">
          <a-form-item label="资金账户：" name="transferSubjectIdFq">
            <a-select  v-model:value="vdata.saveObject.transferSubjectIdFq" placeholder="请选择资金账户" @change="getTransferSubject" show-search :filter-option="false">
              <a-select-option v-for="(item, index) in vdata.filteredBookInfoList" :key="index" :value="item.id">
                {{ item.accountName }} - {{item.transChannelMchNo}} - {{(item.accountBookBalance / 100).toFixed(2)}}
              </a-select-option>
            </a-select>
<!--            <span class="jeepay-tip-text" v-if="vdata.saveObject.balance"> {{vdata.saveObject.balance}}</span>-->
          </a-form-item>
        </a-col>
<!--        <a-col :span="10">-->
<!--          <a-form-item label="结算类型：" name="entryType">-->
<!--            <a-select v-model:value="vdata.saveObject['entryType']" 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-col :span="24">
          <a-form-item label="结算方式：" name="type">
            <a-radio-group v-model:value="vdata.saveObject['type']">
              <a-radio :value="1">单笔</a-radio>
              <a-radio :value="2">批量</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>


        <a-col :span="24" v-if="vdata.saveObject['type'] == 2">
          <a-form-item label="" name="excelFileName">
            <JeepayUpload v-model:src="vdata.saveObject.excelFileName" @ocrScan="ocrScanFunc" fileType="file" bizType="agentFile" />
            <span class="jeepay-tip-text">文件格式：xlsx <a href="javascript:void(0)" class="jeepay-tip-bos-img" @click="download">《下载批量结算模版》</a></span>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <a-button  v-if="vdata.saveObject['type'] == 1" type="primary"    class="mg-b-30"  @click="showSettleUserListFuncModel"> <plus-outlined /> 添加人员 </a-button>

    <a-form v-if="vdata.saveObject['type'] == 1"
          ref="infoFormModel"
          :model="vdata.receiveList"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 15 }">
        <a-table bordered :data-source="vdata.receiveList" :columns="tableColumns"
                 :pagination="false" style="margin-left: -1px;">

          <template #headerCell="{ column }">
              <span v-if="column.tooltipTitle">
                {{ column.title }}
                <a-tooltip :title="column.tooltipTitle"><info-circle-outlined /></a-tooltip>
              </span>
          </template>
          <template #account="{ record }" >
            <a-popover placement="top" style="background: #0c2640 !important;">
              <template #content  style="background: #ff0 !important;">
                <p style="padding: 5px">{{ record.accountTypeName[0] }}：{{record.accountName}}</p>
                <p style="padding: 5px">{{ record.accountTypeName[1] }}：{{record.account}}</p>
                <p style="padding: 5px" v-if="record.message.instProvince">{{ record.accountTypeName[2] }}：{{record.message.instProvince}}</p>
                <p style="padding: 5px" v-if="record.message.instName">{{ record.accountTypeName[3] }}：{{record.message.instName}}</p>
                <p style="padding: 5px" v-if="record.message.instBranchName">{{ record.accountTypeName[4] }}：{{record.message.instBranchName}}</p>
              </template>
              <div class="my-tooltip-title-box"><b><a >{{record.account}}</a></b></div>
            </a-popover>
          </template>
          <template #price="{ record }" >
            <a-input-number class="con-flex-span" addon-after="元" :min="0.01" :precision="2" v-model:value="record.price" placeholder="请输入"/>
          </template>

          <template #transferDesc="{  record }">
            <a-input class="tb_width_80 con-flex-span" v-model:value="record.transferDesc" placeholder="请输入"/>
          </template>

          <template #operation="{ record }">
            <a-popconfirm  title="确认删除吗?" @confirm="onDelete(record.key)">
              <a  class="operation-a"  style="color: #ff4c5b"  >删除</a>
            </a-popconfirm>
          </template>
        </a-table>
      </a-form>

    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" @click="onClose">
        <close-outlined />
        取消
      </a-button>

      <a-button type="primary"  @click="showPay">
        <check-outlined />
        提交结算
      </a-button>
    </div>
  </a-modal>

  <a-modal style="margin-top: -70px !important;" class="modal-box" title="校验密码" v-model:visible="vdata.showPayModal"   @ok="handleOkFunc">
    <a-form ref="infoFormModel" layout="vertical" :model="vdata.saveObject">
      <a-row justify="space-between" type="flex">
          <a-col >
            <a-form-item label="手机号：" name="phoneCheck">
              <a-input v-model:value="vdata.userInfo.phoneCheck" :disabled="true" />
             </a-form-item>
          </a-col>
          <a-col >
          <div class="code-body">
            <!-- <div class="code-layout" :class="{ googleShow: !vdata.googleIsShow }"> -->
            <div class="code-layout"  >
              <div class="code code-layout-item">
                <a-form-item  required label="图形验证码：" name="vercode" class="input-item">
                  <div style="display: flex">
                    <login-text-up v-model:value="vdata.saveObject.vercode" :isLogin="true" placeholder="图形验证码" />
                    <div class="code-img" style="position: relative; background: #ddd">
                      <img v-show="vercodeImgSrc" :src="vercodeImgSrc" @click="refVercode()">
                      <div v-show="isOverdue" class="vercode-mask" @click="refVercode()">
                        已过期 请刷新
                      </div>
                    </div>
                  </div>
                </a-form-item>
              </div>
            </div>
          </div>
          </a-col>
          <a-clo>
            <div class="code">
              <a-form-item required label="验证码：" class="input-item">
                <div style="display: flex">
                  <login-text-up v-model:value="vdata.saveObject.verCode" :isLogin="true" placeholder="请输入手机验证码" />
                  <a-button type="primary"   :disabled="vdata.isDisabled"  style="height: 40px; margin-left: 10px" @click="sendSMS()" >  {{ vdata.codeBtnText }}  </a-button>

                </div>
              </a-form-item>
              <div>
              </div>
            </div>
          </a-clo>
          <a-col >
            <a-form-item required label="支付密码：" name="payPass">
              <a-input v-model:value="vdata.saveObject.payPass" maxlength="6" type="password" autocomplete="off" />

              <span  class="jeepay-tip-text">(如果当前未设置支付密码，请进入 <a href="javascript:void(0)" @click="getSetConfig">【账号中心-系统配置-安全管理】</a> 设置支付密码)</span>
            </a-form-item>
          </a-col>
      </a-row>
     </a-form>

    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" @click="getOnClose">
        <close-outlined />
        取消
      </a-button>
      <a-button type="primary" :loading="vdata.confirmLoading" @click="handleOkFunc">
        <check-outlined />
        提交
      </a-button>
    </div>
  </a-modal>
  <SybSettleUserList v-if="sybSettleUserListRefFlag" ref="sybSettleUserListRef"
                     @selectFinishFunc="selectsybSettleUserListFunc" />
</template>

<script setup lang="ts">
import {
  req,
  API_URL_PAY_TASK_LIST,
  API_URL_PAY_AQF_LIST,
  API_URL_PAY_BATCH_DATA,
  API_URL_PAY_AQF_SETTLEMENT_DATE,
  API_URL_PAY_AQF_BATCH_SETTLEMENT_DATE, $getUserInfo
} from '@/api/manage'
import {reactive, ref, getCurrentInstance, nextTick} from 'vue'
import { Base64 } from 'js-base64'
import { message } from 'ant-design-vue'
import { vercode } from '@/api/login'
import { useRouter } from 'vue-router'
import { sendSmsCode } from '@/api/login'
const router = useRouter()

const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties
  const props = defineProps ({
    configMode: { type: String, default: '' },   // 模式
    callbackFunc: { type: Function, default: () => ({}) }
  })

let vercodeImgSrc = ref('') // 验证码图片
let vercodeToken = ref('') // 验证码验证token
const sybSettleUserListRefFlag = ref()
const sybSettleUserListRef = ref()
const fileList = ref([])
const previewVisible = ref()
const previewImage = ref()
  const infoFormModel = ref()
  const vdata = reactive ({
    userInfo:{} as any,
    showPayModal:false,
    codeBtnText: '发送验证码',
    isDisabled:false,
    googleIsShow: true, // 是否让谷歌输入框展示
    filteredTaskInfoList:[] as any,
    filteredBookInfoList:[] as any,
    receiveList:[] as any,
    saveObject:{entryType:'ZFB',type:1} as any,
    confirmLoading:false,
    loading: false, // 按钮上的loading
    isAdd: true, // 新增 or 修改页面标识
    isShow: false, // 是否显示弹层/抽屉
  })
//接收方
const tableColumns = reactive([
  { key: 'accountName',title: '姓名', dataIndex: 'accountName', align: 'center',width:'10%' ,fixed: 'left'},
  { key: 'account',title: '账号', dataIndex: 'account', align: 'center',width:'10%',slots: { customRender: 'account' } ,fixed: 'left'},
  { key: 'price',title: '实发金额（元）', dataIndex: 'price', align: 'center',slots: { customRender: 'price' } ,width:'20%'},
  { key: 'transferDesc',title: '转账备注', dataIndex: 'transferDesc', align: 'center',slots: { customRender: 'transferDesc' } ,width:'20%'},
  { key: 'operation',title: '操作', dataIndex: 'operation', align: 'center',slots: { customRender: 'operation' },fixed: 'right',width:'10%' },
])
  const rules = reactive({
    taskId: [{ required: true, message: '请选择任务', trigger: 'blur' }],
    entryType: [{ required: true, message: '请选择支付方式', trigger: 'blur' }],
    transferSubjectIdFq: [{ required: true, message: '请选择付款账户', trigger: 'blur' }],
    excelFileName: [{ required: true, message: '请选择文件', trigger: 'blur' }],
  })
  defineExpose({show})
  function show (recordId) { // 弹层打开事件
    if (infoFormModel.value !== undefined) {
      infoFormModel.value.resetFields()
    }
    getTaskList()
    getBookList()
    vdata.isAdd = !recordId
    vdata.receiveList = []
    vdata.confirmLoading = false // 关闭loading


    if (!vdata.isAdd) { // 修改信息 延迟展示弹层
      vdata.isShow = true
    } else {
      vdata.isShow = true // 立马展示弹层信息
    }
  }
function getSetConfig(){
  router.push({
    path: '/config',
    query:{groupKey:"securityConfig"}
  })
}
function showPay(){
  if(!vdata.saveObject.transferSubjectIdFq){
    message.warn('请选择资金账户')
    return false;
  }
  if(vdata.receiveList.length == 0 && vdata.saveObject.type == 1 ){
    message.warn('请选择人员')
    return false;
  }
  console.log(vdata.saveObject.excelFileName,'vdatareceiveListexcelFileName')
  if(!vdata.saveObject.excelFileName && vdata.saveObject.type == 2 ){
    message.warn('请选择上传批量文件')
    return false;
  }
  getUserDetail()
  vdata.showPayModal = true
  refVercode()
}
let timer: number = -1
let isOverdue = ref(false) // 设置过期样式
function refVercode() {
  // 刷新图片验证码
  // 获取图形验证码
  vercode().then((res) => {
    vercodeImgSrc.value = res.imageBase64Data
    vercodeToken.value = res.vercodeToken

    isOverdue.value = false

    if (timer) clearInterval(timer) // 如果多次点击则清除已有的定时器
    // 超过60秒提示过期刷新
    timer = window.setInterval(() => {
      res.expireTime--
      if (res.expireTime <= 0) {
        isOverdue.value = true
        clearInterval(timer)
      }
    }, 1000)
  })
}
  function handleOkFunc () { // 点击【确认】按钮事件
    infoFormModel.value.validate().then(valid=>{
      vdata.loading = true // 打开按钮上的 loading
        vdata.confirmLoading = true // 显示loading
        if (vdata.saveObject.type == 1) {
          let transferOrders = []  as any
          for(let i =0;i<vdata.receiveList.length;i++){
            if(!vdata.receiveList[i].price){
              vdata.loading = false // 打开按钮上的 loading
              vdata.confirmLoading = false // 显示loading
              message.warn('请输入金额')
              return  false;
            }
            var price = vdata.receiveList[i].price *100
            if(price == 0){
              vdata.loading = false // 打开按钮上的 loading
              vdata.confirmLoading = false // 显示loading
              message.warn('请输入金额')
              return  false;
            }
            transferOrders.push({
              transferSubjectIdJs:vdata.receiveList[i].id as any,
              account:vdata.receiveList[i].account  as any,
              accountName:vdata.receiveList[i].accountName as any,
              transAmount:vdata.receiveList[i].price as any,
              transferDesc:vdata.receiveList[i].transferDesc as any,
            })
          }

          //支付密码
          vdata.saveObject.sipw =   Base64.encode(vdata.saveObject.payPass)
          vdata.saveObject.code =   Base64.encode(vdata.saveObject.verCode)


          let  entryType = vdata.saveObject.entryType as any;
          vdata.saveObject.entryType = entryType<=1?"ZFB":"BANK"
          vdata.saveObject.accountType = entryType=0?"C":entryType=1?"B":entryType=3?"C":"B"
          vdata.saveObject.transferOrders = transferOrders
          req.add(API_URL_PAY_AQF_SETTLEMENT_DATE, vdata.saveObject).then(res => {
            message.success('提交成功')
            vdata.isShow = false
            vdata.loading = false
            vdata.confirmLoading = false
            vdata.showPayModal = false
            props.callbackFunc() // 刷新列表
          }).catch((res) => {
            vdata.confirmLoading = false
            vdata.showPayModal = false
          })
        } else {
          //支付密码
          vdata.saveObject.sipw =   Base64.encode(vdata.saveObject.payPass)
          vdata.saveObject.code =   Base64.encode(vdata.saveObject.verCode)
          // let  entryType = vdata.saveObject.payType as any;
          // vdata.saveObject.entryType = entryType<=1?"ZFB":"BANK"
          // vdata.saveObject.accountType = entryType=0?"C":entryType=1?"B":entryType=3?"C":"B"
          req.add(API_URL_PAY_AQF_BATCH_SETTLEMENT_DATE, vdata.saveObject).then(res => {
            message.success('新增成功')
            vdata.isShow = false
            vdata.loading = false
            vdata.confirmLoading = false
            vdata.showPayModal = false
            vdata.showPayModal = false
            props.callbackFunc() // 刷新列表
          }).catch((res) => {
            vdata.confirmLoading = false
          })
        }
    })
  }
  // 关闭抽屉
  function onClose () {
    vdata.isShow = false
    vdata.showPayModal = false;
  }
  function getOnClose(){
    vdata.showPayModal = false
  }
const onDelete = (key,type=0) => {
  // if (vdata.receiveList.length <= 1) {
  //   $infoBox.message.error('最少保留一项')
  //   return false
  // }
  vdata.receiveList = vdata.receiveList.filter(item => item.key !== key)
}
const handleCancel = () => {
  previewVisible.value = false;
};
function getPayType(e){
    console.log(e,'getPayTypegetPayTypegetPayType')
}
const getTransferSubject = value => {

  console.log(value, 'valuevaluevaluevalue')
  vdata.saveObject.transferSubjectIdFq = value
  vdata.filteredBookInfoList.forEach(item => {
    if (item.id == value) {
       vdata.saveObject.balance =  (item.accountBookBalance / 100).toFixed(2)
    }
   })
  // vdata.saveObject.taskId = vdata.filteredBookInfoList[value].openOrderId
};

function getTaskList(value ='' as any){
  req.list(API_URL_PAY_TASK_LIST, { 'pageSize': 100000,taskState:1 ,appName:value}).then(res => {
    vdata.filteredTaskInfoList = res.records
  })
}
function getBookList(value ='' as any){
  req.list(API_URL_PAY_AQF_LIST, { 'pageSize': 100000,state:1,transIfCode:'aliaqf',signState:"0",subjectType:"FQ",appName:value}).then(res => {
    vdata.filteredBookInfoList = res.records
  })
}

function showSettleUserListFuncModel() {
  // vdata.saveObject.entryType
  sybSettleUserListRefFlag.value = true
  var userListIds = []
  if(vdata.receiveList.length > 0){
     for (var i=0;i<vdata.receiveList.length;i++){
       userListIds.push(vdata.receiveList[i].id)
     }
  }
  nextTick(() => {
    sybSettleUserListRef.value.show(userListIds)
  })
}
function selectsybSettleUserListFunc(e) { // 码牌选择完成事件
  sybSettleUserListRefFlag.value = false
  getUserList(e)
  sybSettleUserListRef.value.close()
}
function getUserList(value){
  req.list(API_URL_PAY_BATCH_DATA, { transferSubjects:value.join(",")}).then(res => {
    vdata.receiveList = [];
    for (var i =0;i<res.length;i++){
       res[i].key = i

      res[i].accountTypeState = 0;
      res[i].accountTypeStateDesc = '';
      if(res[i].accountType == 'C' && res[i].entryType == 'ZFB'){
        res[i].accountTypeState = 1;
        res[i].accountTypeStateDesc = '个人支付宝';
        res[i].accountTypeName = [ '支付宝名称','支付宝账号'];
      }else if(res[i].accountType == 'B' && res[i].entryType == 'ZFB'){
        res[i].accountTypeState = 2;
        res[i].accountTypeStateDesc = '企业支付宝';
        res[i].accountTypeName = [ '企业支付宝名称','企业支付宝账号'];
      }else if(res[i].accountType == 'C' && res[i].entryType == 'BANK'){
        res[i].accountTypeState = 3;
        res[i].accountTypeStateDesc = '个人银行卡';
        res[i].accountTypeName = [ '姓名','银行卡号'];
      }else if(res[i].accountType == 'B' && res[i].entryType == 'BANK'){
        res[i].accountTypeState = 4;
        res[i].accountTypeStateDesc = '对公账户';
        res[i].accountTypeName = [ '营业执照名称','对公账户账号','开户行省','开户银行','开户支行名称'];
      }
      if(!res[i].accountMessage){
        res[i].message = {};
      }else{
        var message = JSON.parse(res[i].accountMessage)
        // res.records[i].message = messgae.instProvince + "-"+messgae.instName + "-"+messgae.instBranchName
        res[i].message = message
      }
    }
    vdata.receiveList = res
  })
}

function download(){
  let fileUrl = 'https://syb-manage.oss-cn-hangzhou.aliyuncs.com/shouyinbei/%E6%89%B9%E9%87%8F%E7%BB%93%E7%AE%97.xlsx';

  // 创建一个虚拟的 a 标签
  const link = document.createElement('a');
  link.href = fileUrl;
  link.target = '_blank'; // 在新窗口或标签页中打开
  link.download = 'filename'; // 下载的文件名，你可以根据需要更改

  // 将 a 标签添加到 DOM 中
  document.body.appendChild(link);

  // 模拟点击 a 标签，触发下载
  link.click();

  // 移除添加的 a 标签
  document.body.removeChild(link);
}
function sendSMS() {


  if (!vercodeToken.value) {
    return message.error('请输入验证码！')
  }

  vdata.isDisabled = true

  sendSmsCode({ phone: vdata.userInfo.telphone, smsType: 'auth', vercode: vdata.saveObject.vercode, vercodeToken: vercodeToken.value})
      .then((res) => {
        return message.success('发送成功！')
      })
      .catch((err) => {
        vdata.isDisabled = false

        // 出错后三秒停止计时
        setTimeout(() => {
          if (timer) clearInterval(timer)
          vdata.isDisabled = false
          vdata.codeBtnText = '发送验证码'
        }, 500)
      })

  let time = 60 // 重发验证码时间
  vdata.codeBtnText = `${time}秒后重新发送`
  const timer = setInterval(() => {
    time -= 1
    vdata.codeBtnText = `${time}秒后重新发送`
    if (time === 0) {
      clearInterval(timer)
      vdata.isDisabled = false
      vdata.codeBtnText = '发送短信验证码'
    }
  }, 1000)
}
function getUserDetail () { // 获取基本信息
  $getUserInfo().then(res => {
    res.phoneCheck= maskPhoneNumber(res.telphone)
    vdata.userInfo = res
  })
}
// 图片识别的回调函数
function ocrScanFunc(orcObject: any) {
  if (orcObject) {
     vdata.saveObject.excelFileName = orcObject.ossFileUrl
  }
}
function maskPhoneNumber(phoneNumber) {
  // Ensure the input is a string
  phoneNumber = String(phoneNumber);

  // Regular expression to find the middle four digits
  const regex = /(\d{3})\d{4}(\d{4})/;

  // Replace the middle four digits with asterisks
  return phoneNumber.replace(regex, '$1****$2');
}
</script>
<style>
.tb_width_80{
  width: 80% !important;
}
.con-flex-div{
  display: flex;
  align-items: center;
  justify-content: space-around;
  width: 100%;
}

.code-body {
  padding-top: 20px;
  //width: 300px;
  overflow-x: hidden;
}

.code-layout {
  display: flex;
  //width: 600px;
  width: 100%;
  transition: 0.3s;

  .code-layout-item {
    width: 100%;
  }
}

.googleShow {
  margin-left: -300px;
}
</style>
