<template>
  <div class="violation-registration 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>
      <template #user="{ item, params }">
        <!--        <select-filter-user-->
        <!--          v-model="params[item.prop]"-->
        <!--          clearable-->
        <!--        ></select-filter-user>-->
        <select-url-user
          v-model="params[item.prop]"
          url="/api/admin/tb/violation/user/list"
          clearable
        ></select-url-user>
      </template>
      <template #creator="{ item, params }">
        <!--        <select-filter-user-->
        <!--          v-model="params[item.prop]"-->
        <!--          clearable-->
        <!--        ></select-filter-user>-->
        <select-url-user
          v-model="params[item.prop]"
          url="/api/admin/tb/violation/creator/list"
          clearable
        ></select-url-user>
      </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 }">
          {{ violationTypeFilter(row[col.colKey]) }}
        </template>
        <template #status="{ col, row }">
          <status-tag
            :value="row[col.colKey]"
            type="violationFlow"
          ></status-tag>
        </template>
        <template #createTime="{ col, row }">
          {{ timestampFilter(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>

    <!-- FlowDialog -->
    <violation-flow-dialog
      v-if="perm.LINK_Follow"
      v-model:visible="showViolationFlowDialog"
      :curRow="curRow"
      :type="viewType"
      @confirm="fetchData"
    ></violation-flow-dialog>
  </div>
</template>

<script setup name="ViolationRegistration">
import { reactive, ref, computed } from 'vue';
import { getViolationList, closeViolation, restartViolation } from '@/api/sop';

import useFetchTable from '@/hooks/useFetchTable';
import { dictToOptionList } from '@/utils/tool';
import { VIOLATION_TYPE, VIOLATION_FLOW_STATUS } from '@/config/constants';
import { omit } from 'lodash';
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import { violationTypeFilter, timestampFilter } from '@/utils/filter';
import ViolationFlowDialog from './flow-dialog.vue';
import usePermission from '@/hooks/usePermission';
const { perm } = usePermission();

const showViolationFlowDialog = ref(false);
const curRow = ref({});
const viewType = ref('');
const handleDetail = (row) => {
  viewType.value = 'view';
  curRow.value = row;
  showViolationFlowDialog.value = true;
};
const handleFollow = (row) => {
  viewType.value = 'new';
  curRow.value = row;
  showViolationFlowDialog.value = true;
};
const restartHandler = (row) => {
  const confirmDia = DialogPlugin({
    header: '操作提示',
    body: `您确定要重启当前预警信息吗？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await restartViolation(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 closeViolation(row.id).catch(() => {});
      if (!res) return;
      MessagePlugin.success('操作成功');
      fetchData();
    },
  });
};

const columns = [
  { colKey: 'service', title: '服务单元', width: 140 },
  { colKey: 'code', title: '违规流水号', width: 200 },
  { colKey: 'sopNo', title: 'SOP流水号', width: 200 },
  { colKey: 'userName', title: '节点负责人', width: 140 },
  { colKey: 'custom', title: '客户名称', width: 140 },
  { colKey: 'crmNo', title: '项目单号', width: 200 },
  { colKey: 'crmName', title: '项目名称', width: 200 },
  {
    colKey: 'type',
    title: '违规类型',
    width: 130,
  },
  { colKey: 'content', title: '违规情况', ellipsis: true, width: 200 },
  {
    colKey: 'status',
    title: '跟进状态',
    width: 100,
  },
  { colKey: 'createTime', title: '登记时间', width: 180 },
  { colKey: 'createName', title: '登记人', width: 140 },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 120,
  },
];

const fields = ref([
  {
    prop: 'serviceId',
    label: '服务单元',
    type: 'select',
    labelWidth: 70,
    colSpan: 6,
    cell: 'service',
  },
  {
    prop: 'type',
    label: '违规类型',
    type: 'select',
    labelWidth: 95,
    options: dictToOptionList(VIOLATION_TYPE),
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'status',
    label: '跟进状态',
    type: 'select',
    labelWidth: 80,
    options: dictToOptionList(VIOLATION_FLOW_STATUS),
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'userId',
    label: '节点负责人',
    type: 'select',
    labelWidth: 90,
    colSpan: 6,
    cell: 'user',
  },
  {
    type: 'buttons',
    colSpan: 3,
    children: [
      {
        type: 'button',
        text: '搜索',
        onClick: () => {
          search();
        },
      },
    ],
  },
  {
    prop: 'custom',
    label: '客户名称',
    labelWidth: 70,
    colSpan: 6,
  },
  {
    prop: 'sopNo',
    label: 'SOP流水号',
    labelWidth: 95,
    colSpan: 6,
  },
  {
    prop: 'createId',
    label: '登记人',
    labelWidth: 80,
    colSpan: 6,
    cell: 'creator',
  },
  {
    prop: 'time',
    label: '登记时间',
    type: 'daterange',
    labelWidth: 70,
    colSpan: 12,
    attrs: {
      clearable: true,
      valueType: 'time-stamp',
    },
  },
]);
const params = reactive({
  serviceId: '',
  type: '',
  status: '',
  userId: '',
  custom: '',
  sopNo: '',
  createId: '',
  time: [],
});
const transParams = computed(() => {
  return {
    ...omit(params, 'time'),
    startTime: params.time[0],
    endTime: params.time[1],
  };
});
const {
  loading: tableLoading,
  pagination,
  tableData,
  onChange,
  fetchData,
  search,
} = useFetchTable(getViolationList, {
  params: transParams,
});
</script>
