<template>
  <div class="unit-manage flex flex-col h-full">
    <div v-if="perm.BUTTON_Add" class="page-action">
      <t-button theme="primary" @click="handleAdd">
        <template #icon><svg-icon name="add-circle" color="#fff" /></template
        >新增大区
      </t-button>

      <t-button
        v-if="perm.LINK_Delete"
        variant="outline"
        :disabled="!selectedRowKeys.length"
        @click="handleBatchDisable"
      >
        <template #icon><svg-icon name="delete" 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]"></select-service-unit>
      </template>
      <template #lead="{ item, params }">
        <select-type-user
          v-model="params[item.prop]"
          type="REGION_MANAGER"
        ></select-type-user>
      </template>
      <template #city="{ item, params }">
        <select-area v-model="params[item.prop]" :level="2"></select-area>
      </template>
    </SearchForm>
    <div class="flex-1 page-wrap">
      <t-table
        size="small"
        row-key="serviceRegionId"
        :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 #operate="{ row }">
          <div class="table-operations">
            <t-link
              v-if="perm.LINK_Update"
              theme="primary"
              hover="color"
              :disabled="row.serviceUnitStatus === 'FINISH'"
              @click="handleEdit(row)"
            >
              修改大区
            </t-link>
            <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>

    <AddRegionDialog
      v-if="perm.BUTTON_Add || perm.LINK_Update"
      v-model:visible="showAddRegionDialog"
      :curRow="curRow"
      @success="fetchData"
    ></AddRegionDialog>
  </div>
</template>

<script setup name="RegionalPlanning">
import { ref, reactive } from 'vue';
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import {
  serviceRegionQueryApi,
  serviceRegionRemoveApi,
} from '@/api/service-unit';
import useFetchTable from '@/hooks/useFetchTable';
import AddRegionDialog from './add-region-dialog.vue';
import usePermission from '@/hooks/usePermission';
const { perm } = usePermission();

const curRow = ref(null);
const showAddRegionDialog = ref(false);
const selectedRowKeys = ref([]);
const selectChange = (value, { selectedRowData }) => {
  selectedRowKeys.value = value;
};
const fields = ref([
  {
    prop: 'serviceUnitId',
    label: '服务单元名称',
    type: 'select',
    labelWidth: 100,
    colSpan: 6,
    cell: 'service',
  },
  {
    prop: 'leadId',
    label: '大区经理',
    type: 'select',
    labelWidth: 80,
    colSpan: 6,
    cell: 'lead',
  },
  {
    prop: 'city',
    label: '区域',
    type: 'select',
    labelWidth: 55,
    colSpan: 6,
    cell: 'city',
  },
  {
    type: 'buttons',
    colSpan: 2,
    children: [
      {
        type: 'button',
        text: '搜索',
        onClick: () => {
          search();
        },
      },
    ],
  },
]);
const params = reactive({
  serviceUnitId: '',
  leadId: '',
  city: '',
});

const columns = [
  {
    colKey: 'row-select',
    type: 'multiple',
    width: 50,
    fixed: 'left',
    disabled: ({ rowIndex }) => {
      return tableData.value[rowIndex].serviceUnitStatus === 'FINISH';
    },
  },
  { colKey: 'serviceUnitName', title: '服务单元', width: 160 },
  { colKey: 'regionName', title: '大区名称', width: 100 },
  { colKey: 'leadName', title: '大区经理', width: 120 },
  { colKey: 'regionInfo', title: '区域划分', minWidth: 200 },
  { colKey: 'orderCount', title: '派单共计', width: 100 },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 150,
    cell: 'operate',
  },
];
const {
  loading: tableLoading,
  pagination,
  tableData,
  search,
  fetchData,
  onChange,
} = useFetchTable(serviceRegionQueryApi, { params });

const handleAdd = () => {
  curRow.value = null;
  showAddRegionDialog.value = true;
};
const handleEdit = (row) => {
  curRow.value = row;
  showAddRegionDialog.value = true;
};
const handleDelete = (row) => {
  const confirmDia = DialogPlugin({
    header: '作废提示',
    body: `您确定要作废当前规划的大区吗？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    theme: 'warning',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await serviceRegionRemoveApi([row.serviceRegionId]).catch(
        () => {}
      );
      if (!res) return;
      MessagePlugin.success('操作成功');
      fetchData();
    },
  });
};

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 serviceRegionRemoveApi(selectedRowKeys.value).catch(
        () => {}
      );
      if (!res) return;
      MessagePlugin.success('操作成功');
      fetchData();
    },
  });
};
</script>
