<template>

      <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="36">
          <a-form-item label="结算账户类型" name="type">
            <a-radio-group v-model:value="vdata.saveObject['type']" :disabled="!vdata.isAdd" @change="getObjectType">
              <a-radio :value="1">个人支付宝 </a-radio>
              <a-radio :value="2">企业支付宝</a-radio>
              <a-radio :value="3">个人银行卡</a-radio>
              <a-radio :value="4">对公账户</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
<!--        <a-col :span="36">-->
<!--          <a-form-item label="结算账户类型" name="entryType">-->
<!--            <a-radio-group v-model:value="vdata.saveObject['entryType']" :disabled="!vdata.isAdd">-->
<!--              <a-radio value="ZFB">支付宝 </a-radio>-->
<!--              <a-radio value="BANK">银行卡</a-radio>-->
<!--            </a-radio-group>-->
<!--          </a-form-item>-->
<!--        </a-col>-->
      </a-row>
      <a-row justify="space-between" type="flex">
        <div v-if="vdata.saveObject['accountType'] == 'C' && vdata.saveObject['entryType'] == 'ZFB'" class="space-between-div-type">
          <a-col :span="36">
            <a-form-item label="支付宝姓名" name="accountName">
              <a-input v-model:value="vdata.saveObject['accountName']" :disabled="!vdata.isAdd" />
            </a-form-item>
          </a-col>
          <a-col :span="36">
            <a-form-item label="支付宝账号" name="account">
              <a-input v-model:value="vdata.saveObject['account']" :disabled="!vdata.isAdd" />
            </a-form-item>
          </a-col>
        </div>


        <div v-if="vdata.saveObject['accountType'] == 'B'  && vdata.saveObject['entryType'] == 'ZFB'" class="space-between-div-type">
          <a-col :span="24">
            <a-form-item label="营业执照名称" name="accountName">
              <a-input v-model:value="vdata.saveObject['accountName']" :disabled="!vdata.isAdd" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="企业支付宝账号" name="account">
              <a-input v-model:value="vdata.saveObject['account']" :disabled="!vdata.isAdd" />
            </a-form-item>
          </a-col>
        </div>

        <div v-if="vdata.saveObject['accountType'] == 'C'  && vdata.saveObject['entryType'] == 'BANK'" class="space-between-div-type">
          <a-col :span="24">
            <a-form-item label="姓名" name="accountName">
              <a-input v-model:value="vdata.saveObject['accountName']" :disabled="!vdata.isAdd" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="银行卡号" name="account">
              <a-input v-model:value="vdata.saveObject['account']" :disabled="!vdata.isAdd" />
            </a-form-item>
          </a-col>
        </div>

        <div v-if="vdata.saveObject['accountType'] == 'B' &&  vdata.saveObject['entryType'] == 'BANK'" class="space-between-div-type">
          <a-col :span="24">
            <a-form-item label="营业执照名称" name="accountName">
              <a-input v-model:value="vdata.saveObject['accountName']" :disabled="!vdata.isAdd" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="对公账户账号" name="account">
              <a-input v-model:value="vdata.saveObject['account']" :disabled="!vdata.isAdd" />
            </a-form-item>
          </a-col>
          <a-form-item  label="开户行省市县" name="areaCode">
            <JeepayAreaSelect v-if="vdata.isAdd" v-model:value="vdata.saveObject.areaCode" @change="changeBankAreaFunc" />
            <a-input v-if="!vdata.isAdd" v-model:value="vdata.saveObject['account']" />
          </a-form-item>
<!--          <a-form-item  label="开户银行名称" name="bankName">-->
<!--            <a-input v-model:value="vdata.saveObject['bankName']"  />-->
<!--          </a-form-item>-->

          <a-form-item  label="开户支行名称" name="instBranchName">
            <a-select
                :disabled="!vdata.isAdd"
                v-model:value="vdata.saveObject.account_message.instBranchName"
                placeholder="选择支行"
                show-search
                label-in-value
                :filter-option="false"
                @search="handleBankSearch"
                @change="handleBankChange"
                :getPopupContainer="(triggerNode) => triggerNode.parentElement"
            >
              <a-select-option v-for="(item, index) in vdata.filteredBankInfoList" :key="index" :value="index">
                {{ item.branchName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </div>


      </a-row>

      <div class="drawer-btn-center">
        <a-button :style="{ marginRight: '8px' }" @click="onClose">
          <close-outlined />
          取消
        </a-button>
        <a-button v-if="vdata.isAdd" type="primary" :loading="vdata.confirmLoading" @click="handleOkFunc">
          <check-outlined />
          保存
        </a-button>
      </div>
    </a-form>
</template>

<script setup lang="ts">
import {
  req,
  API_URL_SYS_USER_LIST,
  API_URL_MCH_APPLYMENT_LIST,
  $bankBranchList,
  $getUserInfo,
  API_URL_PAY_AQF_ADD_JS
} from '@/api/manage'
import {defineEmits, getCurrentInstance, reactive, ref} from 'vue'
import { debounce } from "lodash-es";
import { Base64 } from 'js-base64'
import {message, SelectProps} from 'ant-design-vue'
const { $infoBox,$viewerApi } = getCurrentInstance()!.appContext.config.globalProperties

const props = defineProps ({
  configMode: { type: String, default: '' },   // 模式
  callbackFunc: { type: Function, default: () => ({}) }
})

const emit = defineEmits(['itemRender'])
const fileList = ref([])
const previewVisible = ref()
const previewImage = ref()
const infoFormModel = ref()
const vdata = reactive ({
  userInfo:[] as any,
  loading: false, // 按钮上的loading
  value: 1, // 单选框默认的值
  teamList: [] as any, // 团队列表
  confirmLoading: false, // 显示确定按钮loading图标
  isAdd: true, // 新增 or 修改页面标识
  isShow: false, // 是否显示弹层/抽屉
  saveObject: {account_message:{} as any} as any, // 数据对象
  recordId: null, // 更新对象ID
  bankInfoList: [] as any, // 团队列表
  filteredBankInfoList: [] as any, // 团队列表
})
const rules = reactive({
  // accountType: [{ required: true, message: '请选择人员类型', trigger: 'blur' }],
  type: [{ required: true, message: '请选择结算账户类型', trigger: 'blur' }],
  accountName: [{ required: true, message: '请选择名称', trigger: 'blur' }],
  account: [{ required: true, message: '请选择账号', trigger: 'blur' }],
  areaCode: [{ required: true, message: '请选择开户行省市县', trigger: 'blur' }],
  instBranchName: [{ required: true, message: '请选择支行名称', trigger: 'blur' }],
})
defineExpose({show})
function show (record=null as any) { // 弹层打开事件

  if(props.configMode == 'mch'){
     detail()
  }
  console.log(record,'recordId')
  vdata.isAdd = !record
  // 数据恢复为默认数据
  vdata.saveObject = {account_message:{} as any} as any
   vdata.confirmLoading = false // 关闭loading


  if (!vdata.isAdd) { // 修改信息 延迟展示弹层
    vdata.recordId = record
    // const  account_message =  JSON.parse(record.accountMessage)
    // vdata.saveObject.account_message = account_message
    vdata.isShow = true
  } else {

    vdata.isShow = true // 立马展示弹层信息
  }
}
function handleOkFunc () { // 点击【确认】按钮事件
  infoFormModel.value.validate().then(valid=>{
    vdata.loading = true // 打开按钮上的 loading
    vdata.confirmLoading = true // 显示loading
    if (vdata.isAdd) {
      if(vdata.saveObject.areaName){
        vdata.saveObject.account_message.instProvince = vdata.saveObject.areaName[0]
        vdata.saveObject.account_message.instProvinceCode = vdata.saveObject.areaCode[0]
        vdata.saveObject.account_message.instCity = vdata.saveObject.areaName[1]
        vdata.saveObject.account_message.instCityCode = vdata.saveObject.areaCode[1]
      }
      if(vdata.saveObject.type == 1){
        vdata.saveObject.accountType = 'C'
        vdata.saveObject.entryType = 'ZFB'
      }else if(vdata.saveObject.type == 2){
        vdata.saveObject.accountType = 'B'
        vdata.saveObject.entryType = 'ZFB'
      }else if(vdata.saveObject.type == 3){
        vdata.saveObject.accountType = 'C'
        vdata.saveObject.entryType = 'BANK'
      }else{
        vdata.saveObject.accountType = 'B'
        vdata.saveObject.entryType = 'BANK'
      }

      req.add(API_URL_PAY_AQF_ADD_JS, vdata.saveObject).then(res => {
        message.success('新增成功')
        vdata.isShow = false
        vdata.loading = false
        onClose()
      }).catch((res) => {
        vdata.confirmLoading = false
      })
    } else {
      // req.updateById(API_URL_SYS_USER_LIST, vdata.recordId, vdata.saveObject).then(res => {
      //   message.success('修改成功')
      //   vdata.isShow = false
      //   props.callbackFunc() // 刷新列表
      // }).catch(res => {
      //   vdata.confirmLoading = false
      // })
    }
  })
}
// 关闭抽屉
function onClose () {
  vdata.isShow = false

  emit('itemRender')
}

// 切换操作员类型
function changeUserType() {
  if (vdata.saveObject.userType == 1 || vdata.saveObject.userType == 2) {
    vdata.saveObject.isTeamLeader = 0
    vdata.saveObject.teamId = ''
  }
}

function randomPassage(randomFlag, min, max) { // 生成6位随机密码
  let str = ''
  let range = min
  const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  // 随机产生
  if (randomFlag) {
    range = Math.round(Math.random() * (max - min)) + min
  }
  for (var i = 0; i < range; i++) {
    var pos = Math.round(Math.random() * (arr.length - 1))
    str += arr[ pos ]
  }
  vdata.saveObject['loginPassword'] = str
}

const handleCancel = () => {
  previewVisible.value = false;
};


function detail () { // 获取基本信息

  $getUserInfo().then(res => {
    vdata.userInfo = res
    console.log(vdata.userInfo,'vdatauserInfovdatauserInfovdatauserInfo')
  })
}


// 开户行所在省市区
const changeBankAreaFunc:any = debounce((value) => {

  // 区编码
  if (vdata.saveObject?.areaCode?.[1]) {
    vdata.saveObject.settAccountBankBranchAreaName = [];
    vdata.saveObject.areaName = [value[0].label,value[1].label,value[2].label]

    // 区编码
    if (value[2]?.label) {
      vdata.bankInfoList = []
      vdata.filteredBankInfoList = []

      const param = {
        cityCode: vdata.saveObject.areaName[1],
      };
      if(vdata.saveObject.branName){
        // param.branName :any = vdata.saveObject.branName
      }
      $bankBranchList(vdata.userInfo.userNo, 'zftpay', param,null as any).then((res) => {
        if (res?.length) {
          res.forEach(element => {
            vdata.bankInfoList.push(element);
            vdata.filteredBankInfoList.push(element);
          })
        } else {
          $infoBox.message.error('该地区下未找到对应银行列表')
        }
      })
    } else {
      $infoBox.message.warn('请先选择地区')
    }
  }
}, 300)

const handleBankChange: SelectProps['onChange'] = (option :any) => {

  // vdata.saveObject.branchCode = option.value;
  console.log(option,'optionoptionoptionoption')
  // vdata.filteredBankInfoList.forEach(item => {
  //   if (item.branchNo == option.value) {
      vdata.saveObject.account_message.instBranchName = vdata.filteredBankInfoList[option.value].branchName
      vdata.saveObject.account_message.instBranchCode = vdata.filteredBankInfoList[option.value].branchNo
      // vdata.saveObject.branchCode = item.value
      vdata.saveObject.account_message.instName = vdata.filteredBankInfoList[option.value].bankName
      vdata.saveObject.account_message.instCode = vdata.filteredBankInfoList[option.value].bankAbbr
  //   }
  // });
  console.log( vdata.saveObject,' vdatasaveObjectvdatasaveObject')
};
const handleBankSearch = (option) => {
  console.log("handBankSearch", option);
  if(!isChinese(option)){
    return false;
  }
  addCity(option)
};
function isChinese(str) {
  var reg = /[\u4e00-\u9fa5]/; // Unicode范围内的汉字编码
  return reg.test(str);
}
function addCity(value) {
  vdata.bankInfoList = []
  vdata.filteredBankInfoList = []
  const param = {
    cityCode: vdata.saveObject.areaName[1],
    branchName: value,
  };
  $bankBranchList(vdata.userInfo.userNo, 'zftpay', param,null as any).then((res) => {
    if (res?.length) {
      res.forEach(element => {
        vdata.bankInfoList.push(element);
        vdata.filteredBankInfoList.push(element);
      })
    } else {
      $infoBox.message.error('该支行名称未搜索到或该地区没有对应的银行列表')
    }
  })
}
function getObjectType(){
  if(vdata.saveObject.type == 1){
    vdata.saveObject.accountType = 'C'
    vdata.saveObject.entryType = 'ZFB'
  }else if(vdata.saveObject.type == 2){
    vdata.saveObject.accountType = 'B'
    vdata.saveObject.entryType = 'ZFB'
  }else if(vdata.saveObject.type == 3){
    vdata.saveObject.accountType = 'C'
    vdata.saveObject.entryType = 'BANK'
  }else{
    vdata.saveObject.accountType = 'B'
    vdata.saveObject.entryType = 'BANK'
  }
}
</script>
<style>
.space-between-div-type{
  width: 100% !important;
}
</style>
