<template>
  <div class="dispatch-manage flex flex-col h-full">
    <div class="page-action">
      <t-button v-if="perm.BUTTON_Add" theme="primary" @click="handleAdd">
        <template #icon><svg-icon name="add-circle" color="#fff" /></template>
        新增</t-button
      >
      <t-button
        v-if="perm.BUTTON_Cancel"
        variant="outline"
        :disabled="!selectedRowKeys.length"
        @click="handleBatchDisable"
      >
        <template #icon><svg-icon name="delete" color="#262626" /></template>
        作废
      </t-button>
      <t-button
        v-if="perm.BUTTON_BatchDelimit"
        variant="outline"
        :disabled="!selectedRowKeys.length"
        @click="handleMultDelineation"
      >
        <template #icon
          ><svg-icon name="batch-delineation" color="#262626" /></template
        >批量划定</t-button
      >
    </div>
    <SearchForm :fields="fields" :params="params" :search="refresh">
      <template #service="{ item, params }">
        <select-service-unit
          v-model="params[item.prop]"
          :hasNoneValue="true"
        ></select-service-unit>
      </template>
      <template #lead="{ item, params }">
        <select-type-user
          v-model="params[item.prop]"
          type="REGION_MANAGER"
        ></select-type-user>
      </template>
      <template #user="{ item, params }">
        <select-type-user
          v-model="params[item.prop]"
          type="ACCOUNT_MANAGER"
        ></select-type-user>
      </template>
    </SearchForm>
    <div class="flex-1 page-wrap">
      <p class="page-wrap-tips">
        <t-space :size="0">
          <span>
            <ErrorCircleFilledIcon /> 待划定派单数量：{{ waitCount }}
          </span>
          <template #separator>
            <t-divider layout="vertical" />
          </template>
        </t-space>
      </p>
      <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"
        :selected-row-keys="selectedRowKeys"
        @select-change="selectChange"
      >
        <template #type="{ col, row }">
          {{ customerTypeFilter(row[col.colKey]) }}
        </template>
        <template #begin-time="{ col, row }">
          {{ timestampFilter(row[col.colKey], 'mm') }}
        </template>
        <template #start-time="{ col, row }">
          {{ timestampFilter(row[col.colKey], 'mm') }}
        </template>
        <template #end-time="{ col, row }">
          {{ timestampFilter(row[col.colKey], 'mm') }}
        </template>
        <template #create-time="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #operate="{ row }">
          <div class="table-operations" @click.stop>
            <template v-if="perm.LINK_Delimit || perm.LINK_ReDelimit">
              <t-link
                :disabled="row.serviceUnitStatus === 'FINISH'"
                theme="primary"
                hover="color"
                @click="handleDelineation(row)"
              >
                {{ row.serviceId ? '重新划定' : '划定' }}
              </t-link>
            </template>
            <template v-if="perm.LINK_Update">
              <t-link
                :disabled="row.serviceUnitStatus === 'FINISH'"
                theme="primary"
                hover="color"
                @click="handleEdit(row)"
              >
                修改
              </t-link>
            </template>
          </div>
        </template>
      </t-table>
    </div>

    <AddDispatchDialog
      v-if="perm.BUTTON_Add || perm.LINK_Update"
      v-model:visible="showAddDispatchDialog"
      :curRow="curRow"
      @success="fetchData"
    ></AddDispatchDialog>
    <!-- DelineationDialog -->
    <mult-delineation-dialog
      v-if="
        perm.LINK_Delimit || perm.LINK_ReDelimit || perm.BUTTON_BatchDelimit
      "
      v-model:visible="showMultDelineationDialog"
      :crm-ids="curCrmIds"
      :custom-type="curCrmCustomType"
      :dialog-title="curRow?.serviceId ? '重新划定服务单元' : undefined"
      @success="refresh"
    >
      <div v-if="curRow">
        <h4>派单信息</h4>
        <t-form class="crm-content" colon label-width="120px">
          <t-row :gutter="[0, 0]">
            <t-col :span="6">
              <t-form-item label="项目单号">
                {{ curRow.crmNo }}
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item label="项目名称">
                {{ curRow.name }}
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item label="派单时间">
                {{ timestampFilter(curRow.beginTime, 'mm') }}
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item label="客户经理">
                {{ curRow.crmUserName }}
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item label="客户类型">
                {{ customerTypeFilter(curRow.customType) }}
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item label="客户名称">
                {{ curRow.custom }}
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item label="考试开始时间">
                {{ timestampFilter(curRow.examStartTime, 'mm') }}
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item label="考试结束时间">
                {{ timestampFilter(curRow.examEndTime, 'mm') }}
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item label="实施产品">
                {{ curRow.product }}
              </t-form-item>
            </t-col>
          </t-row>
        </t-form>
      </div>
    </mult-delineation-dialog>
  </div>
</template>

<script setup name="DispatchManage">
import { reactive, ref, computed, onMounted } from 'vue';
import { omit } from 'lodash';
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import { ErrorCircleFilledIcon, FactCheckIcon } from 'tdesign-icons-vue-next';
import usePermission from '@/hooks/usePermission';
const { perm } = usePermission();

import {
  dispatchQueryApi,
  dispatchBatchDisableApi,
  dispatchCountWaitZoneApi,
} from '@/api/service-unit';
import useFetchTable from '@/hooks/useFetchTable';
import AddDispatchDialog from './add-dispatch-dialog.vue';
import MultDelineationDialog from './mult-delineation-dialog.vue';

import { CUSTOMER_TYPE } from '@/config/constants';
import { dictToOptionList } from '@/utils/tool';
import { timestampFilter, customerTypeFilter } from '@/utils/filter';

const showMultDelineationDialog = ref(false);
const curRow = ref(null);
const curCrmIds = ref([]);
const curCrmCustomType = ref('');
const showAddDispatchDialog = ref(false);
let waitCount = ref(0);

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

const fields = ref([
  {
    prop: 'serviceId',
    label: '服务单元',
    type: 'select',
    labelWidth: 70,
    colSpan: 6,
    cell: 'service',
  },
  {
    prop: 'leadId',
    label: '大区经理',
    type: 'select',
    labelWidth: 80,
    colSpan: 6,
    cell: 'lead',
  },
  {
    prop: 'crmUserId',
    label: '客户经理',
    type: 'select',
    labelWidth: 80,
    colSpan: 6,
    cell: 'user',
  },
  {
    prop: 'type',
    label: '客户类型',
    type: 'select',
    labelWidth: 80,
    colSpan: 6,
    options: dictToOptionList(CUSTOMER_TYPE),
    attrs: {
      clearable: true,
    },
  },
  {
    type: 'buttons',
    colSpan: 3,
    children: [
      {
        type: 'button',
        text: '搜索',
        attrs: {
          style: { marginLeft: '0 !important' },
        },
        onClick: () => {
          refresh();
        },
      },
    ],
  },
  {
    prop: 'custom',
    label: '客户名称',
    labelWidth: 70,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'crmNo',
    label: '项目单号',
    labelWidth: 80,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'beginTime',
    label: '派单时间',
    type: 'daterange',
    labelWidth: 80,
    colSpan: 12,
    attrs: {
      clearable: true,
      valueType: 'time-stamp',
    },
  },
]);
const params = reactive({
  serviceId: '',
  leadId: '',
  crmUserId: '',
  type: '',
  custom: '',
  crmNo: '',
  beginTime: [],
});

const computedParams = computed(() => {
  let data = omit(params, ['beginTime']);
  data.startTime = params.beginTime[0];
  data.endTime = params.beginTime[1];
  data.isBind = true;
  if (data.serviceId == '-1') {
    data.isBind = false;
    data.serviceId = '';
  }
  return data;
});

const columns = [
  {
    colKey: 'row-select',
    type: 'multiple',
    width: 50,
    fixed: 'left',
  },
  { colKey: 'service', title: '服务单元', minWidth: 160 },
  { colKey: 'crmNo', title: '项目单号', minWidth: 160 },
  { colKey: 'beginTime', title: '派单时间', cell: 'begin-time', width: 170 },
  { colKey: 'crmUserName', title: '客户经理', minWidth: 120 },
  { colKey: 'customType', title: '客户类型', cell: 'type', width: 100 },
  { colKey: 'custom', title: '客户名称', minWidth: 120 },
  { colKey: 'name', title: '项目名称', minWidth: 120 },
  { colKey: 'product', title: '实施产品', minWidth: 120 },
  {
    colKey: 'examStartTime',
    title: '考试开始时间',
    cell: 'start-time',
    width: 180,
  },
  {
    colKey: 'examEndTime',
    title: '考试结束时间',
    cell: 'end-time',
    width: 180,
  },
  { colKey: 'leadName', title: '大区经理' },
  { colKey: 'createName', title: '提交人' },
  { colKey: 'createTime', title: '提交时间', cell: 'create-time', width: 170 },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 140,
    cell: 'operate',
  },
];

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

const refresh = () => {
  search();
  getWaitCount();
};

const getWaitCount = async () => {
  const res = await dispatchCountWaitZoneApi({
    ...computedParams.value,
    isBind: false,
  });
  waitCount.value = res || 0;
};

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

  const customType = selectedRows.value[0].customType;
  if (selectedRows.value.some((item) => item.customType !== customType)) {
    MessagePlugin.error('只能操作统一客户类型的数据');
    return;
  }
  curRow.value = null;
  curCrmIds.value = selectedRowKeys.value;
  curCrmCustomType.value = customType;
  showMultDelineationDialog.value = true;
};
const handleDelineation = (row) => {
  if (row.serviceId) {
    const confirmDia = DialogPlugin({
      header: '操作提示',
      body: `重新划定到新的服务单元后，相关大区负责人信息、SOP信息将全部被清空，确定要操作吗？`,
      confirmBtn: '确定',
      cancelBtn: '取消',
      onConfirm: () => {
        confirmDia.hide();
        curRow.value = row;
        curCrmIds.value = [row.id];
        curCrmCustomType.value = row.customType;
        showMultDelineationDialog.value = true;
      },
    });
  } else {
    curRow.value = row;
    curCrmIds.value = [row.id];
    curCrmCustomType.value = row.customType;
    showMultDelineationDialog.value = true;
  }
};

const handleAdd = () => {
  curRow.value = null;
  showAddDispatchDialog.value = true;
};
const handleEdit = (row) => {
  curRow.value = row;
  showAddDispatchDialog.value = true;
};
const handleBatchDisable = () => {
  if (!selectedRowKeys.value.length) {
    MessagePlugin.error('请选择要作废的记录');
    return;
  }
  const confirmDia = DialogPlugin({
    header: '系统通知',
    body: `是否作废所选服务单元？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    theme: 'warning',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await dispatchBatchDisableApi(selectedRowKeys.value).catch(
        () => {}
      );
      if (!res) return;
      MessagePlugin.success('操作成功');
      refresh();
    },
  });
};

onMounted(() => {
  getWaitCount();
});
</script>

<style lang="less" scoped>
.crm-content {
  padding: 16px 16px 16px 0;
  border-radius: 3px;
  border: 1px solid #e5e5e5;
  margin: 8px 0 24px;
}
</style>
