<template>
  <div class="flex flex-col h-full">
    <div class="page-action">
      <t-space size="small">
        <t-button v-if="perm.BUTTON_Add" theme="primary" @click="handleAdd">
          <template #icon><svg-icon name="add-circle" color="#fff" /></template
          >新增客户
        </t-button>
        <t-popup v-if="perm.BUTTON_BatchImport" trigger="hover">
          <template #content>
            <t-button
              variant="outline"
              @click="downloadImportTemplate('TEMPLATE_CUSTOM')"
            >
              <template #icon
                ><svg-icon name="export" color="#262626" /></template
              >下载模板
            </t-button>
          </template>
          <upload-button upload-url="/api/sys/custom/import" :format="['xlsx']">
            <t-button variant="outline">
              <template #icon
                ><svg-icon name="import" color="#262626" /></template
              >批量导入
            </t-button>
          </upload-button>
        </t-popup>
      </t-space>
    </div>
    <SearchForm :fields="fields" :params="params" :search="search">
      <template #manager="{ item, params }">
        <select-type-user v-model="params[item.prop]" type="ACCOUNT_MANAGER">
        </select-type-user>
      </template>
      <template #level="{ item, params }">
        <select-service-level v-model="params[item.prop]">
        </select-service-level>
      </template>
    </SearchForm>
    <div class="flex-1 page-wrap">
      <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 #create-time="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #role-list="{ col, row }">
          <p v-for="(item, index) in row[col.colKey]" :key="index"
            >{{ item.roleName }}({{ item.quota }})</p
          >
        </template>
        <template #operate="{ row }">
          <div class="table-operations">
            <t-link
              v-if="perm.LINK_Update"
              theme="primary"
              hover="color"
              @click="handleEdit(row)"
            >
              修改
            </t-link>
            <t-link
              v-if="perm.LINK_Delete"
              theme="primary"
              hover="color"
              @click="handleDelete(row)"
            >
              删除
            </t-link>
          </div>
        </template>
      </t-table>
    </div>

    <edit-customer-dialog
      v-if="perm.LINK_Update || perm.BUTTON_Add"
      v-model:visible="showEditCustomerDialog"
      :curRow="curRow"
      @success="fetchData"
    ></edit-customer-dialog>
  </div>
</template>

<script setup name="CustomerManage">
import { ref, reactive } from 'vue';
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import useFetchTable from '@/hooks/useFetchTable';
import EditCustomerDialog from './edit-customer-dialog.vue';
import { customerQueryApi, customerDeleteApi } from '@/api/system';
import { CUSTOMER_TYPE } from '@/config/constants';
import { dictToOptionList } from '@/utils/tool';
import { customerTypeFilter, timestampFilter } from '@/utils/filter';
import usePermission from '@/hooks/usePermission';
import { downloadImportTemplate } from '@/api/common';
const { perm } = usePermission();

const showEditCustomerDialog = ref(false);
const curRow = ref(null);

const fields = ref([
  {
    prop: 'type',
    label: '客户类型',
    type: 'select',
    labelWidth: 70,
    colSpan: 5,
    options: dictToOptionList(CUSTOMER_TYPE),
  },
  // {
  //   prop: 'managerId',
  //   cell: 'manager',
  //   label: '客户经理',
  //   type: 'select',
  //   labelWidth: 80,
  //   colSpan: 5,
  // },
  {
    prop: 'name',
    label: '客户名称',
    labelWidth: 80,
    colSpan: 5,
    attrs: {
      placeholder: '消息名称模糊查询',
      clearable: true,
    },
  },
  {
    prop: 'levelId',
    cell: 'level',
    label: '服务档位',
    type: 'select',
    labelWidth: 80,
    colSpan: 5,
  },
  {
    type: 'buttons',
    colSpan: 2,
    children: [
      {
        type: 'button',
        text: '搜索',
        onClick: () => {
          search();
        },
      },
    ],
  },
]);
const params = reactive({
  type: '',
  // managerId: '',
  name: '',
  levelId: '',
});

const columns = [
  // { colKey: 'id', title: '客户ID', width: 200 },
  { colKey: 'code', title: '客户ID', width: 200 },
  { colKey: 'name', title: '客户名称', width: 120 },
  // { colKey: 'code', title: '客户编号', width: 100 },
  { colKey: 'type', title: '客户类型', cell: 'type', width: 120 },
  { colKey: 'province', title: '省份', width: 100 },
  { colKey: 'city', title: '城市', width: 100 },
  { colKey: 'area', title: '县区', width: 100 },
  { colKey: 'address', title: '地址', minWidth: 160 },
  // { colKey: 'managerName', title: '客户经理', width: 120 },
  { colKey: 'level', title: '服务档位名称', width: 120 },
  {
    colKey: 'roleList',
    title: '项目角色配置',
    cell: 'role-list',
    width: 140,
  },
  { colKey: 'peoperDay', title: '标准人天', width: 100 },
  { colKey: 'createName', title: '创建人', width: 120 },
  { colKey: 'createTime', title: '创建时间', width: 180, cell: 'create-time' },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 120,
  },
];
const {
  loading: tableLoading,
  pagination,
  tableData,
  fetchData,
  search,
  onChange,
} = useFetchTable(customerQueryApi, { params });

const handleAdd = () => {
  curRow.value = null;
  showEditCustomerDialog.value = true;
};

const handleDelete = (row) => {
  const confirmDia = DialogPlugin({
    header: '操作提示',
    body: `是否删除该客户？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    theme: 'warning',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await customerDeleteApi(row.id).catch(() => {});
      if (!res) return;
      MessagePlugin.success('删除成功');
      fetchData();
    },
  });
};
const handleEdit = (row) => {
  curRow.value = row;
  showEditCustomerDialog.value = true;
};
</script>
