<template>
  <div class="office-sop flex flex-col h-full">
    <div class="page-action">
      <t-button
        v-if="perm.BUTTON_Cancel"
        theme="primary"
        :disabled="!selectedRowKeys.length"
        @click="handleBatchCancel"
      >
        <template #icon><svg-icon name="delete" color="#fff" /></template>
        作废
      </t-button>
      <select-metadata
        v-model="params.formWidgetMetadataViewList"
        type="OFFICE_SOP_FLOW"
        :originColumns="originColumns"
        @change="metadataChange"
      ></select-metadata>
      <t-button variant="outline" @click="handleRefresh">
        <template #icon><svg-icon name="refresh" color="#262626" /></template>
        刷新</t-button
      >
      <!-- <t-button variant="outline" @click="handleSort">
        <template #icon><svg-icon name="sort" color="#262626" /></template>
        排序</t-button
      > -->
      <sop-sort-panel
        :metadata="formWidgetMetadataViewList"
        @confirm="sortConfirm"
      ></sop-sort-panel>
      <t-button
        v-if="appStore.showSubmenu"
        variant="outline"
        @click="toggleSubMenuHandle"
      >
        <template #icon><svg-icon name="enlarge" color="#262626" /></template>
        放大</t-button
      >
      <t-button v-else variant="outline" @click="toggleSubMenuHandle">
        <template #icon><svg-icon name="shrink" color="#262626" /></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'],
            type: 'OFFICE',
          }"
        ></select-service-unit>
      </template>
      <template #buttons>
        <t-space :size="16">
          <select-filter
            :metadata="formWidgetMetadataViewList"
            @confirm="filterConfirm"
          ></select-filter>
          <t-button theme="primary" @click="search">搜索</t-button>
        </t-space>
      </template>
    </SearchForm>

    <div class="flex-1 page-wrap">
      <t-table
        size="small"
        row-key="flowId"
        :columns="columns"
        :data="tableData"
        bordered
        :pagination="{
          defaultCurrent: 1,
          defaultPageSize: 10,
          onChange,
          showJumper: true,
          showPageSize: false,
          total: pagination.total,
          current: pagination.pageNumber,
        }"
        v-loading="tableLoading"
        :selected-row-keys="selectedRowKeys"
        @select-change="selectChange"
      >
        <!-- <template #sopNo="{ col, row }">
          <more-content
            :content="row[col.colKey]"
            @action="editSopFlowHandle(row, 'view')"
          ></more-content>
        </template> -->
        <!-- <template #beginTime="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #examStartTime="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #examEndTime="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #flowCreateTime="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #flowUpdateTime="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template> -->
        <template
          v-for="field in formWidgetMetadataViewList"
          #[field.fieldId]="{ col, row }"
        >
          <more-content
            v-if="col.colKey === 'sopNo'"
            :content="row[col.colKey]"
            @action="editSopFlowHandle(row, 'view')"
          ></more-content>
          <span v-else-if="col.colKey === 'status'">{{ row.statusStr }}</span>
          <span v-else-if="col.colKey === 'customManagerType'">{{
            row.customManagerTypeStr
          }}</span>
          <metadata-content
            v-else
            :value="row[col.colKey]"
            :config="{
              code: col.colKeyCode,
              fieldId: col.colKey,
              options: col.colOptions,
            }"
          ></metadata-content>
        </template>

        <template #operate="{ row }">
          <div class="table-operations">
            <template v-if="perm.LINK_Fill">
              <t-link
                :disabled="
                  !row.myself || row.status === 'END' || row.status === 'FINISH'
                "
                theme="primary"
                hover="color"
                @click="editSopFlowHandle(row, 'fill')"
              >
                填报
              </t-link>
            </template>
            <template v-if="perm.LINK_AddSop">
              <t-link
                theme="primary"
                hover="color"
                @click="editSopFlowHandle(row, 'new')"
              >
                新增SOP
              </t-link>
            </template>
            <template v-if="perm.LINK_AddViolation">
              <t-link
                theme="primary"
                hover="color"
                @click="createViolationHandle(row)"
              >
                新增违规
              </t-link>
            </template>
            <template v-if="perm.LINK_ProblemSubmit">
              <t-link
                theme="primary"
                hover="color"
                @click="createQualityIssueHandle(row)"
              >
                上报质量问题
              </t-link>
            </template>
            <template v-if="perm.LINK_ProjectExchange">
              <t-link
                :disabled="row.status === 'END' || row.status === 'FINISH'"
                theme="primary"
                hover="color"
                @click="planChangeHandle(row)"
              >
                计划变更报备
              </t-link>
            </template>
            <template v-if="perm.LINK_Edit">
              <t-link
                theme="primary"
                hover="color"
                @click="editSopFlowHandle(row, 'edit')"
              >
                编辑
              </t-link>
            </template>
          </div>
        </template>
      </t-table>
    </div>

    <!-- SopStepDialog -->
    <sop-step-dialog
      v-if="perm.LINK_Edit || perm.LINK_AddSop || perm.LINK_Fill"
      v-model:visible="showSopStepDialog"
      :sop="curSopData"
      :type="curSopType"
      @confirm="fetchData"
    ></sop-step-dialog>
    <!-- QualityIssueDialog -->
    <quality-issue-dialog
      v-if="perm.LINK_ProblemSubmit"
      v-model:visible="showQualityIssueDialog"
      :sop="curSopData"
      type="new"
      @confirm="fetchData"
    ></quality-issue-dialog>
    <!-- PlanChangeDialog -->
    <plan-change-dialog
      v-if="perm.LINK_ProjectExchange"
      v-model:visible="showPlanChangeDialog"
      :sop="curSopData"
      type="new"
      @confirm="fetchData"
    ></plan-change-dialog>
    <!-- AddViolationDialog -->
    <add-violation-dialog
      v-if="perm.LINK_AddViolation"
      v-model:visible="showAddViolationDialog"
      :sop="curSopData"
    ></add-violation-dialog>
  </div>
</template>

<script setup name="OfficeSop">
import { ref, reactive, computed } from 'vue';
import useFetchTable from '@/hooks/useFetchTable';
import { sopListApi, sopBatchCancelApi } from '@/api/sop';
import { timestampFilter } from '@/utils/filter';
import SelectFilter from '../../components/select-filter/index.vue';
import SopSortPanel from '../../components/sop-sort-panel/index.vue';
import SelectMetadata from '../../components/select-metadata.vue';
import SopStepDialog from '../sop-step/sop-step-dialog.vue';
import QualityIssueDialog from '../quality-issue/quality-issue-dialog.vue';
import PlanChangeDialog from '../plan-change/plan-change-dialog.vue';
import AddViolationDialog from '../../sop-monitor/violation-registration/add-violation-dialog.vue';
import MetadataContent from '../../components/metadata-content.vue';
import { useAppStore } from '@/store';
import usePermission from '@/hooks/usePermission';
import { cloneDeep } from 'lodash';
import { CUSTOMER_TYPE, FLOW_STATUS } from '@/config/constants';
import { dictToOptionList } from '@/utils/tool';
const { perm } = usePermission();

const appStore = useAppStore();

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

const originColumns = [
  { fieldId: 'serviceName', fieldTitle: '服务单元', width: 160, code: 'TEXT' },
  { fieldId: 'sopNo', fieldTitle: 'SOP流水号', width: 200, code: 'TEXT' },
  { fieldId: 'crmNo', fieldTitle: '项目单号', width: 200, code: 'TEXT' },
  { fieldId: 'beginTime', fieldTitle: '派单时间', width: 180, code: 'DATE' },
  {
    fieldId: 'customManagerName',
    fieldTitle: '客户经理',
    width: 140,
    code: 'TEXT',
  },
  {
    fieldId: 'customManagerType',
    fieldTitle: '客户类型',
    width: 120,
    code: 'SINGLE_SELECT',
    options: dictToOptionList(CUSTOMER_TYPE),
  },
  { fieldId: 'customName', fieldTitle: '客户名称', width: 140, code: 'TEXT' },
  { fieldId: 'crmName', fieldTitle: '项目名称', minWidth: 160, code: 'TEXT' },
  { fieldId: 'productName', fieldTitle: '实施产品', width: 120, code: 'TEXT' },
  {
    fieldId: 'examStartTime',
    fieldTitle: '考试开始时间',
    width: 180,
    code: 'DATE',
  },
  {
    fieldId: 'examEndTime',
    fieldTitle: '考试结束时间',
    width: 180,
    code: 'DATE',
  },
  { fieldId: 'flowCreateName', fieldTitle: '提交人', width: 140, code: 'TEXT' },
  {
    fieldId: 'flowCreateTime',
    fieldTitle: '提交时间',
    width: 180,
    code: 'DATE',
  },
  {
    fieldId: 'flowUpdateTime',
    fieldTitle: '更新时间',
    width: 180,
    code: 'DATE',
  },
  {
    fieldId: 'status',
    fieldTitle: '流程状态',
    width: 120,
    code: 'SINGLE_SELECT',
    options: [
      { value: 'AUDITING', label: '进行中' },
      { value: 'FINISH', label: '已完结' },
    ],
  },
  { fieldId: 'taskName', fieldTitle: '流程节点', width: 160, code: 'TEXT' },
  {
    fieldId: 'pendApproveName',
    fieldTitle: '当前节点负责人',
    width: 140,
    code: 'SINGLE_SELECT',
  },
];
const originFieldIds = originColumns.map((item) => item.fieldId);
const columns = computed(() => {
  const defaultColumns = [
    {
      colKey: 'row-select',
      type: 'multiple',
      width: 50,
      fixed: 'left',
    },
    // { colKey: 'serviceName', title: '服务单元', width: 160 },
    // { colKey: 'sopNo', title: 'SOP流水号', width: 200 },
    // { colKey: 'crmNo', title: '项目单号', width: 200 },
    // { colKey: 'beginTime', title: '派单时间', width: 180 },
    // { colKey: 'customManagerName', title: '客户经理', width: 140 },
    // { colKey: 'customManagerTypeStr', title: '客户类型', width: 120 },
    // { colKey: 'customName', title: '客户名称', width: 140 },
    // { colKey: 'crmName', title: '项目名称', minWidth: 160 },
    // { colKey: 'productName', title: '实施产品', width: 120 },
    // { colKey: 'examStartTime', title: '考试开始时间', width: 180 },
    // { colKey: 'examEndTime', title: '考试结束时间', width: 180 },
    // { colKey: 'flowCreateName', title: '提交人', width: 140 },
    // { colKey: 'flowCreateTime', title: '提交时间', width: 180 },
    // { colKey: 'flowUpdateTime', title: '更新时间', width: 180 },
    // { colKey: 'statusStr', title: '流程状态', width: 120 },
    // { colKey: 'taskName', title: '流程节点', width: 160 },
    // { colKey: 'pendApproveName', title: '当前节点负责人', width: 140 },
    {
      title: '管理',
      colKey: 'operate',
      fixed: 'right',
      width: 450,
    },
  ];

  if (formWidgetMetadataViewList.value.length) {
    let metadataColumns = formWidgetMetadataViewList.value.map((item) => {
      return {
        colKey: item.fieldId,
        title: item.fieldTitle,
        colOptions: item.options,
        colKeyCode: item.code,
        width: item.width,
        minWidth: item.minWidth || 170,
      };
    });
    return [
      ...defaultColumns.slice(0, -1),
      ...metadataColumns,
      ...defaultColumns.slice(-1),
    ];
  } else {
    return defaultColumns;
  }
});

const fields = ref([
  {
    prop: 'serviceId',
    label: '服务单元',
    type: 'select',
    labelWidth: 70,
    colSpan: 6,
    cell: 'service',
  },
  {
    prop: 'buttons',
    colSpan: 4,
    labelWidth: 16,
  },
]);
const params = reactive({
  serviceId: '',
  formWidgetMetadataViewList: cloneDeep(originColumns),
  formWidgetMetadataConditionList: [],
  formWidgetMetadataOrderList: [],
  formWidgetMetadataOperation: 'AND',
});
const transParams = computed(() => {
  let formWidgetMetadataViewList = params.formWidgetMetadataViewList.filter(
    (item) => !originFieldIds.includes(item.fieldId)
  );
  return { ...params, formWidgetMetadataViewList, type: 'OFFICE_SOP_FLOW' };
});
const {
  loading: tableLoading,
  pagination,
  tableData,
  search,
  fetchData,
  onChange,
} = useFetchTable(sopListApi, {
  params: transParams,
  fetchDataHandle: () => {
    selectedRowKeys.value = [];
  },
});

const formWidgetMetadataViewList = ref(cloneDeep(originColumns));
const metadataChange = (vals) => {
  formWidgetMetadataViewList.value = vals;
  search();
};

const filterConfirm = (data, formWidgetMetadataOperation) => {
  params.formWidgetMetadataConditionList = data.map((item) => {
    return {
      fieldId: item.fieldId,
      operator: item.operator,
      fieldValue: Array.isArray(item.fieldValue)
        ? JSON.stringify(item.fieldValue)
        : item.fieldValue,
    };
  });
  params.formWidgetMetadataOperation = formWidgetMetadataOperation;
};
const sortConfirm = (data) => {
  params.formWidgetMetadataOrderList = data;
};

const handleSort = () => {
  // TODO:
};
const handleRefresh = () => {
  search();
};

const toggleSubMenuHandle = () => {
  appStore.toggleSubMenu();
};

const handleBatchCancel = () => {
  if (!selectedRowKeys.value.length) {
    MessagePlugin.error('请选择要作废的记录');
    return;
  }
  const confirmDia = DialogPlugin({
    header: '系统通知',
    body: `是否作废所选sop？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    theme: 'warning',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await sopBatchCancelApi(selectedRowKeys.value).catch(
        () => {}
      );
      if (!res) return;
      MessagePlugin.success('操作成功');
      // refresh();
      search();
    },
  });
};

const curSopData = ref({});

const showAddViolationDialog = ref(false);
const createViolationHandle = (row) => {
  curSopData.value = row;
  showAddViolationDialog.value = true;
};

const showSopStepDialog = ref(false);
const curSopType = ref('');
const editSopFlowHandle = (row, type = 'fill') => {
  curSopType.value = type;

  if (type === 'new') {
    curSopData.value = {
      ...row,
      flowDeploymentId:
        appStore.getFlowDetailByType('OFFICE_SOP_FLOW')?.flowDeploymentId,
    };
  } else {
    curSopData.value = row;
  }
  showSopStepDialog.value = true;
};

const showPlanChangeDialog = ref(false);
const planChangeHandle = (row) => {
  curSopData.value = {
    ...row,
    flowDeploymentId: appStore.getFlowDetailByType('PROJECT_EXCHANGE_FLOW')
      ?.flowDeploymentId,
  };
  showPlanChangeDialog.value = true;
};

const showQualityIssueDialog = ref(false);
const createQualityIssueHandle = (row) => {
  curSopData.value = {
    ...row,
    flowDeploymentId: appStore.getFlowDetailByType('QUALITY_PROBLEM_FLOW')
      ?.flowDeploymentId,
  };
  showQualityIssueDialog.value = true;
};
</script>
