<template>
  <div class="app-container" ref="appPanel">
    <div ref="toolPanel">
      <el-row :gutter="10" class="mb8">
        <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">
          <el-button
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
          >导出</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">{{ shelvesNum }}件</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="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="specification">
          <el-input
            v-model="queryParams.specification"
            placeholder="请输入规格"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </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="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="ckType">
          <el-select
            v-model="queryParams.ckType"
            placeholder="请选出库类型"
            clearable>
            <el-option
              v-for="dict in dict.type.outbound_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </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="locationId">
          <el-input
            v-model="queryParams.locationId"
            placeholder="请输入库位"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="申请人" prop="applicant">
          <el-input
            v-model="queryParams.applicant"
            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="supplier">
          <el-select
            v-model="queryParams.supplier"
            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="orderId">
          <el-input
            v-model="queryParams.orderId"
            placeholder="请输入出库单号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="子需求编号" prop="businessId">
          <el-input
            v-model="queryParams.businessId"
            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="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 ref="cardPanel">
        <el-card class="mb-4" :body-style="{ padding: '5px' }">
          <el-row type="flex" justify="space-between">
            <el-col :span="12" class="text-left">
              <el-radio-group v-model="warehouseType" @change="handleWarehouseTypeChange">
                <el-radio-button label="">总体</el-radio-button>
                <el-radio-button label="robot">机器人库</el-radio-button>
                <el-radio-button label="normal">普通仓库</el-radio-button>
              </el-radio-group>
            </el-col>
            <el-col :span="12" class="text-right">
              <el-radio-group v-model="quantityCompareType" @change="handleQuantityCompareChange">
                <el-radio-button label="">全部</el-radio-button>
                <el-radio-button label="more">多出</el-radio-button>
                <el-radio-button label="less">少出</el-radio-button>
                <el-radio-button label="equal">相等</el-radio-button>
              </el-radio-group>
            </el-col>
          </el-row>
        </el-card>
     </div>



    <div class="table-container">
      <div ref="mainTablePanel" :style="{height: mainTableDivHeight}">
        <el-table
          ref="tckOrderBakTab"
          :key="rndKey"
          v-loading="loading"
          border
          size="mini"
          :height="mainTableHeight"
          :data="filteredTckOrderDetailbakList"
          @header-dragend="handleHeaderDragEnd"
          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.seq"
            :label="item.label"
            align="center"
            :prop="item.columnName"
            v-if="item.visible"
            :width="item.width"
            sortable
            :filters="filters[item.columnName]"
            :filter-method="filterHandler"
          >
            <template v-slot="scope">
              <dict-tag
                v-if="item.columnName === 'confirmStatus'"
                :options="dict.type.out_status"
                :value="scope.row[item.columnName]"
              />
              <dict-tag
                v-else-if="item.columnName === 'isAudit'"
                :options="dict.type.is_audit"
                :value="scope.row[item.columnName]"
              />
              <dict-tag
                v-else-if="item.columnName === 'status'"
                :options="dict.type.common_status"
                :value="scope.row[item.columnName]"
              />
              <dict-tag
                v-else-if="item.columnName === 'ckType'"
                :options="dict.type.outbound_type"
                :value="scope.row[item.columnName]"
              />
              <dict-tag
                v-else-if="item.columnName === 'levelType'"
                :options="dict.type.level_type"
                :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 {listTckOrderDetailbak, getTckOrderDetailbak, delTckOrderDetailbak, addTckOrderDetailbak, updateTckOrderDetailbak, disabled, enabled, changeStatus } from "@/api/system/tckOrderDetailbak";
import { listCOLUMN } from "@/api/system/column";
import {selectStorageList} from "@/api/system/storage";
import {listTotal} from "@/api/system/tckOrderDetailbak";
import {listSupplier} from "@/api/system/dept";

export default {
  name: "TckOrderDetailbak",
  dicts: ['level_type', 'outbound_type','out_status'],
  data() {
    return {
      rndKey: 0,
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      tckOrderDetailbakList: [],
      tckOrderDetailbakLists: [],
      storageList: [],
      title: "",
      mainTableHeight: "0px",
      mainTableDivHeight: "0px",
      businessCodeTrk: "tckOrderDetailbak",
      rightToolbarShow: false,
      tableNo: 0,
      open: false,
      daterangeCreateTime: [],
      filteredOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        date: null,
        orderId: null,
        businessId: null,
        goodsId: null,
        goodsName: null,
        locationId: null,
        specification: null,
        unit: null,
        storageId: null,
        storageShortName: null,
        shelvesNum: null,
        goodsNum: null,
        callShelvesNum: null,
        price: null,
        goodsTypeId: null,
        providerId: null,
        recoil: null,
        storageAreaId: null,
        pickNum: null,
        trNum: null,
        barcode: null,
        status: null,
        toLoc: null,
        confirmStatus: null,
        expiryDate: null,
        stockNum: null,
        taskId: null,
        abc: null,
        levelType: null,
        supplier: null,
        applicant: null,
        deliveryId: null,
        toMoney: null,
        ckType: null,
        orderType: null,
        createTime: null,
        ctl: null
      },
      form: {},
      rules: {
        orderId: [
          { required: true, message: "主表id不能为空", trigger: "blur" }
        ],
      },
      columns: [],
      filters:[],
      warehouseType: '',
      quantityCompareType: '',
      totalMoney: '',
      shelvesNum: '',
      selectedRowKeys: [],
    };
  },
  computed: {
    filteredTckOrderDetailbakList() {
      let filteredList = this.tckOrderDetailbakList;

      if (this.warehouseType === 'robot') {
        filteredList = filteredList.filter(item => {
          return this.storageList.some(item2 => item2.storageShortName === item.storageShortName && item2.type == "2");
        });
      } else if (this.warehouseType === 'normal') {
        filteredList = filteredList.filter(item => {
          return this.storageList.some(item2 => item2.storageShortName === item.storageShortName && item2.type == "1");
        });
      }

      if (this.quantityCompareType === 'more') {
        filteredList = filteredList.filter(item => {
          const shelvesNum = parseFloat(item.shelvesNum) || 0;
          const goodsNum = parseFloat(item.goodsNum) || 0;
          return shelvesNum > goodsNum;
        });
      } else if (this.quantityCompareType === 'less') {
        filteredList = filteredList.filter(item => {
          const shelvesNum = parseFloat(item.shelvesNum) || 0;
          const goodsNum = parseFloat(item.goodsNum) || 0;
          return shelvesNum < goodsNum;
        });
      } else if (this.quantityCompareType === 'equal') {
        filteredList = filteredList.filter(item => {
          const shelvesNum = parseFloat(item.shelvesNum) || 0;
          const goodsNum = parseFloat(item.goodsNum) || 0;
          return Math.abs(shelvesNum - goodsNum) < 0.000001;
        });
      }

      return filteredList;
    }
  },
  mounted() {
    this.computedTableHeight();
    this.generateFilters();
  },
  watch: {
    'showSearch': function () {
      this.computedTableHeight();
    }
  },
  created() {
    this.getList();
    this.getStorageList();
    this.getTotal();
    this.getSupplier();
  },
  methods: {
    async getStorageList() {
      await selectStorageList({}).then((response) => {
        if (response.code == 200) {
          this.storageList = [];
          this.storageList = response.data
        }
      });
    },
    recoilFormatter(row, column, cellValue) {
      return cellValue === 'null' ? '' : cellValue;
    },
    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;
      });
    },
    generateFilters() {
      this.columns.forEach(column => {
        const uniqueValues = [...new Set(this.tckOrderDetailbakList.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;
    },
    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";
      })
    },
    async getTotal() {
      try {
        const response = await listTotal(this.queryParams);
        this.tckOrderDetailbakLists = response.data;
        this.totalMoney = this.tckOrderDetailbakLists.reduce((sum, item) => {
          return sum + (parseFloat(item.toMoney) || 0);
        }, 0).toFixed(2);
        this.shelvesNum = this.tckOrderDetailbakLists.reduce((sum, item) => {
          return sum + (parseFloat(item.shelvesNum) || 0);
        }, 0).toFixed(2);
      } catch (error) {
        console.error('Error loading total data:', error);
      }
    },
    getSupplier(){
      listSupplier().then(response=>{
        this.filteredOptions = response.data;
        console.log('部门'+this.filteredOptions)
      })
    },
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }


      listTckOrderDetailbak(this.queryParams).then(response => {
        this.tckOrderDetailbakList = response.rows.map(row => {
          const processedRow = Object.keys(row).reduce((acc, key) => {
            acc[key] = row[key] === 'null' ? '' : row[key];
            return acc;
          }, {});

          if (processedRow.shelvesNum !== undefined) {
            processedRow.goodsNum = processedRow.shelvesNum;
          }

          // 如果 ckType 字段为空值，则赋值为 5
          if (processedRow.ckType === '' || processedRow.ckType === null || processedRow.ckType === undefined) {
            processedRow.ckType = 5;
          }

          return processedRow;
        });
        this.total = response.total;

        if (this.columns.length === 0) {
          this.columns = response.columns.map(column => {
            return column === null ? '' : column;
          });
        }

        this.loading = false;
        this.generateFilters();
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        orderId: null,
        businessId: null,
        goodsId: null,
        goodsName: null,
        locationId: null,
        specification: null,
        unit: null,
        storageId: null,
        storageShortName: null,
        shelvesNum: null,
        goodsNum: null,
        callShelvesNum: null,
        remark: null,
        price: null,
        goodsTypeId: null,
        providerId: null,
        recoil: null,
        storageAreaId: null,
        pickNum: null,
        trNum: null,
        barcode: null,
        status: null,
        toLoc: null,
        confirmStatus: null,
        expiryDate: null,
        stockNum: null,
        taskId: null,
        updateTime: null,
        abc: null,
        levelType: null,
        supplier: null,
        applicant: null,
        createTime: null,
        createBy: null,
        updateBy: null,
        deliveryId: null,
        ckType: null,
        orderType: null,
        ctl: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.getTotal();
    },
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    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)
    },
    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
      getTckOrderDetailbak(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) {
            updateTckOrderDetailbak(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTckOrderDetailbak(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 delTckOrderDetailbak(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/tckOrderDetailbak/export', {
        ...this.queryParams
      }, `tckOrderDetailbak_${new Date().getTime()}.xlsx`)
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (column.property === 'toMoney') {
          const values = data.map(item => Number(item.toMoney));
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] = sums[index].toFixed(2);
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
    handleWarehouseTypeChange() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.getTotal();
    },
    handleQuantityCompareChange() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.getTotal();
    },
  }
};
</script>

<style lang="scss">
.app-container {
  height: calc(100vh - 84px);
  display: flex;
  flex-direction: column;
}

.box-card {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.el-radio-group {
  margin-bottom: 5px;
}

.text-right {
  text-align: right;
  padding-right: 20px;
}

.text-left {
  text-align: left;
  padding-left: 20px;
}

.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>
