<template>
  <div class="app-container" ref="appPanel">
    <div ref="toolPanel">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
          >导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
          >搜索</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              icon="el-icon-refresh"
              size="mini"
              @click="resetQuery"
          >刷新</el-button>
        </el-col>
          <el-col :span="1.5" style="margin-top: -20px;">
            <div>
              <h3 style="color: #0e0e0e">入库总价: <span class="larger-font">{{ totalMoney }}元</span></h3>
            </div>
          </el-col>
          <el-col :span="1.5" style="margin-top: -20px; ">
            <div>
              <h3 style="color: #0e0e0e">入库数量: <span class="larger-font">{{ acceNum }}件</span></h3>
            </div>
          </el-col>

        <!-- <right-toolbar v-if="rightToolbarShow" :showSearch.sync="showSearch" @queryTable="getList" showColumnsType="transfer" :columns="columns" :businessCode="businessCodeTrk" :tableNo="tableNo" ></right-toolbar> -->
        <right-toolbar ref="toolBarRef" @customCols="customColsHandler" :showSearch.sync="showSearch"
        showColumnsType="transfer" :columns="columns"></right-toolbar>
      </el-row>
    </div>
    <div class="search-container" ref="searchPanel">
      <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="发货单号" prop="purchaseId">
          <el-input
            v-model="queryParams.purchaseId"
            placeholder="请输入发货单号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="物料编号" prop="goodsId">
          <el-input
              v-model="queryParams.goodsId"
              placeholder="请输入物料编号"
              clearable
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="物料名称" prop="goodsName">
          <el-input
              v-model="queryParams.goodsName"
              placeholder="请输入物料名称"
              clearable
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="操作人" prop="createBy">
          <el-input
              v-model="queryParams.createBy"
              placeholder="请输入操作人"
              clearable
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="规格型号" prop="specification">
          <el-input
              v-model="queryParams.specification"
              placeholder="请输入规格型号"
              clearable
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="物料描述" prop="recoil">
          <el-input
              v-model="queryParams.recoil"
              placeholder="请输入物料描述"
              clearable
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="库级" prop="levelType">
          <el-select v-model="queryParams.levelType" placeholder="请选择库级" clearable>
            <el-option
                v-for="dict in dict.type.level_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称" prop="storageId">
          <el-select
            v-model="queryParams.storageId"
            placeholder="请选择仓库名称"
            clearable
          >
            <el-option
              v-for="storage in storageList"
              :key="storage.storageId"
              :label="storage.storageShortName"
              :value="storage.storageId">
            </el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="库位" prop="storageLocation">-->
<!--          <el-input-->
<!--            v-model="queryParams.storageLocation"-->
<!--            placeholder="请输入库位"-->
<!--            clearable-->
<!--            @keyup.enter.native="handleQuery"-->
<!--          />-->
<!--        </el-form-item>-->

        <el-form-item label="子需求号" prop="salesOrderNumber">
          <el-input
            v-model="queryParams.salesOrderNumber"
            placeholder="请输入子需求号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="需求部门" prop="needDept">
          <el-select
            v-model="queryParams.needDept"
            placeholder="请选择需求部门"
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="item in filteredOptions"
              :key="item.deptName"
              :label="item.deptName"
              :value="item.deptName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="需求人" prop="needPerson">
          <el-input
            v-model="queryParams.needPerson"
            placeholder="请输入需求人"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="供货供应商" prop="providerName">
          <el-input
            v-model="queryParams.providerName"
            placeholder="请输入供货供应商"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="用途" prop="useType">
          <el-input
            v-model="queryParams.useType"
            placeholder="请输入用途"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>


        <el-form-item label="签收人" prop="recPerson">
          <el-input
            v-model="queryParams.recPerson"
            placeholder="请输入签收人"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input
            v-model="queryParams.brand"
            placeholder="请输入品牌"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>


<!--        <el-form-item label="物料分类" prop="goodsTypeId">-->
<!--          <el-input-->
<!--            v-model="queryParams.goodsTypeId"-->
<!--            placeholder="请输入物料分类"-->
<!--            clearable-->
<!--            @keyup.enter.native="handleQuery"-->
<!--          />-->
<!--        </el-form-item>-->

        <el-form-item label="发票抬头" prop="invoiceTitle">
          <el-input
            v-model="queryParams.invoiceTitle"
            placeholder="请输入发票抬头"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="容器号" prop="ctl">
          <el-input
            v-model="queryParams.ctl"
            placeholder="请输入容器号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="单据日期" prop="date">
          <div class="block">
            <el-date-picker
              v-model="queryParams.date"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @keyup.enter.native="handleQuery"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </div>
        </el-form-item>
      </el-form>
    </div>
<!--    <div>-->
<!--      <h3 style="color: red">库存总价: {{ totalMoney }}元</h3>-->
<!--      <h3 style="color: red">总计数量: {{ acceNum }}件</h3>-->
<!--    </div>-->

    <div   ref="cardPanel">
      <el-card class="mb-4" :body-style="{ padding: '5px' }">
        <el-radio-group v-model="warehouseType" @change="handleWarehouseTypeChange">
          <el-radio-button label="null">总体</el-radio-button>
          <el-radio-button label="robot">智能库</el-radio-button>
          <el-radio-button label="normal">普通仓库</el-radio-button>
        </el-radio-group>
        </el-card>
    </div>

      <div class="table-container" >
        <div ref="mainTablePanel" :style="{height: mainTableDivHeight}">
        <el-table
          ref="filterTable"
         :key="rndKey"
         v-loading="loading"
          border
          size="mini"
          height="650px"
          @header-dragend="handleHeaderDragEnd"
          :data="filteredRkWareNoticeTabBakList"
          show-summary
          :summary-method="getSummaries"
          @selection-change="handleSelectionChange"
          :row-class-name="getRowClassName"



        >

          <el-table-column type="selection" width="55" align="center" />
           <el-table-column
            v-for="item in columns"
            :key="item.key"
            :label="item.label"
            align="center"
            :prop="item.columnName"
            v-if="item.visible"
            :width="item.width"
            sortable
            :filters="item.filters" :filter-method="filterHandler"
          >
            <template v-slot="scope">
              <dict-tag
                v-if="item.columnName === 'receivingStatus'"
                v-slot="scope"
                :options="dict.type.receive_status"
                :value="scope.row[item.columnName]"
              />
<!--              <dict-tag-->
<!--                v-else-if="item.columnName === 'unit'"-->
<!--                :options="dict.type.goods_unit"-->
<!--                :value="scope.row[item.columnName]"-->
<!--              />-->
              <dict-tag
                v-else-if="item.columnName === 'levelType'"
                :options="dict.type.level_type"
                :value="scope.row[item.columnName]"
              />
              <dict-tag
                v-else-if="item.columnName === 'status'"
                :options="dict.type.common_status"
                :value="scope.row[item.columnName]"
              />
              <span v-else>{{ scope.row[item.columnName] }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagePanel">
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { listRkWareNoticeTabBak, getRkWareNoticeTabBak,listTotal, delRkWareNoticeTabBak, addRkWareNoticeTabBak, updateRkWareNoticeTabBak, disabled, enabled, changeStatus } from "@/api/system/rkWareNoticeTabBak";
import { listCOLUMN } from "@/api/system/column";
import {selectStorageList} from "@/api/system/storage";
import {listSupplier} from "@/api/system/dept";

export default {
  name: "RkWareNoticeTabBak",
  dicts: ['level_type', 'common_status', 'inboud_status'],
  data() {
    return {
      rndKey: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库通知单明细历史表表格数据
      storageList: [],
      personList: [''],
      // 弹出层标题
      title: "",
      mainTableHeight: "0px",
      mainTableDivHeight: "0px",
      businessCodeTrk: "rkWareNoticeTabBak",
      rightToolbarShow: false,
      tableNo: 0,
      rkWareNoticeTabBakList: [],
      rkWareNoticeTabBakLists: [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        date: null,
        salesOrderNumber: null,
        noticeId: null,
        goodsId: null,
        goodsName: null,
        unit: null,
        specification: null,
        recoil: null,
        brand: null,
        createBy: null,
        price: null,
        needPerson: null,
        totalMoney: null,
        arraMount: null,
        recNum: null,
        project: null,
        needDept: null,
        useType: null,
        recPerson: null,
        scaleUnit: null,
        totalVolume: null,
        totalRoughWeight: null,
        totalNetWeigh: null,
        amount: null,
        productionDate: null,
        storageId: null,
        storageAreaId: null,
        packageId: null,
        goodsTypeId: null,
        barcode: null,
        goodsVolume: null,
        printSts: null,
        printCs: null,
        netWeigh: null,
        kindNum: null,
        expiryDate: null,
        operateDate: null,
        productStatus: null,
        receivingStatus: null,
        inStatus: null,
        ctl: null,
        qualityInspectionDate: null,
        status: null,
        acceNum: null,
        qualityInspecStatus: null,
        orderType: null,
        applicant: null,
        supplier: null,
        qualified: null,
        planDate: null,
        invoiceTitle: null,
        planTime: null,
        needCycle: null,
        needType: null,
        batchNo: null,
        reportTime: null,
        abc: null,
        levelType: null,
        storageShortName: null,
        storageLocation: null
      },
      // 表单参数
      form: {},
      warehouseType: null, // 默认选中机器人库
      // 表单校验
      rules: {},
      columns: [
      ],
      totalMoney: '',
      acceNum: '',
      selectedRowKeys: [],
      filteredOptions: [],
    };
  },
  computed: {

    filteredRkWareNoticeTabBakList() {
        if (this.warehouseType === 'robot') {
          let arrays1 = this.rkWareNoticeTabBakList.filter(item => {
            return this.storageList.some(item2 => item2.storageShortName === item.storageShortName && item2.type == "2");
          });
          this.total = arrays1.length;
          return arrays1;
        } else if(this.warehouseType === 'normal') {
          let arrays1 = this.rkWareNoticeTabBakList.filter(item => {
            return this.storageList.some(item2 => item2.storageShortName === item.storageShortName && item2.type == "1");
          });
          this.total = arrays1.length;
          return arrays1;
        } else{
          let arrays1 = this.rkWareNoticeTabBakList
          // this.total = arrays1.length;
          return arrays1;
        }
    }
  },
  created() {
    this.getList();
    this.getStorageList();
    this.getTotal();
    this.getSupplier();
  },
  mounted() {
    this.computedTableHeight();
    this.generateFilters();
  },
  watch: {
    'showSearch': function () {
      this.computedTableHeight();
    }
  },
  methods: {
   async  getStorageList() {
     await selectStorageList({}).then((response) => {
        if (response.code == 200) {
          this.storageList = [];
          this.storageList = response.data

        }
      });
    },
    async getTotal() {
      try {
        const response = await listTotal(this.queryParams);
        this.rkWareNoticeTabBakLists = response.data;

        this.totalMoney = this.rkWareNoticeTabBakLists.reduce((sum, item) => {
          return sum + (parseFloat(item.totalMoney) || 0); // 确保将 totalMoney 转换为数字
        }, 0).toFixed(2); // 保留两位小数
        this.acceNum = this.rkWareNoticeTabBakLists.reduce((sum, item) => {
          return sum + (parseFloat(item.acceNum) || 0); // 确保将 shelvesNum 转换为数字
        }, 0).toFixed(2); // 保留两位小数
      } catch (error) {
        console.error('Error loading total data:', error);
      }
    },


    /** 查询用户展示字段定义管理列表 */
    getHideColumn() {
      var queryHideColumnParams = {
        pageNum: 1,
        pageSize: 100,
        businessCode: this.businessCodeTrk,
        tableNo: this.tableNo
      };
      listCOLUMN(queryHideColumnParams).then(response => {
        if (response.rows.length > 0) {
          var row = response.rows[0];
          var columnHide = row.columnHide.split(",");
          if (columnHide.length > 0) {
            for (let item in this.columns) {
              if (columnHide.indexOf(this.columns[item].columnName) > -1) {
                this.columns[item].visible = false;
              }
            }
          }
        }
        this.rightToolbarShow = true;
      });
    },
    handleHeaderDragEnd(newWidth, oldWidth, column, event) {
      this.columns.forEach((obj) => {
        if (obj.columnName === column.property) obj.width = newWidth;
      });
      this.$refs.toolBarRef.saveConfig(this.columns);
    },
    customColsHandler(columns) {
      this.columns = columns;
      this.rndKey = Math.random();
    },
    computedTableHeight() {
      this.$nextTick(() => {
        var totalHeight = this.$refs.appPanel.clientHeight;
        var toolHeight = this.$refs.toolPanel.clientHeight;

        var cardHeight = this.$refs.cardPanel.clientHeight;
        var searchHeight = this.$refs.searchPanel.clientHeight;

        var tablePanelHeight = totalHeight - toolHeight - searchHeight -cardHeight - 14 - 5;

        this.mainTableDivHeight = tablePanelHeight + "px";
        this.mainTableHeight = (tablePanelHeight - 25) + "px";

      })
    },
    getSupplier(){
      listSupplier().then(response=>{
        this.filteredOptions = response.data;
          // .filter(item => item.needDept) // 过滤空值
          // .filter((item, index, self) => index === self.findIndex(t => t.needDept === item.needDept)); // 去重

      })
    },
    /** 查询入库通知单明细历史表列表 */
    getList() {
      this.loading = true;
      listRkWareNoticeTabBak(this.queryParams).then(response => {
        this.rkWareNoticeTabBakList =  response.rows.map(row => {
          return Object.keys(row).reduce((acc, key) => {
            // 检查每个值，如果为null则替换为''，否则保留原值
            acc[key] = row[key] === 'null' ? '' : row[key];
            return acc;
          }, {});
        });
        this.total = response.total;
        if (this.columns.length === 0) {
          this.columns = response.columns.map(column => {
            // 如果columns中也可能有null值，同样进行处理
            return column === null ? '' : column;
          });
      }

       this.loading = false;
        this.generateFilters();
       });



    },
    generateFilters() {
      this.columns.forEach(column => {
        const uniqueValues = [...new Set(this.rkWareNoticeTabBakList.map(item => item[column.columnName]))];
        column.filters = uniqueValues.map(value => ({text: value, value}));
        column.filterMethod = (value, row) => row[column.columnName] === value;
      });
    },
    filterHandler(value, row, column) {
      const property = column['property'];
      return row[property] === value;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        salesOrderNumber: null,
        purchaseId: null,
        noticeId: null,
        goodsId: null,
        goodsName: null,
        unit: null,
        specification: null,
        recoil: null,
        brand: null,
        invoiceTitle: null,
        price: null,
        totalMoney: null,
        arraMount: null,
        recNum: null,
        project: null,
        needDept: null,
        useType: null,
        needPerson: null,
        providerName: null,
        scaleUnit: null,
        totalVolume: null,
        totalRoughWeight: null,
        totalNetWeigh: null,
        amount: null,
        productionDate: null,
        storageId: null,
        storageAreaId: null,
        packageId: null,
        remark: null,
        goodsTypeId: null,
        barcode: null,
        goodsVolume: null,
        printSts: null,
        printCs: null,
        netWeigh: null,
        kindNum: null,
        expiryDate: null,
        operateDate: null,
        productStatus: null,
        receivingStatus: null,
        inStatus: null,
        ctl: null,
        qualityInspectionDate: null,
        status: null,
        acceNum: null,
        recPerson: null,
        qualityInspecStatus: null,
        orderType: null,
        applicant: null,
        supplier: null,
        qualified: null,
        updateTime: null,
        planDate: null,
        planTime: null,
        needCycle: null,
        needType: null,
        batchNo: null,
        reportTime: null,
        createTime: null,
        createBy: null,
        updateBy: null,
        abc: null,
        levelType: null,
        storageShortName: null,
        storageLocation: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.getTotal();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
      this.$refs.filterTable.clearFilter();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.selectedRowKeys = selection.map(item => item.id) // 更新选中行的 key
    },
    getRowClassName({ row }) {
      if (this.selectedRowKeys.includes(row.id)) {
        return 'selected-row'
      }
      return ''
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加入库通知单明细历史表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRkWareNoticeTabBak(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改入库通知单明细历史表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRkWareNoticeTabBak(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRkWareNoticeTabBak(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除入库通知单明细历史表编号为"' + ids + '"的数据项？').then(function () {
        return delRkWareNoticeTabBak(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    /** 用户状态修改 */
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '"id为"' + row.id + '"数据项？').then(function () {
        return changeStatus(row.id, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 启用按钮操作 */
    handleEnable(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认启用入库通知单明细历史表编号为"' + ids + '"的数据项？').then(function () {
        return enabled(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("启用成功");
      }).catch(() => {
      });
    },
    /** 禁用按钮操作 */
    handleDisabled(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认禁用入库通知单明细历史表编号为"' + ids + '"的数据项？').then(function () {
        return disabled(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("禁用成功");
      }).catch(() => {
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('system/rkWareNoticeTabBak/export', {
        ...this.queryParams
      }, `rkWareNoticeTabBak_${new Date().getTime()}.xlsx`)
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      const sumFields = ['arraMount', "totalMoney"];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }

        if (sumFields.includes(column.property)) {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] = this.formatCurrency(sums[index]);
          } else {
            sums[index] = ' ';
          }
        }
      });
      return sums;
    },

    // 处理仓库类型变化
    handleWarehouseTypeChange() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    formatCurrency(value) {
      return Number(value).toFixed(2);
    },
  }
};
</script>
<style lang="scss">
.app-container {
  height: calc(100vh - 84px);
}
.box-card {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}


.el-radio-group {
  margin-bottom: 5px;
}
.el-table {
  .selected-row {
    background-color: #71b7e7 !important;

    &:hover > td {
      background-color: #71b7e7 !important;
    }

    td {
      background-color: #71b7e7 !important;
    }
  }
}
.larger-font {
  font-size: 25px; /* 调整字体大小，根据需要修改 */
}
</style>
