<template>
  <div class="delay-warning flex flex-col h-full">
    <SearchForm :fields="fields" :params="params" :search="search">
      <template #service="{ item, params }">
        <select-service-unit
          v-model="params[item.prop]"
          clearable
        ></select-service-unit>
      </template>
    </SearchForm>
    <div class="flex-1 page-wrap">
      <t-table
        size="small"
        row-key="id"
        :columns="columns"
        :data="tableData"
        bordered
        :pagination="{
          defaultCurrent: 1,
          defaultPageSize: 10,
          onChange,
          showJumper: true,
          showPageSize: false,
          total: pagination.total,
        }"
        v-loading="tableLoading"
      >
        <template #code="{ col, row }">
          <more-content
            :content="row[col.colKey]"
            @action="handleDetail(row)"
          ></more-content>
        </template>
        <template #type="{ col, row }">
          {{ warnTypeFilter(row[col.colKey]) }}
        </template>
        <template #status="{ col, row }">
          <status-tag :value="row[col.colKey]" type="warnFlow"></status-tag>
        </template>
        <template #warnTime="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #fieldObj="{ col, row }">
          {{ enumFilter(row[col.colKey]) }}
        </template>
        <template #operate="{ row }">
          <div class="table-operations">
            <template v-if="perm.LINK_Follow">
              <t-link
                :disabled="row.status === 'CLOSE'"
                theme="primary"
                hover="color"
                @click="handleFollow(row)"
              >
                跟进
              </t-link>
            </template>
            <template v-if="perm.LINK_Restart">
              <t-link
                v-if="row.status === 'CLOSE'"
                theme="primary"
                hover="color"
                @click="restartHandler(row)"
              >
                重启
              </t-link>
            </template>
            <template v-if="perm.LINK_Close">
              <t-link
                v-if="row.status !== 'CLOSE'"
                theme="primary"
                hover="color"
                @click="closeHandler(row)"
              >
                关闭
              </t-link>
            </template>
          </div>
        </template>
      </t-table>
    </div>

    <!-- DelayWarnFlowDialog -->
    <delay-warn-flow-dialog
      v-if="perm.LINK_Follow"
      v-model:visible="showDelayWarnFlowDialog"
      :curRow="curRow"
      :type="viewType"
      @success="fetchData"
      :enumFilter="enumFilter"
    ></delay-warn-flow-dialog>
  </div>
</template>

<script setup name="DelayWarning">
import { reactive, ref, computed, onMounted } from 'vue';
import { getDelayWarnList, closeDelayWarn, restartDelayWarn } from '@/api/sop';
import { enumListByType } from '@/api/common';
import useFetchTable from '@/hooks/useFetchTable';
import { dictToOptionList } from '@/utils/tool';
import { WARN_TYPE, WARN_FLOW_STATUS } from '@/config/constants';
import { omit } from 'lodash';
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import { warnTypeFilter, timestampFilter } from '@/utils/filter';
import DelayWarnFlowDialog from './flow-dialog';
import usePermission from '@/hooks/usePermission';
const { perm } = usePermission();

const showDelayWarnFlowDialog = ref(false);
const curRow = ref({});
const viewType = ref('');

const enumData = ref({});
const getEnumData = async () => {
  enumData.value = await enumListByType('PROCESS_LIMITED_ENUM');
};

const enumFilter = (type) => {
  return enumData.value[type.toUpperCase()] || '--';
};

const handleFollow = (row) => {
  viewType.value = 'new';
  curRow.value = row;
  showDelayWarnFlowDialog.value = true;
};
const handleDetail = (row) => {
  viewType.value = 'view';
  curRow.value = row;
  showDelayWarnFlowDialog.value = true;
};
const restartHandler = (row) => {
  const confirmDia = DialogPlugin({
    header: '操作提示',
    body: `您确定要重启当前预警信息吗？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await restartDelayWarn(row.id).catch(() => {});
      if (!res) return;
      MessagePlugin.success('操作成功');
      fetchData();
    },
  });
};
const closeHandler = (row) => {
  const confirmDia = DialogPlugin({
    header: '操作提示',
    body: `您确定要关闭当前预警信息吗？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await closeDelayWarn(row.id).catch(() => {});
      if (!res) return;
      MessagePlugin.success('操作成功');
      fetchData();
    },
  });
};
const columns = [
  { colKey: 'service', title: '服务单元', width: 140 },
  { colKey: 'code', title: '预警流水号', width: 200 },
  { colKey: 'warnTime', title: '预警时间', width: 180 },
  { colKey: 'sopNo', title: 'SOP流水号', width: 200 },
  { colKey: 'createName', title: '节点负责人', width: 140 },
  { colKey: 'custom', title: '客户名称', width: 140 },
  { colKey: 'crmNo', title: '项目单号', width: 200 },
  { colKey: 'crmName', title: '项目名称', width: 200 },
  {
    colKey: 'type',
    title: '预警类型',
    width: 150,
  },
  { colKey: 'fieldObj', title: '预警字段', width: 150 },
  {
    colKey: 'status',
    title: '跟进状态',
    width: 100,
  },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 120,
  },
];

const fields = ref([
  {
    prop: 'serviceId',
    label: '服务单元',
    type: 'select',
    labelWidth: 80,
    colSpan: 6,
    cell: 'service',
  },
  {
    prop: 'type',
    label: '预警类型',
    type: 'select',
    labelWidth: 80,
    options: dictToOptionList(WARN_TYPE),
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'status',
    label: '跟进状态',
    type: 'multipleSelect',
    labelWidth: 80,
    options: dictToOptionList(WARN_FLOW_STATUS),
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'custom',
    label: '客户名称',
    labelWidth: 80,
    colSpan: 6,
  },
  {
    type: 'buttons',
    colSpan: 3,
    children: [
      {
        type: 'button',
        text: '搜索',
        onClick: () => {
          search();
        },
      },
    ],
  },
  {
    prop: 'sopNo',
    label: 'SOP流水号',
    labelWidth: 80,
    colSpan: 6,
  },
  {
    prop: 'time',
    label: '预警时间',
    type: 'daterange',
    labelWidth: 80,
    colSpan: 12,
    attrs: {
      clearable: true,
      valueType: 'time-stamp',
    },
  },
  {
    prop: 'fieldObj',
    label: '预警字段',
    labelWidth: 80,
    colSpan: 6,
  },
]);
const params = reactive({
  serviceId: '',
  type: '',
  status: [],
  custom: '',
  sopNo: '',
  time: [],
  fieldObj: '',
});
const transParams = computed(() => {
  return {
    ...omit(params, 'time'),
    startTime: params.time[0],
    endTime: params.time[1],
  };
});

const {
  loading: tableLoading,
  pagination,
  tableData,
  onChange,
  fetchData,
  search,
} = useFetchTable(
  getDelayWarnList,
  {
    params: transParams,
  },
  false
);

const initData = async () => {
  await getEnumData();
  await search();
};

onMounted(() => {
  initData();
});
</script>
