<template>
  <a-drawer
    v-model:visible="vdata.visible"
    :mask-closable="false"
    :title="'预警设置'"
    width="40%"
    class="drawer-width"
    @close="onClose"
  >
    <a-divider class="jeepay-m-divider" orientation="left" style="color: #1A66FF;">{{vdata.earlyInfo.typeNameDesc}}提醒设置</a-divider>
    <a-form v-if="vdata.visible" ref="infoFormModel" :model="vdata.saveObject" :rules="saveRule" layout="vertical">
      <a-row justify="space-between" type="flex">

        <a-col :span="11">
          <a-form-item label="余额小于（元）" name="amount">
            <a-input-number v-model:value="vdata.saveObject.amount"  style="width:330px" placeholder="请设置金额"/>
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="规则状态" name="remindState">
            <a-radio-group name="remindState" v-model:value="vdata.saveObject.remindState">
              <a-radio :value="1">开启</a-radio>
              <a-radio :value="0">关闭</a-radio>
            </a-radio-group>
          </a-form-item>

        </a-col>
        <a-col :span="11">
          <a-form-item label="提醒频率" name="interval">
            <a-select v-model:value="vdata.saveObject.interval" placeholder="请选择提醒频率">
              <a-select-option :value="6">6小时/次</a-select-option>
              <a-select-option :value="12">12小时/次</a-select-option>
              <a-select-option :value="24">24小时/次</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="提醒方式" name="typeList">
            <a-checkbox-group v-model:value="checkValue" @change="getFilteredColumns">
              <a-checkbox value="mail" disabled>站内信</a-checkbox>
                <a-checkbox value="email">邮件</a-checkbox>
                <a-checkbox value="phone">短信</a-checkbox>
            </a-checkbox-group>
          </a-form-item>
        </a-col>



      </a-row>
    </a-form>


    <a-divider class="jeepay-m-divider" orientation="left" style="color: #1A66FF;">接收人信息设置</a-divider>
    <a-form  ref="infoFormModel2" :model="vdata.saveObject" :rules="saveRule" layout="vertical" style="margin-bottom: 20px;">
<!--      <a-row justify="space-between" type="flex">-->
<!--        <a-col :span="24">-->
<!--          <a-form-item>-->
<!--            <a-button type="dashed" @click="addDomain"><PlusOutlined />新增</a-button>-->
<!--          </a-form-item>-->
<!--        </a-col>-->
<!--        <a-col :span="24">-->
<!--        </a-col>-->

<!--      </a-row>-->

      <a-table bordered v-if="vdata.feeColumns.length >1 " :data-source="vdata.deviceList" :columns="vdata.feeColumns" :pagination="false" style="margin-left: -1px;">

        <template #bodyCell="{column, record,index}">

        <template v-if="column.key == 'email'">
          <a-input v-model:value="record.email" placeholder="请输入邮箱" />
        </template>

        <template v-if="column.key === 'phone'">
          <a-input v-model:value="record.phone" placeholder="请输入电话" />
        </template>

        <template v-if="column.key === 'operation'">
          <a-button  type="link" @click="addDomain">添加</a-button>
          <a-button  type="link" style="color:red"  @click="onDelete(index)">删除</a-button>
        </template>
        </template>
      </a-table>

<!--      <a-row v-for="(item, index) in vdata.deviceList" :key="index" justify="start" type="flex" :gutter="8">-->

<!--          <a-form-item-->
<!--              v-if="checkValue.indexOf('email') !== -1"-->
<!--              layout="vertical"-->
<!--              label="邮箱"-->
<!--              :name="['deviceList', index, 'email']"-->
<!--              :rules="{-->
<!--                required: false,-->
<!--                message: '邮箱不能为空',-->
<!--                trigger: 'blur',-->
<!--              }"-->
<!--          >-->
<!--            <a-input v-model:value="item.email" placeholder="请输入" />-->
<!--          </a-form-item>-->

<!--          <a-form-item label="联系电话" style="margin-left: 10px" v-if="checkValue.indexOf('phone') !== -1">-->
<!--            <a-input v-model:value="item.phone"-->

<!--                     :rules="{-->
<!--                required: false,-->
<!--                message: '联系电话不能为空',-->
<!--                trigger: 'blur',-->
<!--              }" placeholder="请输入" />-->
<!--          </a-form-item>-->
<!--        <a-button v-if="index >= 1" danger type="link" @click="removeDomain(item)"><MinusCircleOutlined class="delete-button" /></a-button>-->
<!--      </a-row>-->
    </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" @click="handleOkFunc"><check-outlined />保存</a-button>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>

import {
  API_URL_MCH_QR_CODE_LIST,
  API_URL_MCH_APP,
  API_URL_MCH_STORE_LIST,
  $getPayAccountWarnRule,
  req,
  $getMchIncomingRefresh
} from '@/api/manage'
import {defineProps, reactive, ref, getCurrentInstance, defineEmits} from 'vue'
import {message} from "ant-design-vue";
const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties


// 定义组件参数
const props = defineProps({
  callbackFunc: {type: Function, default: () => {}}
})

// 定义ref对象
const infoFormModel = ref()

const saveRule = {
  remindState: [{ required: true, message: '请设置规则状态', trigger: 'blur' }],
  amount: [{ required: true, message: '请设置金额临界值', trigger: 'blur' }],
  interval: [{ required: true, message: '请选择提醒时间间隔', trigger: 'blur' }],
}

const checkValue = ref(['mail']);
const vdata = reactive({
  earlyInfo:{} as any,//预警设置
  deviceList: [{ email: '', phone: '' }] as any, // 配置对象
  isAdd: true, // 新增 or 修改页面标志
  recordId: null, // 更新对象ID
  visible: false, // 是否显示弹层/抽屉
  saveObject: {} as any, // 数据对象
  amount:"" as any,
  remindState:1 as any,
  mchAppList: [] as any, // 商户应用的List
  storeList: [] as any, // 商户门店的List
  filteredStoreInfoList:[] as any,
  filteredAppInfoList:[] as any,
  feeColumns: [
    {key:"email", title: '邮箱',  dataIndex: 'email', hidden: false},
    {key:"phone", title: '短信', dataIndex: 'phone', hidden: false},
    { key:"operation", title: '操作',   dataIndex: 'operation',   },
  ],
  feeColumnsList: [
    {key:"email", title: '邮箱',  dataIndex: 'email'},
    {key:"phone", title: '短信', dataIndex: 'phone'},
    { key:"operation", title: '操作',   dataIndex: 'operation',   },
  ],
})
function getFilteredColumns(e){
  const feeColumnsList = vdata.feeColumnsList;
  const feeColumns = []  as any;
  feeColumnsList.forEach(item=>{
    const value = item as any;
    if(item.key != 'operation'){
      if(e.indexOf(item.key) !== -1){
        feeColumns.push(item)
      }
    }else{
      feeColumns.push(item)
    }
  })
  vdata.feeColumns = feeColumns
}
function onDelete (index){
  console.log(index,'indexindexindexindex')
  console.log(vdata.deviceList,'indexindexindexindex')
  if (vdata.deviceList.length <= 1) {
    $infoBox.message.error('最少保留一项')
    return false
  }
  const deviceList = vdata.deviceList
  vdata.deviceList = [];
  delete deviceList[index]
  deviceList.forEach(item=>{
    vdata.deviceList.push(item)
  })
}
function addDomain() {
  if(vdata.deviceList.length == 5){
    $infoBox.message.error('只能新增5个接收人')
    return false;
  }
let typeList = checkValue.value;
  console.log(typeList,'typeList')
  console.log(typeList.indexOf('email') !== -1,'typeList.indexOf')
  console.log(typeList.indexOf('phone') !== -1,'typeList.indexOf')
  if(!(typeList.indexOf('email') !== -1) && !(typeList.indexOf('phone') !== -1)){
    $infoBox.message.error('请设置提醒方式为短信或者邮箱')
    return false;
  }
  vdata.deviceList.push({
    email: '',
    phone: ''
  })
}
function removeDomain(item) {
  const index = vdata.deviceList.indexOf(item)
  if (index != -1) {
    vdata.deviceList.splice(index, 1)
  }
}
// 弹层打开事件
function show(data) {

  vdata.earlyInfo =  data
  vdata.isAdd = !data
  vdata.saveObject = {remindState: '1', amount: '' } // 重置清空
  vdata.deviceList = [];
  vdata.deviceList.push({
    email: '',
    phone: ''
  })
  //更新商户的应用列表
  // 修改弹层
  if (!vdata.isAdd) { // 修改信息 延迟展示弹层
     // remindState.value = data.remindState
    // console.log(remindState.value,'remindState.value')
    vdata.saveObject.remindState = data.remindState
    if(data.remindRuleExt){
      vdata.saveObject.amount = data.remindRuleExt.amount??""
      checkValue.value = data.remindRuleExt.typeList??""
      vdata.deviceList = data.remindRuleExt.receiveList??""
      vdata.saveObject.interval = data.remindRuleExt.interval??""
    }
    vdata.visible = true // 立马展示弹层信息
  } else {
    vdata.visible = true // 立马展示弹层信息
  }
}

// 点击 【保存】按钮的事件
function handleOkFunc(){

  infoFormModel.value.validate().then(() => {

    let typeList = checkValue.value;
    if(!(typeList.indexOf('mail') !== -1)){
      typeList.push('mail')
    }
    let data = {
         'accountNo':vdata.earlyInfo.accountNo,
         'remindState':vdata.saveObject.remindState,
         'ruleExt':{
           'amount':vdata.saveObject.amount,
           'typeList':checkValue.value,
           'interval':vdata.saveObject.interval,
           'receiveList':vdata.deviceList,
         }
    }

    $getPayAccountWarnRule(data).then(res => {
       message.success('设置成功')
      emit('itemRender',1)
    }).catch(err => {
      message.error('设置失败')
    })

  })

}
const emit = defineEmits(['itemRender'])

function onClose() {
  vdata.visible = false
}




defineExpose({show})
</script>
