<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-button
          v-if="perm.BUTTON_Cancel"
          variant="outline"
          :disabled="!selectedRowKeys.length"
          @click="handleDestroy"
        >
          <template #icon><svg-icon name="delete" color="#262626" /></template>
          批量作废
        </t-button>
        <t-button
          v-if="perm.BUTTON_BatchEnable"
          variant="outline"
          :disabled="!selectedRowKeys.length"
          @click="handleEnable(selectedRowKeys, true)"
        >
          <template #icon><svg-icon name="enable" color="#262626" /></template>
          批量启用
        </t-button>
        <t-button
          v-if="perm.BUTTON_BatchUnEnable"
          variant="outline"
          :disabled="!selectedRowKeys.length"
          @click="handleEnable(selectedRowKeys, false)"
        >
          <template #icon><svg-icon name="disable" color="#262626" /></template>
          批量禁用
        </t-button>
        <t-popup v-if="perm.BUTTON_BatchImport" trigger="hover">
          <template #content>
            <t-button
              variant="outline"
              @click="downloadImportTemplate('TEMPLATE_DEVICE')"
            >
              <template #icon
                ><svg-icon name="export" color="#262626" /></template
              >下载模板
            </t-button>
          </template>
          <upload-button upload-url="/api/sys/device/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 #supplier="{ item, params }">
        <select-supplier
          v-model="params[item.prop]"
          type="DEVICE"
        ></select-supplier>
      </template>
      <template #brand="{ item, params }">
        <t-select
          v-model="params[item.prop]"
          :options="brandList"
          clearable
          @change="brandChange"
        />
      </template>
      <template #model="{ item, params }">
        <t-select
          v-model="params[item.prop]"
          :options="brandModelList"
          clearable
        />
      </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"
        :selected-row-keys="selectedRowKeys"
        @select-change="selectChange"
      >
        <template #enable="{ col, row }">
          <status-tag :value="row[col.colKey]" type="enable"></status-tag>
        </template>
        <template #buy-time="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #status="{ col, row }">
          {{ runningStatusFilter(row[col.colKey]) }}
        </template>
        <template #bound="{ col, row }">
          {{ inoutTypeFilter(row[col.colKey]) }}
        </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_Enable"
              theme="primary"
              hover="color"
              @click="handleEnable([row.id], !row.enable)"
            >
              {{ row.enable ? '禁用' : '启用' }}
            </t-link>
          </div>
        </template>
      </t-table>
    </div>

    <edit-device-dialog
      v-if="perm.LINK_Update || perm.BUTTON_Add"
      v-model:visible="showEditDeviceDialog"
      :curRow="curRow"
      :brand-list="brandList"
      @success="fetchData"
    ></edit-device-dialog>
  </div>
</template>

<script setup name="DeviceManage">
import { ref, reactive, onMounted, computed } from 'vue';
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import useFetchTable from '@/hooks/useFetchTable';
import EditDeviceDialog from './edit-device-dialog.vue';
import {
  deviceQueryApi,
  deviceDestroyApi,
  deviceEnableApi,
  deviceBrandListApi,
} from '@/api/system';
import {
  runningStatusFilter,
  timestampFilter,
  inoutTypeFilter,
} from '@/utils/filter';
import { dictToOptionList } from '@/utils/tool';
import { ABLE_TYPE, RUNNING_STATUS, INOUT_TYPE } from '@/config/constants';
import usePermission from '@/hooks/usePermission';
import { omit } from 'lodash';
import { downloadImportTemplate } from '@/api/common';
const { perm } = usePermission();

const showEditDeviceDialog = ref(false);
const curRow = ref(null);
const selectedRowKeys = ref([]);
const brandList = ref([]);
const brandModelList = ref([]);

const getBrandList = async () => {
  const res = await deviceBrandListApi().catch(() => {});
  if (!res) return;
  brandList.value = res.map((item) => {
    return {
      label: item.brand,
      value: item.brand,
      list: item.list.map((elem) => {
        return {
          label: elem.model,
          value: elem.model,
        };
      }),
    };
  });
};
const brandChange = () => {
  params.model = '';
  brandModelList.value = [];
  getBrandModelList(params.brand);
};

const getBrandModelList = (brand) => {
  const curBrand = brandList.value.find((item) => item.value === brand);
  if (!curBrand) {
    brandModelList.value = [];
    return;
  }
  brandModelList.value = curBrand.list;
};

const fields = ref([
  {
    prop: 'supplierId',
    label: '设备供应商',
    type: 'select',
    labelWidth: 80,
    colSpan: 6,
    cell: 'supplier',
  },
  {
    prop: 'brand',
    label: '品牌',
    type: 'select',
    labelWidth: 90,
    colSpan: 6,
  },
  {
    prop: 'model',
    label: '型号',
    type: 'select',
    labelWidth: 90,
    colSpan: 6,
  },
  {
    prop: 'deviceCode',
    label: '设备编号',
    labelWidth: 80,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'serialNo',
    label: '设备序列号',
    labelWidth: 80,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    type: 'buttons',
    colSpan: 2,
    children: [
      {
        type: 'button',
        text: '搜索',
        attrs: {
          style: { marginLeft: '0 !important' },
        },
        onClick: () => {
          search();
        },
      },
    ],
  },
  {
    prop: 'status',
    label: '运行状态',
    type: 'select',
    labelWidth: 80,
    colSpan: 6,
    options: dictToOptionList(RUNNING_STATUS),
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'bound',
    label: '出库/入库',
    type: 'select',
    labelWidth: 90,
    colSpan: 6,
    options: dictToOptionList(INOUT_TYPE),
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'enable',
    label: '启用/禁用',
    type: 'select',
    labelWidth: 90,
    colSpan: 6,
    options: dictToOptionList(ABLE_TYPE),
    attrs: {
      clearable: true,
    },
  },
]);
const params = reactive({
  supplierId: '',
  brand: '',
  model: '',
  deviceCode: '',
  serialNo: '',
  status: '',
  bound: '',
  enable: '',
});

const columns = [
  { colKey: 'row-select', type: 'multiple', width: 50 },
  { colKey: 'deviceCode', title: '设备编号', width: 200 },
  { colKey: 'serialNo', title: '序列号', width: 200 },
  { colKey: 'brand', title: '品牌', width: 200 },
  { colKey: 'model', title: '型号', width: 200 },
  { colKey: 'buyTime', title: '购买时间', cell: 'buy-time', width: 180 },
  { colKey: 'supplier', title: '设备供应商', width: 140 },
  { colKey: 'status', title: '运行状态', cell: 'status', width: 120 },
  { colKey: 'location', title: '当前所在地', width: 140 },
  { colKey: 'scanCount', title: '总扫描量', width: 100 },
  { colKey: 'bound', title: '出库/入库', width: 120 },
  { colKey: 'enable', title: '启用/禁用', width: 120 },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 120,
  },
];
const selectChange = (value) => {
  selectedRowKeys.value = value;
};
const {
  loading: tableLoading,
  pagination,
  tableData,
  fetchData,
  search,
  onChange,
} = useFetchTable(deviceQueryApi, {
  params: params,
  fetchDataHandle: () => {
    selectedRowKeys.value = [];
  },
});

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

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

  const confirmDia = DialogPlugin({
    header: '系统通知',
    body: `是否作废该设备？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await deviceDestroyApi(selectedRowKeys.value).catch(() => {});
      if (!res) return;
      MessagePlugin.success('删除成功');
      fetchData();
    },
  });
};
const handleEnable = (selectedIds, enable) => {
  const name = enable ? '启用' : '禁用';

  if (!selectedIds.length) {
    MessagePlugin.error(`请选择要${name}的记录`);
    return;
  }

  const confirmDia = DialogPlugin({
    header: `${name}提示`,
    body: `是否${name}该设备？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await deviceEnableApi(selectedIds, enable).catch(() => {});
      if (!res) return;
      MessagePlugin.success('操作成功');
      fetchData();
    },
  });
};

const handleEdit = (row) => {
  curRow.value = row;
  showEditDeviceDialog.value = true;
};

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