<template>
  <div class="person-allocate flex flex-col h-full">
    <div v-if="perm.BUTTON_AllocateBatch" class="page-action">
      <t-button
        theme="primary"
        :disabled="!selectedRowKeys.length"
        @click="handleBatchDeploy"
        >批量调配</t-button
      >
    </div>
    <SearchForm :fields="fields" :params="params" :search="mixinSearch">
      <template #service="{ item, params }">
        <select-service-unit
          v-model="params[item.prop]"
          :clearable="true"
        ></select-service-unit>
      </template>
      <template #area>
        <strict-area v-model="areaInfo" @change="areaChange"></strict-area>
      </template>
    </SearchForm>
    <div class="flex-1 page-wrap">
      <p class="page-wrap-tips">
        <t-space :size="0">
          <span>
            <ErrorCircleFilledIcon /> 已发布派单：{{
              statisticsInfo.publishedCrmCount
            }}
            / {{ statisticsInfo.totalCrmCount }}
          </span>
          <span>
            实施工程师配额：{{ statisticsInfo.effectDistributed }} /
            {{ statisticsInfo.effectQuota }}
          </span>
          <span>
            助理工程师配额：{{ statisticsInfo.assistantDistributed }}/
            {{ statisticsInfo.assistantQuota }}
          </span>
          <span>
            区域协调人配额：{{ statisticsInfo.coordinatorDistributed }} /
            {{ statisticsInfo.coordinatorQuota }}
          </span>
          <template #separator>
            <t-divider layout="vertical" />
          </template>
        </t-space>
      </p>

      <t-table
        size="small"
        row-key="crmId"
        :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 #crmno="{ 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 #roles="{ row }">
          {{ rolesFilter(row) }}
        </template>
        <template #crmStatus="{ col, row }">
          {{ crmStatusFilter(row[col.colKey]) }}
        </template>
        <template #publishTime="{ col, row }">
          <span v-if="row.crmStatus === 'PUBLISH'">
            {{ timestampFilter(row[col.colKey]) }}
          </span>
          <span v-else>--</span>
        </template>
        <template #publishUserName="{ col, row }">
          <span v-if="row.crmStatus === 'PUBLISH'">
            {{ row[col.colKey] }}
          </span>
          <span v-else>--</span>
        </template>
        <template #operate="{ row }">
          <div class="table-operations">
            <template v-if="perm.LINK_Allocate">
              <t-link
                :disabled="row.crmStatus !== 'UN_PUBLISH'"
                theme="primary"
                hover="color"
                @click="handleDeploy(row)"
              >
                调配
              </t-link>
            </template>
            <template v-if="perm.LINK_Publish">
              <t-link
                v-if="row.crmStatus === 'UN_PUBLISH'"
                theme="primary"
                hover="color"
                @click="handleSubmitSop(row)"
              >
                发布SOP
              </t-link>
            </template>
            <template v-if="perm.LINK_UnPublish">
              <t-link
                v-if="row.crmStatus === 'PUBLISH'"
                theme="danger"
                hover="color"
                @click="handleCancelSubmitSop(row)"
              >
                撤销发布
              </t-link>
            </template>
          </div>
        </template>
      </t-table>
    </div>

    <!-- PersonDeployDialog -->
    <person-deploy-dialog
      v-if="perm.LINK_Allocate"
      v-model:visible="showPersonDeployDialog"
      :curRow="curRow"
      @success="personDeploySuccess"
    ></person-deploy-dialog>
    <!-- DeployDetailDialog -->
    <deploy-detail-dialog
      v-model:visible="showDeployDetailDialog"
      :curRow="curRow"
    ></deploy-detail-dialog>
  </div>
</template>

<script setup name="PersonAllocate">
import { reactive, ref } from 'vue';
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import { ErrorCircleFilledIcon } from 'tdesign-icons-vue-next';

import useFetchTable from '@/hooks/useFetchTable';
import {
  personAllocateListApi,
  personAllocateStatisticsApi,
  personAllocateBatchDeployApi,
  personAllocateSubmitSopApi,
  personAllocateCancelSubmitSopApi,
} from '@/api/resource-guard';
import {
  crmStatusFilter,
  customerTypeFilter,
  timestampFilter,
} from '@/utils/filter';
import PersonDeployDialog from './person-deploy-dialog.vue';
import DeployDetailDialog from './deploy-detail-dialog.vue';
import usePermission from '@/hooks/usePermission';
const { perm } = usePermission();

const curRow = ref(null);
const showPersonDeployDialog = ref(false);
const showDeployDetailDialog = ref(false);

let areaInfo = ref(['', '', '']);
let statisticsInfo = ref({});
const getStatisticsInfo = async () => {
  const res = await personAllocateStatisticsApi(params);
  statisticsInfo.value = res || {};
};

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

const fields = ref([
  {
    prop: 'serviceUnitId',
    label: '服务单元',
    type: 'select',
    labelWidth: 70,
    colSpan: 6,
    cell: 'service',
  },
  {
    prop: 'province',
    label: '服务区域',
    type: 'select',
    labelWidth: 80,
    colSpan: 7,
    cell: 'area',
  },
  {
    prop: 'customName',
    label: '客户名称',
    labelWidth: 80,
    colSpan: 5,
  },
  {
    prop: 'gap',
    label: '分配差额≤',
    labelWidth: 85,
    colSpan: 4,
    type: 'number',
    attrs: {
      theme: 'column',
      decimalPlaces: 0,
      max: 1000000,
      min: 0,
      style: 'width: 100%',
    },
  },
  {
    type: 'buttons',
    colSpan: 2,
    labelWidth: 0,
    children: [
      {
        type: 'button',
        text: '搜索',
        onClick: () => {
          search();
          getStatisticsInfo();
        },
      },
    ],
  },
]);
const mixinSearch = () => {
  search();
  getStatisticsInfo();
};
const params = reactive({
  serviceUnitId: '',
  province: '',
  city: '',
  area: '',
  customName: '',
  gap: null,
});

const columns = [
  {
    colKey: 'row-select',
    type: 'multiple',
    width: 50,
    fixed: 'left',
    disabled: ({ rowIndex }) => {
      return tableData.value[rowIndex].crmStatus !== 'UN_PUBLISH';
    },
  },
  { colKey: 'serviceUnitName', title: '服务单元', width: 160 },
  { colKey: 'crmNo', title: '项目单号', width: 200, cell: 'crmno' },
  { colKey: 'customName', title: '客户名称', width: 120 },
  { colKey: 'customType', title: '客户类型', cell: 'custom-type', width: 120 },
  { colKey: 'province', title: '省份' },
  { colKey: 'city', title: '城市' },
  { colKey: 'area', title: '区县' },
  { colKey: 'level', title: '服务挡位', width: 100 },
  { colKey: 'roles', title: '项目角色配置', cell: 'roles', width: 200 },
  { colKey: 'quota', title: '配额（人）', width: 120 },
  { colKey: 'distributed', title: '已分配（人）', width: 120 },
  { colKey: 'unDistributed', title: '分配差额（人）', width: 140 },
  { colKey: 'crmStatus', title: 'SOP发布', width: 140 },
  { colKey: 'publishTime', title: '发布时间', width: 170 },
  { colKey: 'publishUserName', title: '发布人', width: 140 },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 160,
  },
];
const { pagination, tableData, fetchData, search, onChange } = useFetchTable(
  personAllocateListApi,
  {
    fetchDataHandle: () => {
      selectedRowKeys.value = [];
      getStatisticsInfo();
    },
    params,
  }
);

const rolesFilter = (row) => {
  // data = {
  //   coordinatorQuota: 1,
  //   effectQuota: 3,
  //   assistantQuota: 3,
  //   coordinatorDistributed: 1,
  //   effectDistributed: 1,
  //   assistantDistributed: 1,
  //   coordinatorUnDistributed: 0,
  //   effectUnDistributed: 2,
  //   assistantUnDistributed: 2,
  // };
  let data = [];
  if (row.coordinatorQuota) {
    data.push(['区域协调人', row.coordinatorQuota, row.coordinatorDistributed]);
  }
  if (row.effectQuota) {
    data.push(['实施工程师', row.effectQuota, row.effectDistributed]);
  }
  if (row.assistantQuota) {
    data.push(['助理工程师', row.assistantQuota, row.assistantDistributed]);
  }
  return data.map((item) => `${item[0]}（${item[2]}/${item[1]}）`).join('，');
};

const personDeploySuccess = () => {
  fetchData();
  getStatisticsInfo();
};

const initData = () => {
  search();
  getStatisticsInfo();
};

const areaChange = (data) => {
  params.province = data[0];
  params.city = data[1];
  params.area = data[2];
};

const handleBatchDeploy = () => {
  if (!selectedRowKeys.value.length) {
    MessagePlugin.error('请选择记录');
    return;
  }
  const confirmDia = DialogPlugin({
    header: '批量调配提示',
    body: `批量调配会对派单中可能已调配人员的结果进行重新调配，您还要继续该操作吗？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await personAllocateBatchDeployApi({
        crmIdList: selectedRowKeys.value,
        serviceUnitId: params.serviceUnitId,
      }).catch(() => {});
      if (!res) return;
      MessagePlugin.success('操作成功');
      fetchData();
    },
  });
};
const handleDeploy = (row) => {
  curRow.value = row;
  showPersonDeployDialog.value = true;
};
const handleSubmitSop = (row) => {
  const confirmDia = DialogPlugin({
    header: '发布SOP提示',
    body: `您确定要发布当前派单的SOP吗？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await personAllocateSubmitSopApi(row.crmNo).catch(() => {});
      if (!res) return;
      MessagePlugin.success('操作成功');
      fetchData();
    },
  });
};
const handleCancelSubmitSop = (row) => {
  const confirmDia = DialogPlugin({
    header: '撤销SOP提示',
    body: `您确定要撤销当前派单的SOP吗？若该SOP已开始填报，则撤销后该SOP填报的所有信息将会全部清空，请谨慎操作！`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await personAllocateCancelSubmitSopApi(row.crmNo).catch(
        () => {}
      );
      if (!res) return;
      MessagePlugin.success('操作成功');
      fetchData();
    },
  });
};

const handleDetail = (row) => {
  curRow.value = row;
  showDeployDetailDialog.value = true;
};
</script>
