<template>
  <div class="unit-manage flex flex-col h-full">
    <div v-if="perm.BUTTON_Add" class="page-action">
      <t-button theme="primary" @click="handleAdd">
        <template #icon><svg-icon name="add-circle" color="#fff" /></template>
        新增服务单元</t-button
      >
    </div>
    <SearchForm :fields="fields" :params="params" :search="search">
      <template #leader="{ item, params }">
        <select-type-user
          v-model="params[item.prop]"
          type="BUSSINESS"
        ></select-type-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,
          current: pagination.pageNumber,
        }"
        v-loading="tableLoading"
      >
        <template #type="{ col, row }">
          {{ customerTypeFilter(row[col.colKey]) }}
        </template>
        <template #status="{ col, row }">
          <status-tag :value="row[col.colKey]" type="serviceUnit"></status-tag>
        </template>
        <template #start-time="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #end-time="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #create-time="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #operate="{ row }">
          <div class="table-operations">
            <template v-if="perm.LINK_Update">
              <t-link
                :disabled="row.status === 'FINISH'"
                theme="primary"
                hover="color"
                @click="handleEdit(row)"
              >
                修改
              </t-link>
            </template>
            <template v-if="perm.LINK_Publish">
              <t-link
                :disabled="row.status !== 'NEW' && row.status !== 'FINISH'"
                theme="primary"
                hover="color"
                @click="handlePublish(row)"
              >
                发布
              </t-link>
            </template>
            <template v-if="perm.LINK_Cancel">
              <t-link
                :disabled="row.status !== 'NEW'"
                theme="primary"
                hover="color"
                @click="handleDestroy(row)"
              >
                作废
              </t-link>
            </template>
            <!-- <template v-if="perm.LINK_Restart">
              <t-link
                :disabled="row.status !== 'FINISH'"
                theme="primary"
                hover="color"
                @click="handleRestart(row)"
              >
                重启
              </t-link>
            </template> -->
            <template v-if="perm.LINK_Close">
              <t-link
                :disabled="row.status !== 'PUBLISH'"
                theme="primary"
                hover="color"
                @click="handleCloze(row)"
              >
                关闭
              </t-link>
            </template>
            <template v-if="perm.LINK_Set">
              <t-link
                :disabled="row.status !== 'NEW'"
                theme="primary"
                hover="color"
                @click="handleSetGroup(row)"
              >
                设置考勤组
              </t-link>
            </template>
          </div>
        </template>
      </t-table>
    </div>

    <AddUnitDialog
      v-if="perm.LINK_Update || perm.BUTTON_Add"
      v-model:visible="showAddUnitDialog"
      :curRow="curRow"
      @success="fetchData"
    ></AddUnitDialog>
  </div>
</template>

<script setup name="UnitManage">
import { ref, reactive, computed } from 'vue';
import { omit } from 'lodash';
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import useFetchTable from '@/hooks/useFetchTable';
import AddUnitDialog from './add-unit-dialog.vue';
import { timestampFilter, customerTypeFilter } from '@/utils/filter';
import { SERVICE_UNIT_STATUS, CUSTOMER_TYPE } from '@/config/constants';
import { dictToOptionList } from '@/utils/tool';
import {
  serviceUnitQueryApi,
  serviceUnitCancelApi,
  serviceUnitClozeApi,
  serviceUnitRestartApi,
  serviceUnitPublishApi,
} from '@/api/service-unit';
import { useRouter } from 'vue-router';
import usePermission from '@/hooks/usePermission';
const { perm } = usePermission();

const showAddUnitDialog = ref(false);
const curRow = ref(null);
const router = useRouter();

const fields = ref([
  {
    prop: 'type',
    label: '业务类型',
    type: 'select',
    labelWidth: 70,
    colSpan: 6,
    options: dictToOptionList(CUSTOMER_TYPE),
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'serviceLeadId',
    label: '负责人',
    type: 'select',
    labelWidth: 70,
    colSpan: 6,
    cell: 'leader',
  },
  {
    prop: 'status',
    label: '当前状态',
    type: 'select',
    labelWidth: 80,
    colSpan: 6,
    options: dictToOptionList(SERVICE_UNIT_STATUS),
    attrs: {
      clearable: true,
    },
  },
  {
    type: 'buttons',
    colSpan: 2,
    children: [
      {
        type: 'button',
        text: '搜索',
        onClick: () => {
          search();
        },
      },
    ],
  },
  {
    prop: 'serviceUnitName',
    label: '服务单元名称',
    labelWidth: 110,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'createTime',
    label: '创建时间',
    type: 'daterange',
    labelWidth: 70,
    colSpan: 12,
    attrs: {
      clearable: true,
      valueType: 'time-stamp',
    },
  },
]);
const params = reactive({
  type: '',
  serviceLeadId: '',
  status: '',
  createTime: [],
  serviceUnitName: '',
});

const computedParams = computed(() => {
  let data = omit(params, ['createTime']);
  data.createStartTime = params.createTime[0];
  data.createEndTime = params.createTime[1];
  return data;
});

const columns = [
  { colKey: 'name', title: '服务单元名称', minWidth: 140 },
  {
    colKey: 'startTime',
    title: '服务开始时间',
    cell: 'start-time',
    width: 180,
  },
  { colKey: 'endTime', title: '服务截止时间', cell: 'end-time', width: 180 },
  { colKey: 'type', title: '业务类型', cell: 'type', width: 120 },
  { colKey: 'serviceLeadName', title: '负责人', minWidth: 120 },
  { colKey: 'rate', title: '区域配比', width: 100 },
  { colKey: 'status', title: '当前状态', cell: 'status', width: 100 },
  { colKey: 'creatorName', title: '创建人', minWidth: 120 },
  { colKey: 'createTime', title: '创建时间', cell: 'create-time', width: 180 },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 320,
    cell: 'operate',
  },
];
const {
  loading: tableLoading,
  pagination,
  tableData,
  search,
  fetchData,
  onChange,
} = useFetchTable(serviceUnitQueryApi, { params: computedParams });

const handleAdd = () => {
  curRow.value = null;
  showAddUnitDialog.value = true;
};
const handleEdit = (row) => {
  curRow.value = row;
  showAddUnitDialog.value = true;
};
const handleDestroy = (row) => {
  const confirmDia = DialogPlugin({
    header: '系统通知',
    body: `是否作废所选服务单元？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    theme: 'warning',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await serviceUnitCancelApi(row.id).catch(() => {});
      if (!res) return;
      MessagePlugin.success('删除成功');
      fetchData();
    },
  });
};
const handlePublish = (row) => {
  const confirmDia = DialogPlugin({
    header: '系统通知',
    body: `是否发布所选服务单元？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    theme: 'success',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await serviceUnitPublishApi(row.id).catch(() => {});
      if (!res) return;
      MessagePlugin.success('发布成功');
      fetchData();
    },
  });
};
const handleRestart = (row) => {
  const confirmDia = DialogPlugin({
    header: '系统通知',
    body: `是否重启所选服务单元？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    theme: 'info',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await serviceUnitRestartApi(row.id).catch(() => {});
      if (!res) return;
      MessagePlugin.success('重启成功');
      fetchData();
    },
  });
};
const handleCloze = (row) => {
  const confirmDia = DialogPlugin({
    header: '系统通知',
    body: `是否关闭所选服务单元？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    theme: 'danger',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await serviceUnitClozeApi(row.id).catch(() => {});
      if (!res) return;
      MessagePlugin.success('关闭成功');
      fetchData();
    },
  });
};
const handleSetGroup = (row) => {
  router.push({
    name: 'CheckinManage',
    query: {
      serviceId: row.id,
    },
  });
};
</script>
