<template>
  <div class="flex flex-col h-full">
    <div v-if="perm.BUTTON_Cancel" class="page-action">
      <t-button
        theme="primary"
        :disabled="!selectedRowKeys.length"
        @click="handleDestroy"
      >
        <template #icon><svg-icon name="delete" 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: ['PUBLISH', 'FINISH'] }"
        ></select-service-unit>
      </template>
      <template #user="{ item, params }">
        <select-url-user
          v-model="params[item.prop]"
          url="/api/admin/tb/quality/problem/apply/user/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,
          current: pagination.pageNumber,
        }"
        :selected-row-keys="selectedRowKeys"
        @select-change="selectChange"
      >
        <template #problemNo="{ col, row }">
          <more-content
            :content="row[col.colKey]"
            @action="handleDetail(row)"
          ></more-content>
        </template>
        <template #custom-type="{ col, row }">
          {{ customerTypeFilter(row[col.colKey]) }}
        </template>
        <template #flow-status="{ col, row }">
          {{ flowStatusFilter(row[col.colKey]) }}
        </template>
        <template #issues-type="{ col, row }">
          {{ issuesTypeFilter(row[col.colKey]) }}
        </template>
        <template #issues-reason="{ col, row }">
          {{ issuesReasonTypeFilter(row[col.colKey]) }}
        </template>
        <template #submit-time="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #update-time="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #operate="{ row }">
          <div class="table-operations">
            <t-link
              v-if="perm.LINK_Approve"
              theme="primary"
              hover="color"
              :disabled="row.status === 'FINISH' || !row.myself"
              @click="auditQualityIssueHandle(row)"
            >
              审核
            </t-link>
          </div>
        </template>
      </t-table>
    </div>

    <!-- QualityIssueDialog -->
    <quality-issue-dialog
      v-model:visible="showQualityIssueDialog"
      :sop="curSopData"
      :type="curType"
      @confirm="fetchData"
    ></quality-issue-dialog>
  </div>
</template>

<script setup name="IssuesFeedback">
import { computed, reactive, ref } from 'vue';
import { omit } from 'lodash';
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import QualityIssueDialog from '@/views/sop/sop-manage/quality-issue/quality-issue-dialog.vue';

import {
  issuesFeedbackListApi,
  issuesFeedbackDestroyApi,
} from '@/api/project-quality';
import useFetchTable from '@/hooks/useFetchTable';
import { dictToOptionList } from '@/utils/tool';
import {
  timestampFilter,
  customerTypeFilter,
  issuesReasonTypeFilter,
  issuesTypeFilter,
  flowStatusFilter,
} from '@/utils/filter';
import {
  ISSUES_INFLUENCE_DEGREE,
  ISSUES_REASON_TYPE,
  ISSUES_TYPE,
} from '@/config/constants';
import usePermission from '@/hooks/usePermission';
const { perm } = usePermission();

const selectedRowKeys = ref([]);
const selectChange = (value) => {
  selectedRowKeys.value = value;
};
const curSopData = ref({});

const fields = ref([
  {
    prop: 'serviceId',
    label: '服务单元',
    type: 'select',
    labelWidth: 70,
    colSpan: 6,
    cell: 'service',
  },
  {
    prop: 'userId',
    label: '责任人',
    type: 'select',
    labelWidth: 80,
    colSpan: 6,
    cell: 'user',
  },
  {
    prop: 'type',
    label: '问题类型',
    type: 'select',
    labelWidth: 110,
    colSpan: 6,
    options: dictToOptionList(ISSUES_TYPE),
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'reason',
    label: '问题归因',
    type: 'select',
    labelWidth: 80,
    colSpan: 6,
    options: dictToOptionList(ISSUES_REASON_TYPE),
    attrs: {
      clearable: true,
    },
  },
  {
    type: 'buttons',
    colSpan: 3,
    children: [
      {
        type: 'button',
        text: '搜索',
        onClick: () => {
          search();
        },
      },
    ],
  },
  {
    prop: 'degree',
    label: '影响度',
    type: 'select',
    labelWidth: 70,
    colSpan: 6,
    options: ISSUES_INFLUENCE_DEGREE.map((item) => {
      return {
        label: item,
        value: item,
      };
    }),
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'custom',
    label: '客户名称',
    labelWidth: 80,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'problemNo',
    label: '质量问题编号',
    labelWidth: 110,
    colSpan: 12,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'submitTime',
    label: '提交时间',
    type: 'daterange',
    labelWidth: 70,
    colSpan: 12,
    attrs: {
      clearable: true,
      valueType: 'time-stamp',
    },
  },
]);
const params = reactive({
  serviceId: '',
  userId: '',
  type: '',
  reason: '',
  degree: '',
  custom: '',
  problemNo: '',
  submitTime: [],
});
const computedParams = computed(() => {
  let data = omit(params, ['submitTime']);
  data.startTime = params.submitTime[0];
  data.endTime = params.submitTime[1];
  return data;
});

const columns = [
  {
    colKey: 'row-select',
    type: 'multiple',
    width: 50,
    fixed: 'left',
  },
  { colKey: 'problemNo', title: '质量问题编号', width: 200 },
  { colKey: 'crmNo', title: '项目单号', width: 200 },
  { colKey: 'customType', title: '客户类型', cell: 'custom-type', width: 120 },
  { colKey: 'custom', title: '客户名称', width: 140 },
  // { colKey: 'productName', title: '实施产品' },
  { colKey: 'sopTypeStr', title: '实施产品' },
  { colKey: 'summary', title: '问题简要' },
  { colKey: 'userNames', title: '责任人', width: 140 },
  { colKey: 'type', title: '问题类型', cell: 'issues-type', width: 120 },
  { colKey: 'reason', title: '问题归因', cell: 'issues-reason', width: 160 },
  { colKey: 'influenceDegree', title: '影响度', width: 100 },
  { colKey: 'submitter', title: '提交人', width: 140 },
  {
    colKey: 'submissionTime',
    title: '提交时间',
    cell: 'submit-time',
    width: 180,
  },
  {
    colKey: 'updateDateTime',
    title: '更新时间',
    cell: 'update-time',
    width: 180,
  },
  { colKey: 'status', title: '流程状态', cell: 'flow-status', width: 120 },
  { colKey: 'taskName', title: '当前节点', minWidth: 160 },
  { colKey: 'pendApproveUsers', title: '当前负责人', width: 140 },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 100,
  },
];

const { pagination, tableData, fetchData, search, onChange } = useFetchTable(
  issuesFeedbackListApi,
  {
    fetchDataHandle: () => {
      selectedRowKeys.value = [];
    },
    params: computedParams,
  }
);

const handleDestroy = () => {
  if (!selectedRowKeys.value.length) {
    MessagePlugin.error('请选择要作废的记录');
    return;
  }

  const confirmDia = DialogPlugin({
    header: '操作提示',
    body: `确定要作废当前选择的所有记录吗`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await issuesFeedbackDestroyApi(selectedRowKeys.value).catch(
        () => {}
      );
      if (!res) return;
      MessagePlugin.success('操作成功');
      fetchData();
    },
  });
};

const showQualityIssueDialog = ref(false);
const curType = ref('fill');
const auditQualityIssueHandle = (row) => {
  curSopData.value = {
    ...row,
    customManagerTypeStr: row.customTypeStr,
    customName: row.custom,
  };
  curType.value = 'fill';
  showQualityIssueDialog.value = true;
};
const handleDetail = (row) => {
  curSopData.value = {
    ...row,
    customManagerTypeStr: row.customTypeStr,
    customName: row.custom,
  };
  curType.value = 'view';
  showQualityIssueDialog.value = true;
};
</script>
