<template>
  <div class="unit-manage flex flex-col h-full">
    <div v-if="perm.BUTTON_Add" class="page-action">
      <t-button theme="primary" @click="handleAddRange">
        <template #icon><svg-icon name="add-circle" color="#fff" /></template>
        新增服务范围
      </t-button>
    </div>
    <SearchForm :fields="fields" :params="params" :search="mixinSearch">
      <template #service-unit="{ item, params }">
        <select-service-unit v-model="params[item.prop]"></select-service-unit>
      </template>
      <template #city="{ item, params }">
        <select-area v-model="params[item.prop]" :level="2"></select-area>
      </template>
    </SearchForm>
    <div class="flex-1 page-wrap">
      <p class="page-wrap-tips">
        <t-space :size="0">
          <span>
            <ErrorCircleFilledIcon /> 共计服务派单：{{
              totalData.totalCrmCount
            }}个
          </span>
          <span>已划定派单：{{ totalData.bindCrmCount }}个</span>
          <span>待划定派单：{{ totalData.unbindCrmCount }}个</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"
      >
        <template #type="{ col, row }">
          {{ customerTypeFilter(row[col.colKey]) }}
        </template>
        <template #operate="{ row }">
          <div class="table-operations">
            <t-link
              v-if="perm.LINK_Delete"
              theme="primary"
              hover="color"
              :disabled="row.serviceUnitStatus === 'FINISH'"
              @click="handleDelete(row)"
            >
              移除
            </t-link>
          </div>
        </template>
      </t-table>
    </div>

    <!-- AddRangeDialog -->
    <add-range-dialog
      v-if="perm.BUTTON_Add"
      v-model:visible="showAddRangeDialog"
      @success="fetchData"
    ></add-range-dialog>
  </div>
</template>

<script setup name="RangeManage">
import { ref, reactive, onMounted } from 'vue';
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import { ErrorCircleFilledIcon } from 'tdesign-icons-vue-next';
import {
  serviceScopeQueryApi,
  serviceScopeUnbindApi,
  serviceScopeSubTotalApi,
} from '@/api/service-unit';
import useFetchTable from '@/hooks/useFetchTable';
import { CUSTOMER_TYPE } from '@/config/constants';
import { dictToOptionList } from '@/utils/tool';
import { customerTypeFilter } from '@/utils/filter';
import AddRangeDialog from './add-range-dialog.vue';
import usePermission from '@/hooks/usePermission';
const { perm } = usePermission();

const showAddRangeDialog = ref(false);

const fields = ref([
  {
    prop: 'serviceUnitId',
    label: '服务单元名称',
    type: 'select',
    labelWidth: 95,
    colSpan: 6,
    cell: 'service-unit',
  },
  {
    prop: 'city',
    label: '区域',
    type: 'select',
    labelWidth: 55,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'productType',
    label: '客户类型',
    type: 'select',
    labelWidth: 80,
    colSpan: 6,
    options: dictToOptionList(CUSTOMER_TYPE),
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'customName',
    label: '客户名称',
    labelWidth: 80,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    type: 'buttons',
    colSpan: 2,
    children: [
      {
        type: 'button',
        text: '搜索',
        attrs: {
          style: { marginLeft: '0 !important' },
        },
        onClick: () => {
          search();
          getTotalData();
        },
      },
    ],
  },
]);
const mixinSearch = () => {
  search();
  getTotalData();
};
const params = reactive({
  serviceUnitId: '',
  city: '',
  productType: '',
  customName: '',
});

const columns = [
  { colKey: 'serviceUnitName', title: '服务单元', minWidth: 120 },
  { colKey: 'crmNo', title: '项目单号', width: 200 },
  { colKey: 'customName', title: '客户名称', minWidth: 120 },
  { colKey: 'productType', title: '客户类型', width: 120, cell: 'type' },
  { colKey: 'province', title: '省份', minWidth: 100 },
  { colKey: 'city', title: '城市', minWidth: 100 },
  { colKey: 'area', title: '区县', minWidth: 100 },
  { colKey: 'level', title: '服务档位', width: 100 },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 100,
    cell: 'operate',
  },
];
const {
  loading: tableLoading,
  pagination,
  tableData,
  search,
  fetchData,
  onChange,
} = useFetchTable(serviceScopeQueryApi, { params }, false);

let totalData = ref({
  totalCrmCount: 0,
  bindCrmCount: 0,
  unbindCrmCount: 0,
});

const getTotalData = async () => {
  const res = await serviceScopeSubTotalApi(params);
  totalData.value = res;
};

const handleAddRange = () => {
  showAddRangeDialog.value = true;
};
const handleDelete = (row) => {
  const confirmDia = DialogPlugin({
    header: '系统通知',
    body: `您确定要将当前派单从派单服务单元中移除吗？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    theme: 'warning',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await serviceScopeUnbindApi(row.crmId).catch(() => {});
      if (!res) return;
      MessagePlugin.success('删除成功');
      fetchData();
    },
  });
};

onMounted(() => {
  search();
  getTotalData();
});
</script>
