<template>
  <page-header-wrapper>
    <a-card>
      <JeepaySearchForm
        :searchConditionNum="6"
        :searchFunc="searchFunc"
        :resetFunc="() => { data.searchData= {} }"
      >
        <a-form-item label="" class="table-search-item">
          <JeepayDateRangePicker
              ref="dateRangePicker"
              v-model:value="data.searchData['queryDateRange']"
              customDateRangeType="dateTime"
          />
        </a-form-item>
        <jeepay-text-up v-model:value="data.searchData['name']" :placeholder="'分账任务ID'" />
        <jeepay-text-up v-model:value="data.searchData['name']" :placeholder="'分账任务名称'" />
        <!-- <jeepay-text-up v-model:value="data.searchData['name']" :placeholder="'任务状态'" /> -->
        <a-form-item label class="table-search-item">
          <a-select v-model:value="data.searchData['userType']" placeholder="任务状态">
            <a-select-option value>全部</a-select-option>
            <a-select-option value="0">待审核</a-select-option>
            <a-select-option value="1">进行中</a-select-option>
            <a-select-option value="2">审核拒绝</a-select-option>
            <a-select-option value="3">已结束</a-select-option>
          </a-select>
        </a-form-item>
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :init-data="true"
        :req-table-data-func="reqTableDataFunc"
        :statisticsIsShow="false"
        :table-columns="tableColumns"
        :search-data="data.searchData"
        row-key="sysUserId"
        @btnLoadClose="data.btnLoading=false"
      >
        <template #statistics>
          <div class="statistics-list">
            <div v-for="(item, index) in vdata.filteredStoreInfoList" :key="index" class="item">
              <div v-if="item.type == 'line'" class="line" />
              <div class="title">{{ item.appName }}</div>
              <div v-if="item.title" class="amount" :style="{color: item.textColor}">
                <span class="amount-num">{{ item.content }}</span>
              </div>
            </div>
          </div>
        </template>
        <template #topBtnSlot>
          <div>
            <a-button
              v-if="$access('ENT_UR_USER_ADD')"
              type="primary"
              class="mg-b-30"
              @click="AddTask(1)"
            >
              <plus-outlined />发布任务
            </a-button>
          </div>
        </template>

        <template #bodyCell="{column,record}">
          <template v-if="column.key == 'ifCode'">
            --
          </template>
          <template v-if="column.key == 'divisionMode'">
            <a-tag
                :key="record.divisionMode"
                :color="record.divisionMode === 0 ?'orange':record.divisionMode === 1?'blue':''"
            >
              {{ record.divisionMode === 0?'按比例分账':record.divisionMode === 1?'按金额分账':'未知' }}
            </a-tag>
          </template>
          <template v-if="column.key == 'divisionType'">


            <a-tag
                :key="record.divisionType"
                :color="record.divisionType === 0 ?'orange':record.divisionType === 1?'orange':record.divisionType === 2?'blue':''"
            >
              {{ record.divisionType === 0?'实时分账':record.divisionType === 1?'延时分账':record.divisionType === 2?'延时分账':'未知' }}
            </a-tag>
          </template>
          <template v-if="column.key == 'isAuto'">

            <a-tag v-if="record.isAuto == 0" color="red">否</a-tag>
            <a-tag v-if="record.isAuto == 1" color="green">是</a-tag>
          </template>

          <template v-if="column.key === 'state'">
            <JeepayTableColState :state="record.state"  :showSwitchType="true"  :onChange="(state) => { return updateState(record.id, state)}" />
          </template>
          <template v-if="column.key == 'op'">
            <!-- 操作列插槽 -->
<!--            <a-button  type="link" style="padding-left: 10px;padding-right: 10px;" @click="fzallocation()">分账设置</a-button>-->
            <a-button  type="link" style="padding-left: 10px;padding-right: 10px;" @click="AddTask(2)">修改</a-button>
            <a-button  type="link" style="color: red" @click="delFunc(record.id)">删除</a-button>
          </template>
        </template>
      </JeepayTable>
    </a-card>

    <SybProductTradeDivideAccountsInfoAddTask ref="showAddTask" :callbackFunc="searchFunc"></SybProductTradeDivideAccountsInfoAddTask>

    <SybProductTradeDivideAccountsInfoSybprotast ref="ledgerGroupAdd" :callbackFunc="searchFunc"></SybProductTradeDivideAccountsInfoSybprotast>
  </page-header-wrapper>
</template>
    <script setup lang="ts">
import {
  API_URL_MCH_APPLYMENT_LIST,
  req,
  reqLoad,
  API_URL_MCH_STORE_LIST,
  API_URL_DIVISIONTASK
} from "@/api/manage";
import { reactive, ref, getCurrentInstance, onMounted } from "vue";
import fileDownload from "js-file-download";
import { message } from "ant-design-vue";
import { useRoute } from "vue-router";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { createVNode, defineComponent } from "vue";
import { Modal } from "ant-design-vue";
import { name } from "store/storages/cookieStorage";
const props = defineProps({
  configMode: { type: String, default: "" } // 模式
});

const {
  $infoBox,
  $access,
  $hasAgentEnt
} = getCurrentInstance()!.appContext.config.globalProperties;
const ledgerGroupAdd = ref();
const showAddTask = ref();
const tableColumns = reactive([
  { key: "taskId", title: "分账任务ID", dataIndex: "taskId" },
  { key: 'name', dataIndex: 'name', title: '任务名称' },
  { key: 'ifName', dataIndex: 'ifName', title: '支付通道' },
  { key: 'divisionMode', dataIndex: 'divisionMode', title: '分账模式' },
  { key: 'divisionType', dataIndex: 'divisionType', title: '分账类型' },
  // { key: 'receiver', dataIndex: 'receiver', title: '分账接收方' },
  // { key: 'divider', dataIndex: 'divider', title: '分账分出方' },
  { key: "isAuto", title: "自动分账组", dataIndex: "isAuto" },
  { key: 'state', title: '任务状态', },
  { key: 'createdAt', dataIndex: 'createdAt', title: '创建时间' },
  { key: 'op', title: '操作', width: '200px', fixed: 'right', align: 'center' }
]);

const infoTable = ref();
const rules = ref();

let data: any = reactive({
  tableColumns: tableColumns,
  searchData: { queryDateRange: "" } as any,
  btnLoading: false
});

let count: any = ref([]); // 数据统计数组
let vdata: any = reactive({
  isshows: false,
  storeList: [] as any,
  mchApplyList: [] as any,
  filteredMchApplyList: [] as any,
  filteredStoreInfoList: [] as any,
  saveObject: {} as any,
  userAddTitle: "",
  visible: false,
  showRechargeModal: false,
  rechargeModalLoading: false, // loading
  rechargeObject: {}, // 预审核结果
  isShow: false, // 发布任务
  showPreRouteModal: false, // 是否显示预审核弹层
  preRouteModalLoading: false, // loading
  preRouteResult: {} // 预审核结果
});

// 请求table接口数据
async function reqTableDataFunc(params) {
  let res =  await req.list(API_URL_DIVISIONTASK, params);
  return res
}

function AddTask(e) {
  let TaskName;
  if (e == 1) {
    TaskName = "新增任务";
  } else {
    TaskName = "修改任务";
  }
  showAddTask.value.show(e);
}

function searchFunc() {
  // 点击【查询】按钮点击事件
  vdata.btnLoading = true; // 打开查询按钮上的loading
  infoTable.value.refTable(true);
}

function addFunc() {
  // 业务通用【新增】 函数
  mchApplyList();
  vdata.showPreRouteModal = true;
}

function colseTask() {
  Modal.confirm({
    title: () => "提示",
    icon: () => createVNode(ExclamationCircleOutlined),
    content: () => "确定关闭任务么",
    onOk() {},
    // eslint-disable-next-line @typescript-eslint/no-empty-function
    onCancel() {}
  });
}

function editFunc(record) {
  // 业务通用【修改】 函数
  vdata.showPreRouteModal = false;
  vdata.userAddTitle = "新建付款账户";
}
function delFunc(recordId) {
  // 业务通用【删除】 函数
  $infoBox.confirmDanger("确认删除？", "", () => {
    return req.delById(API_URL_MCH_APPLYMENT_LIST, recordId).then(res => {
      $infoBox.message.success("删除成功！");
      infoTable.value.refTable(false);
    });
  });
}

function onCopySuccess() {
  $infoBox.message.success("复制成功");
}
// 预审核结果
function rechargeHandleOkFunc() {
  if (!vdata.rechargeResult.state) {
    return $infoBox.message.error("请选择审核结果");
  }

  if (vdata.rechargeResult.state == 8 && !vdata.rechargeResult.applyErrorInfo) {
    return $infoBox.message.error("请填写拒绝原因");
  }

  vdata.rechargeModalLoading = true;
}
function rechargeFunc(record) {
  vdata.showRechargeModal = true;
}
const sybProductTradeRouteStrategyAddOrEdit = ref();
// 分账配置
function fzallocation() {
  ledgerGroupAdd.value.show(true);
  //   vdata.copyInfoSourceApplyId = ""; // 清空副本信息

  //   vdata.showPreRouteModal = true;
  //   vdata.preRouteResult = { applyId: recordId };
}

// 显示弹层
function showPreRouteModalFunc(recordId) {
  vdata.copyInfoSourceApplyId = ""; // 清空副本信息

  vdata.showPreRouteModal = true;
  vdata.preRouteResult = { applyId: recordId };
}
// 预审核结果
function preRouteHandleOkFunc() {
  if (!vdata.preRouteResult.state) {
    return $infoBox.message.error("请选择审核结果");
  }

  if (vdata.preRouteResult.state == 8 && !vdata.preRouteResult.applyErrorInfo) {
    return $infoBox.message.error("请填写拒绝原因");
  }

  vdata.preRouteModalLoading = true;
}

function historyFunc(record) {
  vdata.visible = true;
}
function updateState(recordId, state) {
  // 【更新状态】

  const title = state === 1 ? "确认[启用]？" : "确认[停用]？";
  return new Promise<void>((resolve, reject) => {
    $infoBox.confirmDanger(
      title,
      "",
      () => {
        // return reqLoad.updateById(API_URL_MCH_QR_CODE_LIST, recordId, { qrcState: state }).then(res => {
        //   searchFunc()
        //   resolve()
        // }).catch(err => reject(err))
      },
      () => {
        reject(new Error());
      }
    );
  });
}


function setAqfRouteInfo(e) {
  vdata.showPreRouteModal = false;
}

//门店
function storeList() {
  vdata.saveObject.storeId = "";
  req
    .list(API_URL_MCH_STORE_LIST, {
      pageSize: 100000,
      mchApplyName: vdata.saveObject.mchApplyId
    })
    .then(res => {
      vdata.filteredStoreInfoList = res.records;
      vdata.storeList = res.records;
    });
}

//商户
function mchApplyList() {
  req
    .list(API_URL_MCH_APPLYMENT_LIST, { pageSize: 100000, state: 99 })
    .then(res => {
      vdata.filteredMchApplyList = res.records;
      vdata.mchApplyList = res.records;
    });
}
function onClose() {
  vdata.showPreRouteModal = false;
}
function handleOkFunc() {}

function handleMchApplyChange(e) {
  vdata.saveObject.mchApplyId = e.value;
  storeList();
}

const handleMchApplySearch = value => {
  vdata.filteredMchApplyList = [];
  req
    .list(API_URL_MCH_APPLYMENT_LIST, {
      mchApplyName: value,
      pageSize: 100000,
      state: 99
    })
    .then(res => {
      vdata.filteredMchApplyList = res.records;
      vdata.mchApplyList = res.records;
    });
};
const handleStoreChange = value => {
  vdata.filteredStoreInfoList = [];
  vdata.storeList = [];
  req
    .list(API_URL_MCH_STORE_LIST, {
      storeName: value,
      pageSize: 100000,
      mchApplyName: vdata.saveObject.mchApplyId
    })
    .then(res => {
      vdata.filteredStoreInfoList = res.records;
      vdata.storeList = res.records;
    });
};
</script>

  <style lang="less" >
.bott {
  margin: 50px;
  width: 40%;
  margin-left: 25%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  .botwarn {
    background-color: #e01515;
    border: #e01515;
  }
}

.card-box-div {
  margin: 10px 0 20px 0;
  .div-top-title-tio1 {
    margin: 18px 0 0 20px;

    .div-top-title-tio-span {
      font-weight: 600;
      font-size: 17px;
    }
  }
  .upload {
    margin-left: 30px;
  }
}

.edit-box {
  padding: 20px 30px;
  margin-bottom: 20px;
}
</style>
