<template>
  <div class="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 #service="{ item, params }">
        <select-service-unit
          v-model="params[item.prop]"
          :filterParams="{ statusList: ['NEW', 'PUBLISH'] }"
        ></select-service-unit>
      </template>
      <template #supplier="{ item, params }">
        <select-supplier
          v-model="params[item.prop]"
          :min-collapsed-num="10"
          :filterable="false"
          multiple
        ></select-supplier>
      </template>
      <template #dingRole="{ item, params }">
        <select-role
          v-model="params[item.prop]"
          :min-collapsed-num="10"
          :filterable="false"
          multiple
        >
        </select-role>
      </template>
      <template #approveRole="{ item, params }">
        <select-role
          v-model="params[item.prop]"
          :min-collapsed-num="10"
          :filterable="false"
          multiple
        >
        </select-role>
      </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 #face-open="{ item, row }">
          {{ row.faceOpen ? '是' : '否' }}
        </template>
        <template #ding-objs="{ row }">
          {{
            row.dingObjs
              .filter((item) => item.type === 'DING')
              .map((item) => item.roleName)
              .join('，')
          }}
        </template>
        <template #approve-objs="{ item, row }">
          {{
            row.dingObjs
              .filter((item) => item.type === 'APPROVE')
              .map((item) => item.roleName)
              .join('，')
          }}
        </template>
        <template #status="{ col, row }">
          <status-tag :value="row[col.colKey]" type="serviceUnit"></status-tag>
        </template>
        <template #create-time="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #operate="{ row }">
          <div class="table-operations">
            <t-link
              v-if="perm.LINK_Update"
              theme="primary"
              hover="color"
              @click="handleEdit(row)"
            >
              修改
            </t-link>
            <t-link
              v-if="perm.LINK_Delete"
              theme="primary"
              hover="color"
              :disabled="row.status !== 'NEW'"
              @click="handleDelete(row)"
            >
              删除
            </t-link>
          </div>
        </template>
      </t-table>
    </div>

    <edit-checkin-dialog
      v-if="perm.LINK_Update || perm.BUTTON_Add"
      v-model:visible="showEditCheckinDialog"
      :curRow="curRow"
      @success="fetchData"
    ></edit-checkin-dialog>
  </div>
</template>

<script setup name="CheckinManage">
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute } from 'vue-router';
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import useFetchTable from '@/hooks/useFetchTable';
import EditCheckinDialog from './edit-checkin-dialog.vue';
import { checkinQueryApi, checkinDeleteApi } from '@/api/system';
import { timestampFilter } from '@/utils/filter';
import { SERVICE_UNIT_STATUS } from '@/config/constants';
import { dictToOptionList } from '@/utils/tool';
import { omit } from 'lodash';
import usePermission from '@/hooks/usePermission';
const { perm } = usePermission();

const showEditCheckinDialog = ref(false);
const curRow = ref(null);

const route = useRoute();

const fields = ref([
  {
    prop: 'serviceId',
    label: '服务单元名称',
    type: 'select',
    labelWidth: 95,
    colSpan: 5,
    cell: 'service',
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'status',
    label: '发布状态',
    type: 'select',
    labelWidth: 110,
    colSpan: 5,
    options: dictToOptionList(SERVICE_UNIT_STATUS),
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'supplierIds',
    label: '适用供应商',
    type: 'select',
    labelWidth: 95,
    colSpan: 6,
    cell: 'supplier',
  },
  {
    prop: 'dingRoleIds',
    label: '适用考勤对象',
    type: 'select',
    labelWidth: 110,
    colSpan: 6,
    cell: 'dingRole',
  },
  {
    type: 'buttons',
    colSpan: 2,
    children: [
      {
        type: 'button',
        text: '搜索',
        onClick: () => {
          search();
        },
      },
    ],
  },
  {
    prop: 'approveRoleIds',
    label: '审核角色',
    type: 'select',
    labelWidth: 95,
    colSpan: 5,
    cell: 'approveRole',
  },
  {
    prop: 'faceOpen',
    label: '是否开启人脸',
    type: 'select',
    labelWidth: 110,
    colSpan: 5,
    options: [
      {
        label: '是',
        value: 1,
      },
      {
        label: '否',
        value: 0,
      },
    ],
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'createTime',
    label: '创建时间',
    type: 'daterange',
    labelWidth: 95,
    colSpan: 12,
    attrs: {
      clearable: true,
      valueType: 'time-stamp',
    },
  },
]);
const params = reactive({
  serviceId: '',
  status: '',
  supplierIds: '',
  dingRoleIds: '',
  approveRoleIds: '',
  faceOpen: null,
  createTime: [],
});

const columns = [
  { colKey: 'service', title: '服务单元', minWidth: 140 },
  { colKey: 'status', title: '服务单元发布状态', width: 100 },
  { colKey: 'name', title: '考勤组名称', minWidth: 140 },
  {
    colKey: 'dingObjs',
    title: '适用考勤对象',
    cell: 'ding-objs',
    minWidth: 200,
  },
  { colKey: 'supplier', title: '适用供应商', minWidth: 200 },
  { colKey: 'signInTime', title: '签到时段', width: 160 },
  { colKey: 'signOutTime', title: '签退时段', width: 160 },
  {
    colKey: 'auditRoles',
    title: '审核角色',
    cell: 'approve-objs',
    minWidth: 200,
  },
  { colKey: 'faceOpen', title: '是否开启人脸', cell: 'face-open', width: 120 },
  { colKey: 'reissueCardCount', title: '允许补卡次数', width: 120 },
  { colKey: 'createName', title: '创建人', with: 140 },
  { colKey: 'createTime', title: '创建时间', cell: 'create-time', width: 180 },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 120,
  },
];

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

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

const handleAdd = () => {
  curRow.value = null;
  showEditCheckinDialog.value = true;
};
const handleEdit = (row) => {
  curRow.value = row;
  showEditCheckinDialog.value = true;
};
const handleDelete = (row) => {
  const confirmDia = DialogPlugin({
    header: '操作提示',
    body: `确定要删除当前记录吗`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    theme: 'warning',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await checkinDeleteApi(row.id).catch(() => {});
      if (!res) return;
      MessagePlugin.success('删除成功');
      fetchData();
    },
  });
};

onMounted(() => {
  params.serviceId = route.query.serviceId || '';
  search();
});
</script>
