<template>
  <a-drawer
    :maskClosable="false"
    :visible="vdata.visible"
    :title=" vdata.isAdd ? '新增渠道' : '修改渠道' "
    :body-style="{ paddingBottom: '80px' }"
    width="40%"
    @close="onClose"
  >
    <a-form 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="ownerType" >
            <a-radio-group v-model:value="vdata.saveObject['ownerType']" @change="getInfoType" :disabled="!vdata.isAdd" :defaultValue="1">
              <a-radio :value="'AGENT'">
                服务商
              </a-radio>
              <a-radio :value="'MCH'">
                用户
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>

        <a-col :span="10">
          <a-form-item label="渠道所属ID" name="ownerNo">
            <a-select v-model:value="vdata.saveObject['ownerNo']" :disabled="!vdata.isAdd" placeholder="选择渠道所属ID" show-search @search="handleAppidChange" :filter-option="false">
              <a-select-option v-for="(item) in vdata.filteredAppInfoList" :key="item.agentNo">{{ item.name }} [{{ item.agentNo }}]</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row justify="space-between" type="flex">


        <a-col :span="10">
          <a-form-item label="渠道名称" name="isvName">
            <a-input
              v-model:value="vdata.saveObject['isvName']"
              placeholder="请输入渠道号所属公司全称"
            />
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-form-item label="渠道简称" name="isvShortName">
            <a-input
              v-model:value="vdata.saveObject['isvShortName']"
              placeholder="请输入渠道号简称"
            />
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-form-item label="渠道类型" name="isvLevel" >
            <a-radio-group v-model:value="vdata.saveObject['isvLevel']"  :disabled="!vdata.isAdd" :defaultValue="1">
              <a-radio :value="1">
                一级渠道
              </a-radio>
              <a-radio :value="2">
                二级渠道
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-form-item label="状态" name="state">
            <a-radio-group v-model:value="vdata.saveObject['state']" :defaultValue="1">
              <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="10">
          <a-form-item label="联系人姓名" name="contactName">
            <a-input
              v-model:value="vdata.saveObject['contactName']"
              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 :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="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-row>
    </a-form>
    <div class="drawer-btn-center">
      <a-button style="margin-right:8px" @click="onClose">
        <CloseOutlined />取消
      </a-button>
      <a-button type="primary" style="margin-right:8px" :loading="vdata.btnLoading" @click="handleOkFunc">
        <CheckOutlined />保存
      </a-button>
    </div>
  </a-drawer>
</template>

<script setup lang="ts" >
import {API_URL_AGENT_LIST, API_URL_ISV_LIST, API_URL_MCH_LIST, req} from '@/api/manage'
import { ref, reactive, getCurrentInstance, onMounted, defineProps, defineExpose } from 'vue'

// 导入全局函数
const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties

// 组件
const infoFormModel = ref()


// 定义函数
const props = defineProps({
  callbackFunc: { type: Function,default:null }
})


const vdata = reactive({
      filteredAppInfoList:[] as any,
      mchInfoList:[] as any,
      agentsList:[] as any,
      btnLoading: false,
      isAdd: true, // 新增 or 修改页面标志
      saveObject: {}, // 数据对象
      recordId: null, // 更新对象ID
      visible: false, // 是否显示弹层/抽屉
      rules: {
        isvLevel: [ { required: true, message: '请选择渠道级别', trigger: 'blur' } ],
        ownerType: [ { required: true, message: '请选择渠道所属', trigger: 'blur' } ],
        ownerNo: [ { required: true, message: '请选择渠道所属', trigger: 'blur' } ],
        isvName: [ { required: true, message: '请输入渠道名称', trigger: 'blur' } ],
        isvShortName: [ { required: true, message: '请输入渠道简称', 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: false, pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' }]
      }

})


    function show (recordIdParam) { // 弹层打开事件
      vdata.isAdd = !recordIdParam
      vdata.saveObject = { 'state': 1, 'isvLevel': 2 } // 数据清空
      filteredAppInfoList()
      if (infoFormModel.value !== undefined) {
        infoFormModel.value.resetFields()
      }

      if (!vdata.isAdd) { // 修改信息 延迟展示弹层
        vdata.recordId = recordIdParam
        req.getById(API_URL_ISV_LIST, vdata.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) {
              req.add(API_URL_ISV_LIST, vdata.saveObject).then(res => {
                $infoBox.message.success('新增成功')
                vdata.visible = false
                props.callbackFunc() // 刷新列表
                vdata.btnLoading = false
              }).catch(res => {
                vdata.btnLoading = false
              })
            } else {
              req.updateById(API_URL_ISV_LIST, vdata.recordId, vdata.saveObject).then(res => {
                $infoBox.message.success('修改成功')
                vdata.visible = false
                props.callbackFunc() // 刷新列表
                vdata.btnLoading = false
              }).catch(res => {
                vdata.btnLoading = false
              })
            }
        })
    }
    function onClose () {
      vdata.visible = false
    }

    function filteredAppInfoList(){
      req.list(API_URL_AGENT_LIST, { 'pageSize': -1 }).then(res => {
        vdata.agentsList = res.records
      })
      req.list(API_URL_MCH_LIST, { 'pageSize': -1 }).then(res => {
        vdata.mchInfoList = res.records
      })
    }

    function getInfoType(e){
      vdata.filteredAppInfoList = [];
      if(e.target.value == 'AGENT'){
        vdata.agentsList.forEach((item: { agentNo: string | any[], agentName: string | any[] },index) => {
          vdata.filteredAppInfoList.push({
            agentNo:item.agentNo,
            name:item.agentName,
          })
        });
      }else{
        vdata.mchInfoList.forEach((item: { mchNo: string | any[], mchName: string | any[] },index) => {
          vdata.filteredAppInfoList.push({
            agentNo:item.mchNo,
            name:item.mchName,
          })
        });
      }
 }
const handleAppidChange = (value) => {
  vdata.filteredAppInfoList = [];
  if(vdata.saveObject['ownerType'] == 1){
    vdata.agentsList.forEach((item: { agentNo: string | any[], agentName: string | any[] },index) => {
      if (item.agentName.includes(value) ) {
        vdata.filteredAppInfoList.push({
          agentNo:item.agentNo,
          name:item.agentName,
        })
      }
    });
  }else{
    vdata.mchInfoList.forEach((item: { mchNo: string | any[], mchName: string | any[] },index) => {
      if (item.mchName.includes(value) ) {
          vdata.filteredAppInfoList.push({
            agentNo:item.mchNo,
            name:item.mchName,
          })
      }
    });
  }

};
defineExpose({ show })

</script>
