<!--
  * 容器信息
  *
  * @Author:    霍锦
  * @Date:      2024-11-26 11:37:48
  * @Copyright  友仓
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="容器" class="smart-query-form-item">
        <StockSelect v-model:value="queryForm.stockId" :disabled-flag="true" @change="changeStockSelect"/>
      </a-form-item>
      <a-form-item label="库位" class="smart-query-form-item">
        <LocationSelect v-model:value="queryForm.locationId" :disabledFlag="true" @change="changeLocationSelect"/>
      </a-form-item>
      <a-form-item label="状态" class="smart-query-form-item">
        <SmartEnumSelect style="width: 200px" enum-name="USAGE_STATUS_ENUM" v-model:value="queryForm.status"/>
      </a-form-item>
      <a-form-item label="是否启用" class="smart-query-form-item">
        <a-select style="width: 200px" v-model:value="queryForm.disabledFlag" allowClear placeholder="请选择">
          <a-select-option :value="true">启用</a-select-option>
          <a-select-option :value="false">禁用</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="onSearch" class="smart-margin-left10">
          <template #icon>
            <SearchOutlined/>
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery" class="smart-margin-left10">
          <template #icon>
            <ReloadOutlined/>
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="showForm" type="primary" v-privilege="'stock:add'">
          <template #icon>
            <PlusOutlined/>
          </template>
          新建
        </a-button>
        <a-button @click="confirmBatchDelete" type="primary" danger v-privilege="'stock:batchDelete'"
                  :disabled="selectedRowKeyList.length == 0">
          <template #icon>
            <DeleteOutlined/>
          </template>
          批量删除
        </a-button>
        <a-button @click="showImportModal" type="primary" v-privilege="'stock:importStocks'">
          <template #icon>
            <ImportOutlined/>
          </template>
          导入
        </a-button>

        <a-button @click="onExportStocks" type="primary" v-privilege="'stock:exportStocks'">
          <template #icon>
            <ExportOutlined/>
          </template>
          导出
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.BASE.STOCK" :refresh="queryData"/>
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->
    <a-table
        size="small"
        :dataSource="tableData"
        :columns="columns"
        rowKey="stockId"
        bordered
        :loading="tableLoading"
        :pagination="false"
        :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
    >
      <template #bodyCell="{ text, record, column }">

        <template v-if="column.dataIndex === 'stockType'">
          <DictPreview :options="stockType.STOCK_TYPE" :value="text"/>
        </template>

        <template v-if="column.dataIndex === 'status'">
          <a-tag :color="text==='FREE' ? 'success' : 'error'">
            {{ $smartEnumPlugin.getDescByValue('USAGE_STATUS_ENUM', text) }}
          </a-tag>
        </template>

        <template v-if="column.dataIndex === 'disabledFlag'">
          <a-tag :color="text ? 'processing' : 'error'">{{ text ? '启用' : '禁用' }}</a-tag>
        </template>

        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button @click="showForm(record)" type="link" v-privilege="'stock:update'">
              <template #icon>
                <EditOutlined/>
              </template>
              编辑
            </a-button>
            <a-button @click="onDelete(record)" danger type="link" v-privilege="'stock:delete'">
              <template #icon>
                <DeleteOutlined/>
              </template>
              删除
            </a-button>
          </div>
        </template>
      </template>
    </a-table>
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
          showSizeChanger
          showQuickJumper
          show-less-items
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :defaultPageSize="queryForm.pageSize"
          v-model:current="queryForm.pageNum"
          v-model:pageSize="queryForm.pageSize"
          :total="total"
          @change="queryData"
          @showSizeChange="queryData"
          :show-total="(total:number) => `共${total}条`"
      />
    </div>

    <!--    新建/编辑-->
    <StockForm ref="formRef" @reloadList="queryData"/>

    <!--    导入-->
    <a-modal v-model:open="importModalShowFlag" title="导入" footer>
      <div style="text-align: center; width: 400px; margin: 0 auto">
        <a-button @click="downloadExcel">
          <download-outlined/>
          第一步：下载模板
        </a-button>
        <br/>
        <br/>
        <a-upload
            v-model:fileList="fileList"
            name="file"
            :multiple="false"
            action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
            accept=".xls,.xlsx"
            :before-upload="beforeUpload"
            @remove="handleRemove"
        >
          <a-button>
            <upload-outlined/>
            第二步：选择文件
          </a-button>
        </a-upload>

        <br/>
        <a-button @click="onImportStocks">
          <ImportOutlined/>
          第三步：开始导入
        </a-button>
      </div>
    </a-modal>

  </a-card>
</template>
<script setup lang="ts">
import {reactive, ref, onMounted} from 'vue';
import {message, Modal} from 'ant-design-vue';
import {SmartLoading} from '/@/components/framework/smart-loading';
import {stockApi} from '/@/api/business/base/stock/stock-api';
import {PAGE_SIZE_OPTIONS} from '/@/constants/common-const';
import {smartSentry} from '/@/lib/smart-sentry';
import TableOperator from '/@/components/support/table-operator/index.vue';
import StockForm from '/@/views/business/base/stock/stock-form.vue';
import {TABLE_ID_CONST} from "/@/constants/support/table-id-const";
import DictPreview from '/@/components/dict-preview/index.vue';
import {useDict} from "/@/utils/dict";
import {UploadFile} from 'ant-design-vue';
import {fileApi} from "/@/api/support/file-api";
import StockSelect from "/@/views/business/base/stock/stock-select.vue";
import SmartEnumSelect from "/@/components/framework/smart-enum-select/index.vue";
import LocationSelect from "/@/views/business/base/location/location-select.vue";


//容器类型
const stockType = useDict('STOCK_TYPE');
// ---------------------------- 表格列 ----------------------------

const columns = ref([
  {
    title: '容器id',
    dataIndex: 'stockId',
    ellipsis: true,
  },
  {
    title: '容器编码',
    dataIndex: 'stockCode',
    ellipsis: true,
  },
  {
    title: '容器类型',
    dataIndex: 'stockType',
    ellipsis: true,
  },
  {
    title: '库位',
    dataIndex: 'locationCode',
    ellipsis: true,
  },
  {
    title: '状态',
    dataIndex: 'status',
    ellipsis: true,
  },
  {
    title: '启用状态',
    dataIndex: 'disabledFlag',
    ellipsis: true,
  },

  {
    title: '创建时间',
    dataIndex: 'createTime',
    ellipsis: true,
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 140,
  },
]);

// ---------------------------- 查询数据表单和方法 ----------------------------

const queryFormState = {
  stockId: undefined, //容器
  locationId: undefined,//库位
  disabledFlag: undefined,//是否启用
  status: undefined,//状态
  pageNum: 1,
  pageSize: 10,
};
// 查询表单form
const queryForm = reactive({...queryFormState});
// 表格加载loading
const tableLoading = ref(false);
// 表格数据
const tableData = ref([]);
// 总数
const total = ref(0);

// 重置查询条件
function resetQuery() {
  let pageSize = queryForm.pageSize;
  Object.assign(queryForm, queryFormState);
  queryForm.pageSize = pageSize;
  queryData();
}

// 搜索
function onSearch() {
  queryForm.pageNum = 1;
  queryData();
}

//选择容器
function changeStockSelect(selectValue: any) {
  if (selectValue) {
    queryForm.stockId = selectValue.stockId;
  }
}

//选择库位
function changeLocationSelect(selectValue: any) {
  if (selectValue) {
    queryForm.locationId = selectValue.locationId;
  }
}

// 查询数据
async function queryData() {
  tableLoading.value = true;
  try {
    let queryResult = await stockApi.queryPage(queryForm);
    tableData.value = queryResult.data.list;
    total.value = queryResult.data.total;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}


onMounted(queryData);

// ---------------------------- 添加/修改 ----------------------------
const formRef = ref();

function showForm(data: object) {
  formRef.value.show(data);
}

// ---------------------------- 单个删除 ----------------------------
//确认删除
function onDelete(data: object) {
  Modal.confirm({
    title: '提示',
    content: '确定要删除选吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      requestDelete(data);
    },
    cancelText: '取消',
    onCancel() {
    },
  });
}

//请求删除
async function requestDelete(data: any) {
  SmartLoading.show();
  try {
    await stockApi.delete(data.stockId);
    message.success('删除成功');
    await queryData();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}

// ---------------------------- 批量删除 ----------------------------

// 选择表格行
const selectedRowKeyList = ref([]);

function onSelectChange(selectedRowKeys: any) {
  selectedRowKeyList.value = selectedRowKeys;
}

// 批量删除
function confirmBatchDelete() {
  Modal.confirm({
    title: '提示',
    content: '确定要批量删除这些数据吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      requestBatchDelete();
    },
    cancelText: '取消',
    onCancel() {
    },
  });
}

//请求批量删除
async function requestBatchDelete() {
  try {
    SmartLoading.show();
    await stockApi.batchDelete(selectedRowKeyList.value);
    message.success('删除成功');
    await queryData();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}

// ------------------------------- 导出和导入 ---------------------------------
// 导入弹窗
const importModalShowFlag = ref(false);

const fileList = ref<UploadFile[]>([])

// 显示导入
function showImportModal() {
  fileList.value = [];
  importModalShowFlag.value = true;
}

//下载模板
async function downloadExcel() {
  try {
    //默认库位模板fileKey
    let fileKey = 'public/common/d7ece9dda26b4b4b81fe3f7f88f7a707_20250319174104.xlsx';
    fileApi.downLoadFile(fileKey);
  } catch (e) {
    smartSentry.captureError(e);
  }
}

// 移除文件
function handleRemove(file: UploadFile) {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
}

// 上传文件
function beforeUpload(file: UploadFile) {
  fileList.value = [...(fileList.value || []), file];

  return false;
}


//导入
async function onImportStocks() {
  if (fileList.value.length === 0) {
    return message.error('请选择文件');
  }
  const formData = new FormData();
  fileList.value.forEach((file: UploadFile) => {
    formData.append('file', file.originFileObj!);
  });

  SmartLoading.show();
  try {
    const response = await stockApi.importStocks(formData);
    const {success} = JSON.parse(response.msg);
    message.success(success);
    importModalShowFlag.value = false;
    await queryData();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}

//导出
function onExportStocks() {
  stockApi.exportStocks();
}
</script>
