<template>
  <a-drawer
    v-model:visible="vdata.visible"
    :mask-closable="false"
    :title=" vdata.isAdd ? '新增服务商' : '修改服务商' "
    :body-style="{ paddingBottom: '80px' }"
    width="40%"
    class="drawer-width"
    @close="onClose"
  >
    <a-form v-if="vdata.visible" ref="infoFormModel" :model="vdata.saveObject" layout="vertical" :rules="vdata.rules">
      <a-row justify="space-between" type="flex">
        <a-col :span="10">
          <a-form-item label="服务商名称" name="agentName">
            <a-input
              v-model:value="vdata.saveObject['agentName']"
              placeholder="请输入服务商名称"
            />
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-form-item label="登录名" name="loginUsername">
            <a-input
              v-model:value="vdata.saveObject['loginUsername']"
              placeholder="请输入服务商登录名"
              :disabled="!vdata.isAdd"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row justify="space-between" type="flex">
        <a-col :span="10">
          <a-form-item label="服务商简称" name="agentShortName">
            <a-input
              v-model:value="vdata.saveObject['agentShortName']"
              placeholder="请输入服务商简称"
            />
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-form-item label="联系人姓名" name="contactName">
            <a-input
              v-model:value="vdata.saveObject['contactName']"
              placeholder="请输入联系人姓名"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row justify="space-between" type="flex">
        <a-col :span="10">
          <a-form-item label="联系人邮箱" name="contactEmail">
            <a-input
              v-model:value="vdata.saveObject['contactEmail']"
              placeholder="请输入联系人邮箱"
            />
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-form-item label="联系人手机号" name="contactTel">
            <a-input
              v-model:value="vdata.saveObject['contactTel']"
              placeholder="请输入联系人手机号"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row justify="space-between" type="flex">
        <a-col v-if="!vdata.isAdd" :span="10">
          <a-form-item label="渠道商号" name="isvNo">
            <a-select v-model:value="vdata.saveObject['isvNo']" :disabled="!vdata.isAdd" placeholder="请选择渠道商">
              <a-select-option v-for="d in vdata.isvList" :key="d.isvNo" v-model:value="d.isvNo">
                {{ d.isvName + " [ ID: " + d.isvNo + " ]" }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-form-item label="状态" name="state">
            <a-radio-group v-model:value="vdata.saveObject['state']" :disabled="vdata.saveObject.state == '2' || vdata.saveObject.state == '3'">
              <a-radio :value="1">
                启用
              </a-radio>
              <a-radio :value="0">
                禁用
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col v-if="vdata.isAdd" :span="10">
          <a-form-item label="是否允许发展下级" name="addAgentFlag">
            <a-radio-group v-model:value="vdata.saveObject['addAgentFlag']">
              <a-radio :value="1">
                是
              </a-radio>
              <a-radio :value="0">
                否
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>


      <!-- <a-row justify="space-between" type="flex">
        <a-col :span="24">
          <a-form-item label="备注" name="remark">
            <a-input v-model:value="vdata.saveObject['remark']" placeholder="请输入备注" type="textarea" />
          </a-form-item>
        </a-col>
      </a-row> -->

      <!-- 重置密码板块 -->
      <a-row justify="space-between" type="flex">
        <a-col :span="24">
          <a-divider orientation="left">
            <a-tag color="#FF4B33">
              账户安全
            </a-tag>
          </a-divider>
        </a-col>
      </a-row>
      <div v-if="vdata.isAdd">
        <a-row justify="space-between" type="flex">
          <a-col :span="24">
            <a-form-item label="是否发送开通提醒">
              <a-radio-group v-model:value="vdata.saveObject['isNotify']">
                <a-radio :value="0">否</a-radio>
                <a-radio :value="1">是</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="密码设置">
              <a-radio-group v-model:value="vdata.saveObject['passwordType']">
                <a-radio value="default">默认密码</a-radio>
                <a-radio value="custom">自定义密码</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col v-if="vdata.saveObject.passwordType == 'custom'" :span="12">
            <a-form-item label="登录密码" name="loginPassword">
              <a-input
                v-model:value="vdata.saveObject['loginPassword']"
                placeholder="请输入登录密码"
              />
            </a-form-item>
            <a-button type="primary" ghost @click="randomPassage(false, 6, 0)"><file-sync-outlined />随机生成密码</a-button>
          </a-col>
        </a-row>
      </div>
      <div v-else>
        <div>
          <a-row justify="space-between" type="flex">
            <a-col :span="10">
              <a-form-item v-if="vdata.resetIsShow" label="">
                重置密码：<a-checkbox v-model:checked="vdata.sysPassword.resetPass" />
              </a-form-item>
            </a-col>
            <a-col :span="10">
              <a-form-item v-if="vdata.sysPassword.resetPass" label="">
                恢复默认密码：<a-checkbox v-model:checked="vdata.sysPassword.defaultPass" @click="isResetPass" />
              </a-form-item>
            </a-col>
          </a-row>
        </div>

        <div v-if="vdata.sysPassword.resetPass">
          <div v-if="!vdata.sysPassword.defaultPass">
            <a-row justify="space-between" type="flex">
              <a-col :span="10">
                <a-form-item label="新密码：" name="newPwd">
                  <a-input-password v-model:value="vdata.newPwd" autocomplete="new-password" :disabled="vdata.sysPassword.defaultPass" />
                </a-form-item>
              </a-col>

              <a-col :span="10">
                <a-form-item label="确认新密码：" name="confirmPwd">
                  <a-input-password v-model:value="vdata.sysPassword.confirmPwd" autocomplete="new-password" :disabled="vdata.sysPassword.defaultPass" />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </div>
      </div>
      <div v-if="vdata.isAudit">
        <a-row justify="space-between" type="flex">
          <a-col :span="24">
            <a-divider orientation="left">
              <a-tag color="#FF4B33">
                账户信息
              </a-tag>
            </a-divider>
          </a-col>
        </a-row>
        <a-row justify="space-between" type="flex">
          <a-col :span="10">
            <a-form-item label="服务商类型" name="agentType">
              <a-select v-model:value="vdata.saveObject['agentType']" :defaultValue="1">
                <a-select-option :value="1">个人</a-select-option>
                <a-select-option :value="2">企业</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item label="收款账户类型" name="settAccountType">
              <a-select v-model:value="vdata.saveObject['settAccountType']" defaultValue="ALIPAY_CASH">
                <a-select-option value="ALIPAY_CASH">个人支付宝</a-select-option>
                <a-select-option value="BANK_PRIVATE">对私账户</a-select-option>
                <a-select-option v-if="vdata.saveObject['agentType'] !== 1" value="BANK_PUBLIC">对公账户</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-if="vdata.saveObject['settAccountType'] === 'ALIPAY_CASH'" justify="space-between" type="flex">
          <a-col :span="10">
            <a-form-item label="账户姓名">
              <a-input
                v-model:value="vdata.saveObject['settAccountName']"
              />
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item label="支付宝账号">
              <a-input
                v-model:value="vdata.saveObject['settAccountNo']"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-if="vdata.saveObject['settAccountType'] === 'BANK_PRIVATE'" justify="space-between" type="flex">
          <a-col :span="10">
            <a-form-item label="账户姓名">
              <a-input
                v-model:value="vdata.saveObject['settAccountName']"
              />
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item label="开户银行名称">
              <a-input
                v-model:value="vdata.saveObject['settAccountBank']"
              />
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item label="收款银行卡号">
              <a-input
                v-model:value="vdata.saveObject['settAccountNo']"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-if="vdata.saveObject['settAccountType'] === 'BANK_PUBLIC'" justify="space-between" type="flex">
          <a-col :span="10">
            <a-form-item label="对公账户名称">
              <a-input
                v-model:value="vdata.saveObject['settAccountName']"
              />
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item label="对公账号">
              <a-input
                v-model:value="vdata.saveObject['settAccountNo']"
              />
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item label="开户银行名称">
              <a-input
                v-model:value="vdata.saveObject['settAccountBank']"
              />
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item label="开户行支行名称">
              <a-input
                v-model:value="vdata.saveObject['settAccountSubBank']"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row justify="space-between" type="flex">
          <a-col :span="24">
            <a-divider orientation="left">
              <a-tag color="#FF4B33">
                资料信息
              </a-tag>
            </a-divider>
          </a-col>
        </a-row>
        <a-row justify="space-between" type="flex">
          <a-col v-if="vdata.saveObject['agentType'] == 2" :span="10">
            <a-form-item label="营业执照照片" name="licenseImg">
              <JeepayUpload v-model:src="vdata.saveObject['licenseImg']" bizType="applyment" />
            </a-form-item>
          </a-col>
          <a-col v-if="vdata.saveObject['agentType'] == 2 && vdata.saveObject['settAccountType'] == 'BANK_PUBLIC'" :span="10">
            <a-form-item label="开户许可证照片" name="permitImg">
              <JeepayUpload v-model:src="vdata.saveObject['permitImg']" bizType="applyment" />
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item :label="vdata.saveObject['agentType'] == 1?'[联系人]身份证人像面照片':'[法人]身份证人像面照片'" name="idcard1Img">
              <JeepayUpload v-model:src="vdata.saveObject['idcard1Img']" bizType="applyment" />
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item :label="vdata.saveObject['agentType'] == 1?'[联系人]身份证国徽面照片':'[法人]身份证国徽面照片'" name="idcard2Img">
              <JeepayUpload v-model:src="vdata.saveObject['idcard2Img']" bizType="applyment" />
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item :label="vdata.saveObject['agentType'] == 1?'[联系人]手持承诺函照片':'[法人]手持承诺函照片'" name="idcardInHandImg">
              <JeepayUpload v-model:src="vdata.saveObject['idcardInHandImg']" bizType="applyment" />
            </a-form-item>
          </a-col>
          <a-col v-if="vdata.saveObject['settAccountType'] == 'BANK_PRIVATE'" :span="10">
            <a-form-item label="银行卡照片" name="bankCardImg">
              <JeepayUpload v-model:src="vdata.saveObject['bankCardImg']" bizType="applyment" />
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item label="手持承诺函照示例：" name="">
              <a-image style="width: 100px;height: 120px;" src="https://jeepaypublic.oss-cn-beijing.aliyuncs.com/oem/b1cd1646-fdd2-4ea7-8f1f-02a55669f534.svg" />
              <span><a :href="vdata.promiseFile">模板下载</a></span>
            </a-form-item>
          </a-col>
        </a-row>
      </div>
    </a-form>
    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" style="margin-right:8px" @click="onClose">
        <close-outlined />
        取消
      </a-button>
      <a-button type="primary" :loading="vdata.btnLoading" @click="handleOkFunc">
        <check-outlined />
        保存
      </a-button>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
import { API_URL_AGENT_LIST, API_URL_ISV_LIST, req, $getPasswordRules, $getMainUserInfo } from '@/api/manage'
import { Base64 } from 'js-base64'
import {message} from 'ant-design-vue'
import {defineProps,reactive,ref} from 'vue'

    const props = defineProps({
    callbackFunc: { type: Function,default:null }
    })


  const checkIsvNo = (rule, value) => { // 校验是否选择了渠道商
    if (!value) {
      return Promise.reject(new Error('请选择渠道商'))
    }
    return Promise.resolve()
  }
  const infoFormModel = ref()
  const infoTable =ref()
  const vdata : any = reactive({
    newPwd: '', //  新密码
    resetIsShow: false, // 重置密码是否展现
    passwordRules: /^$/, //密码规则
    passwordRulesText: '', //密码规则提示文字
    sysPassword: {
      resetPass: false, // 重置密码
      defaultPass: true, // 使用默认密码
      confirmPwd: '' //  确认密码
    },
    btnLoading: false,
    isAdd: true, // 新增 or 修改页面标志
    isAudit: false,
    saveObject: { isNotify: 0 }, // 数据对象
    recordId: null, // 更新对象ID
    visible: false, // 是否显示弹层/抽屉
    isvList: [] as any, // 渠道商下拉列表
    rules: {
      agentName: [{ required: true, message: '请输入服务商名称', trigger: 'blur' }],
      loginUsername: [{ required: true, pattern: /^[a-zA-Z][a-zA-Z0-9]{5,17}$/, message: '请输入字母开头，长度为6-18位的登录名', trigger: 'blur' }],
      agentShortName: [{ required: true, message: '请输入服务商简称', trigger: 'blur' }],
      contactName: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
      isvNo: [{ validator: checkIsvNo, trigger: 'blur' }],
      contactEmail: [{ required: false, pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/, message: '请输入正确的邮箱地址', trigger: 'blur' }],
      contactTel: [{ required: true, pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' }],
      newPwd: [{ required: false, trigger: 'blur' }, {
        validator: (rule, value) => {
          if (!vdata.sysPassword.defaultPass) {
            if (!vdata.passwordRules.test(vdata.newPwd)) {
              return Promise.reject(vdata.passwordRulesText)
            } else if(vdata.newPwd !== vdata.sysPassword.confirmPwd) {
              return Promise.reject('新密码与确认密码不一致')
            } else return Promise.resolve()
          } else {
              return Promise.resolve()
          }

        }
      }], // 新密码
      confirmPwd: [{ required: false, trigger: 'blur' }, {
        validator: (rule, value) => {
          if (!vdata.sysPassword.defaultPass) {
            // vdata.newPwd === vdata.sysPassword.confirmPwd ? callBack() : callBack('新密码与确认密码不一致')
            if(!vdata.passwordRules.test(vdata.sysPassword.confirmPwd)){
              return Promise.reject(vdata.passwordRulesText)
            } else if(vdata.newPwd !== vdata.sysPassword.confirmPwd) {
              return Promise.reject('新密码与确认密码不一致')
            } else return Promise.resolve()
          } else {
              return Promise.resolve()
          }
        }
      }] // 确认新密码
    }
  })
  function getPasswordRules () { // 获取密码规则
    $getPasswordRules().then(res => {
      vdata.passwordRules = new RegExp(res.regexpRules)
      vdata.passwordRulesText = res.errTips
      if(res.subIsAudit == '1') {
        vdata.saveObject['settAccountType'] = 'ALIPAY_CASH'
        vdata.isAudit = true
      }
    })
  }
  function show (recordId) { // 弹层打开事件
    getPasswordRules()

    // 查询手持承诺函模板
    getAgentInfo()

    vdata.isAdd = !recordId
    vdata.saveObject = { 'state': 1, passwordType: 'default', 'addAgentFlag': 1, isNotify: 0, agentType: 1 } // 数据清空
    if (infoFormModel.value != undefined) {
      infoFormModel.value.resetFields()
    }

    req.list(API_URL_ISV_LIST, { 'pageSize': -1, 'state': 1 }).then(res => { // 渠道商下拉选择列表
      vdata.isvList = res.records
    })

    if (!vdata.isAdd) { // 修改信息 延迟展示弹层
      vdata.resetIsShow = true // 展示重置密码板块
      vdata.recordId = recordId
      req.getById(API_URL_AGENT_LIST, recordId).then(res => {
        vdata.saveObject = res
      })
      vdata.visible = true
    } else {
      vdata.visible = true // 立马展示弹层信息
    }
  }
  function handleOkFunc () { // 点击【确认】按钮事件
      infoFormModel.value.validate().then(valid =>{

          vdata.btnLoading = true

          // 请求接口
          if (vdata.isAdd) {
            // 如果新增密码设置为默认密码，登录密码设置为空
            if(vdata.saveObject.passwordType == 'default' || !vdata.saveObject.loginPassword) {
              vdata.saveObject.loginPassword = ''
            }
            if(vdata.saveObject.passwordType == 'custom' && !vdata.passwordRules.test(vdata.saveObject.loginPassword)) {
              vdata.btnLoading = false
              return message.error(vdata.passwordRulesText)
            }
            req.add(API_URL_AGENT_LIST, vdata.saveObject).then(res => {
              message.success('新增成功')
              vdata.visible = false
              props.callbackFunc() // 刷新列表
              vdata.btnLoading = false
            }).catch(res => {
              vdata.btnLoading = false
            })
          } else {

            vdata.sysPassword.confirmPwd = Base64.encode(vdata.sysPassword.confirmPwd)
            Object.assign(vdata.saveObject, vdata.sysPassword) // 拼接对象
            req.updateById(API_URL_AGENT_LIST, vdata.recordId, vdata.saveObject).then(res => {
              message.success('修改成功')
              vdata.visible = false
              props.callbackFunc() // 刷新列表
              vdata.btnLoading = false
              vdata.resetIsShow = true // 展示重置密码板块
              vdata.sysPassword.resetPass = false
              vdata.sysPassword.defaultPass = true // 是否使用默认密码默认为true
              resetPassEmpty(DataView) // 清空密码
            }).catch(res => {
              vdata.btnLoading = false
              vdata.resetIsShow = true // 展示重置密码板块
              vdata.sysPassword.resetPass = false
              vdata.sysPassword.defaultPass = true // 是否使用默认密码默认为true
              resetPassEmpty(vdata) // 清空密码
            })
          }

      }).catch(valid =>{
      })
  }
  function  onClose () {
    vdata.visible = false
    vdata.resetIsShow = false // 取消重置密码板块展示
    vdata.sysPassword.resetPass = false
    resetPassEmpty(vdata)
    vdata.sysPassword.defaultPass = true// 是否使用默认密码默认为true
  }
  // 使用默认密码重置是否为true
  function isResetPass () {
    if (!vdata.sysPassword.defaultPass) {
      vdata.newPwd = ''
      vdata.sysPassword.confirmPwd = ''
    }
  }
  // 保存后清空密码
  function resetPassEmpty (vdata) {
    vdata.newPwd = ''
    vdata.sysPassword.confirmPwd = ''
  }

  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
  }

  function getAgentInfo() {
    // 获取服务商信息
    $getMainUserInfo().then((res) => {
      vdata.promiseFile = res.promiseFile
    })
  }

defineExpose({
  show
})
</script>
<style lang="less">
  .typePopover {
    position: absolute;
    top: 0;
    left:62px;
  }
</style>
