<script setup lang="ts">

import SystemConfig from "@/constant/SystemConfig.ts";
import {FormatterUtils} from "@/utils/FormatterUtils.ts";
import {onMounted, ref} from "vue";
import type {ITrayConveyLocationSearch} from "@/interface/page/trayConvey/ITrayConveyLocationSearch.ts";
import TrayConveyLocationTypeFormatter from "@/plugin/formatter/TrayConveyLocationTypeFormatter.ts";
import TrueFalseTagStyleFormatter from "@/plugin/formatter/TrueFalseTagStyleFormatter.ts";
import {userStore} from "@/stores/user.ts";
import type {ITrayConveyTableData} from "@/model/table/ITrayConveyTableData.ts";
import TrayConveyLocationApi from "@/api/trayConveyLocation.ts";
import MessageUtils from "@/utils/MessageUtils.ts";
import type {PageDataResponse} from "@/interface/api/PageDataResponse.ts";
import type {AppServeDataResponse} from "@/interface/api/AppServeDataResponse.ts";
import {AppServeResponseCodeEnum} from "@/constant/enums/AppServeResponseCodeEnum.ts";
import AddTrayConveyLocation from "@/components/page/trayConveyLocation/AddTrayConveyLocation.vue";
import TrayConveyLocationDetail from "@/components/page/trayConveyLocation/TrayConveyLocationDetail.vue";
import AppDeveloper from "@/components/manage/AppDeveloper.vue";

const userStoreInstance = userStore();
const locationSearch = ref<ITrayConveyLocationSearch>({}); // 查询的点位查询参数
const trayConveyLocationTypeFormatter = new TrayConveyLocationTypeFormatter(); // 托盘线点位类型格式化
const trueFalseForMatter = new TrueFalseTagStyleFormatter(); // 是否格式化
const pageSize = ref<number>(50); // 分页单页数据
const pageIndex = ref<number>(1); // 分页页码
const totalPages = ref<number | undefined>(1); // 总数据数
const tableData = ref<ITrayConveyTableData[] | undefined>([]); // 表格数据
const showAdd = ref<boolean>(false); // 显示添加弹窗
const showDetail = ref<boolean>(false); // 显示详情弹窗
const detailRow = ref<ITrayConveyTableData>({}); // 传送到详情弹窗的数据

onMounted(() => {
  query();
});

// 查询
const query = () => {
  const loadingInstance = MessageUtils.loading('查询中...');
  TrayConveyLocationApi.query(locationSearch.value, pageSize.value, pageIndex.value).then(res => {
    const responseString = JSON.stringify(res.data);
    const response = JSON.parse(responseString) as AppServeDataResponse<PageDataResponse<ITrayConveyTableData>>;
    if (response && response.code == AppServeResponseCodeEnum.SUCCESS && response.data != undefined) {
      tableData.value = response.data.data;
      totalPages.value = response.data.totalCount;
      MessageUtils.successMessage('查询成功');
      return;
    }
    MessageUtils.errMessage('查询失败' + response.msg);
    return;
  }).catch(() => {}).finally(() => {
    loadingInstance.close();
  })
};
// 重置查询参数
const resetInput = () => {
  locationSearch.value = {};
};
// 添加库位
const addLocations = () => {
  showAdd.value = true;
};
// 导出数据
const downLoadData = () => {
  MessageUtils.confirmMessageBox('确定导出数据？','导出确认').then(() => {
    TrayConveyLocationApi.downloadTrayConveyLocation(locationSearch.value).then(res => {
      const url = window.URL.createObjectURL(new Blob([res.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', '托盘线点位信息下载.xlsx');
      document.body.appendChild(link);
      link.click();
      MessageUtils.successMessage('您的下载将尽快开始，请稍后');
      document.body.removeChild(link);
    }).catch(() => {});
  }).catch(() => {});
};
// 分页数据发生变化时
const paginationChange = () => {
  query();
};
// 查看按钮
const handleEdit = (index: number, row: any) => {
  detailRow.value = {
    id: row.id,
    locationId: row.locationId,
    businessLocationId: row.businessLocationId,
    locationName: row.locationName,
    locationStatus: row.locationStatus,
    locationType: row.locationType,
    plcId: row.plcId,
    locationXyz: row.locationXyz,
    areaId: row.areaId,
    readStatusAddress: row.readStatusAddress,
    writeTaskAddress: row.writeTaskAddress,
    createTime: row.createTime,
    updateTime: row.updateTime,
    remark: row.remark
  };
  showDetail.value = true;
};


</script>

<template>
  <div style="margin-left: 10px;margin-top: 10px; width: calc(100vw - 280px);">
    <h3>托盘线点位管理</h3>
    <el-row class="searchCard">
      <el-row style="width: 100%;">
        <el-form class="searchForm" v-model="locationSearch" label-position="top" label-width="150px" inline>
          <el-form-item label="点位ID：" style="width: 250px;">
            <el-input v-model="locationSearch.locationId" placeholder="要查询的点位ID" clearable></el-input>
          </el-form-item>
          <el-form-item label="业务点位ID：" style="width: 250px;">
            <el-input v-model="locationSearch.businessLocationId" placeholder="要查询的业务点位ID" clearable></el-input>
          </el-form-item>
          <el-form-item label="点位名称：" style="width: 250px;">
            <el-input v-model="locationSearch.locationName" placeholder="要查询的点位名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="点位类型：" style="width: 250px;">
            <el-select v-model="locationSearch.locationType" style="width: 250px" clearable>
              <el-option v-for="item in trayConveyLocationTypeFormatter.locationType" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="点位状态：" style="width: 250px;">
            <el-select v-model="locationSearch.locationStatus" style="width: 250px" clearable>
              <el-option v-for="item in trueFalseForMatter.canUseTagStyle" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="区域号：" style="width: 250px;">
            <el-input v-model="locationSearch.areaId" placeholder="要查询的区域号" clearable></el-input>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row>
        <el-button-group style="width: 100%;margin-left: 10px; margin-bottom: 10px">
          <el-button type="primary" @click="query">查询/刷新</el-button>
          <el-button type="warning" @click="resetInput">重置查询参数</el-button>
          <el-button v-if="userStoreInstance.getUserInfo().userId === SystemConfig.DEVELOPER_ID" type="success" @click="addLocations">添加点位</el-button>
          <app-developer>
            <el-button type="info" @click="downLoadData">导出数据</el-button>
          </app-developer>
        </el-button-group>
      </el-row>
    </el-row>
    <el-row class="dataTable">
      <el-table :data="tableData" stripe border style="width: 100%" max-height="calc(100vh - 400px)">
        <el-table-column type="index" width="80" label="序号" align="center" show-overflow-tooltip fixed="left"/>
        <el-table-column prop="id" label="编号" width="150" align="center" show-overflow-tooltip/>
        <el-table-column prop="locationId" label="点位号" width="150" align="center" show-overflow-tooltip/>
        <el-table-column prop="businessLocationId" label="业务点位号" width="150" align="center" show-overflow-tooltip/>
        <el-table-column prop="locationName" label="点位名称" width="150" align="center" show-overflow-tooltip/>
        <el-table-column prop="locationStatus" label="点位状态" width="150" align="center" show-overflow-tooltip>
          <template #default="scope">
            <el-tag :type="trueFalseForMatter.canUseTagStyleFormatter(scope.row.locationStatus).type">
              {{trueFalseForMatter.canUseTagStyleFormatter(scope.row.locationStatus).label}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="locationType" label="点位类型" width="100" align="center" show-overflow-tooltip>
          <template #default="scope">
            <el-tag :type="trayConveyLocationTypeFormatter.trayConveyLocationTypeFormatter(scope.row.locationType).type">
              {{trayConveyLocationTypeFormatter.trayConveyLocationTypeFormatter(scope.row.locationType).label}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="plcId" label="管辖的PLC ID" width="120" align="center" show-overflow-tooltip/>
        <el-table-column prop="locationXyz" label="点位坐标" width="120" align="center" show-overflow-tooltip />
        <el-table-column prop="areaId" label="所属区域" width="120" align="center" show-overflow-tooltip/>
        <el-table-column prop="readStatusAddress" label="读取状态的地址" width="180" align="center" show-overflow-tooltip />
        <el-table-column prop="writeTaskAddress" label="写入任务的地址" width="180" align="center" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="180" align="center" :formatter="FormatterUtils.formatCellValueTime" show-overflow-tooltip/>
        <el-table-column prop="updateTime" label="上次更新时间" width="180" align="center" :formatter="FormatterUtils.formatCellValueTime" show-overflow-tooltip/>
        <el-table-column prop="remark" label="备注" width="250" align="center" show-overflow-tooltip />
        <el-table-column label="操作" width="80" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination style="margin: 10px"
                     background
                     v-model:current-page="pageIndex"
                     v-model:page-size="pageSize"
                     :page-sizes="[50, 100, 200, 300]"
                     size="small"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="totalPages"
                     @size-change="paginationChange"
                     @current-change="paginationChange"
      />
    </el-row>
  </div>
<!--  添加数据组件-->
  <AddTrayConveyLocation v-model="showAdd" @reLoadingTableData="query"/>
<!--  详细信息组件-->
  <TrayConveyLocationDetail v-model="showDetail" @reLoadingTableData="query" :row-data="detailRow"/>
</template>

<style scoped>
.searchCard {
  width: 100%;
  border: #ccc solid 1px;
  border-radius: 4px;
  background-color: #fff;
}
.dataTable {
  margin: 10px 10px 0 auto;
  width: 100%;
  border: #ccc solid 1px;
  border-radius: 4px;
  background-color: #fff;
}
.searchForm {
  margin: 5px 10px 0 10px;
  width: 100%;
}
.searchForm :deep(.el-form-item__label){
  font-size: 13px;
}
</style>