<template>
  <div class="app-container" ref="appPanel">
    <!-- Charts Section -->
    <!--    <el-row :gutter="20" class="mb8">
          <div slot="header" class="clearfix">
            <span>库存统计图表</span>
          </div>
          <el-card class="box-card" style="height: 620px">
            <div slot="header" class="clearfix">
            </div>
            <el-row :gutter="20">
              <el-col :span="12">
                <div ref="inventoryDistributionChart" style="height: 300px;"></div>
              </el-col>
              <el-col :span="12">
                <div ref="inventoryTrendChart" style="height: 300px;"></div>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <div ref="levelTypeDistributionChart" style="height: 300px;"></div>
              </el-col>
              <el-col :span="12">
                <div ref="monthlyValueTrendChart" style="height: 300px;"></div>
              </el-col>
            </el-row>
          </el-card>
        </el-row>-->

    <!-- Original Content -->
    <div ref="toolPanel">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleImport"
            v-hasPermi="['system:ckOrders:export']"
          >导入
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:stock:export']"
          >导出
          </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">{{ shelvesNum }}件</span></h3>
          </div>
        </el-col>

        <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="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="locationId">
          <el-input
            v-model="queryParams.locationId"
            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="goodsId">
          <el-input
            v-model="queryParams.specification"
            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="storageMode">
          <el-input
            v-model="queryParams.storageMode"
            placeholder="请输入入库类型"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
        <!-- <el-form-item label="入库时间" prop="wareDate">
          <el-input
            v-model="queryParams.wareDate"
            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="recoil">
          <el-input
            v-model="queryParams.recoil"
            placeholder="请输入物料描述"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="需求部门" prop="needDept">
          <el-input
            v-model="queryParams.needDept"
            placeholder="请输入需求部门"
            clearable
            @keyup.enter.native="needDept"
          />
        </el-form-item>

        <el-form-item label="需求人" prop="needPerson">
          <el-input
            v-model="queryParams.needPerson"
            placeholder="请输入需求人"
            clearable
            @keyup.enter.native="needPerson"
          />
        </el-form-item>

        <el-form-item label="子需求编号" prop="salesOrderNumber">
          <el-input
            v-model="queryParams.salesOrderNumber"
            placeholder="请输入子需求编号"
            clearable
            @keyup.enter.native="salesOrderNumber"
          />
        </el-form-item>







        <el-form-item label="容器编号" prop="ctl">
          <el-input
            v-model="queryParams.ctl"
            placeholder="请输入容器编号"
            clearable
            @keyup.enter.native="ctl"
          />
        </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-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>
    </div>
<!--    <div>-->
<!--      <h3 style="color: red">库存总价: {{ totalMoney }}元</h3>-->
<!--      <h3 style="color: red">总计数量: {{ shelvesNum }}件</h3>-->
<!--    </div>-->
    <div class="table-container" style="flex-grow: 1; overflow: auto;">
      <div ref="mainTablePanel">
        <el-table :key="rndKey" ref="filterTable" v-loading="loading" border size="mini"
                  height="650px"
                  :data="tMiStockList" @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" sortable :key="item.seq" :label="item.label" align="center"
                           :prop="item.columnName" v-if="item.visible" :width="item.width"
                           :filters="item.filters" :filter-method="filterHandler">
            <template slot-scope="scope">
              <dict-tag v-if="item.columnName === 'status'" :options="dict.type.common_status"
                        :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-if="['price', 'totalMoney'].includes(item.columnName)">
                {{ formatCurrency(scope.row[item.columnName]) }}
              </span>
              <span v-else>{{ scope.row[item.columnName] }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="pagePanel">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
<!--          <el-checkbox v-model="upload.updateSupport"/>-->
<!--          是否更新已经存在的通知单数据-->
          <el-link
            type="primary"
            style="font-size: 12px"
            @click="importTemplate"
          >下载模板
          </el-link>
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addStock,
  delStock,
  getStock,
  listStock,
  updateStock,
  listTotal
} from "@/api/system/tMiXnStock";
import {selectStorageList} from "@/api/system/storage";
import TableMixin from "@/api/tableMixin";
import * as echarts from 'echarts';
import {listCOLUMN} from "@/api/system/column";
import {getToken} from "@/utils/auth";

export default {
  name: "TMiXnStock",
  dicts: ["storage_classification", "common_status", "level_type"],
  mixins: [TableMixin],
  data() {
    return {
      rndKey: 0,
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      tMiStockList: [],
      tMiStockLists: [],
      title: "",
      mainTableHeight: "0px",
      mainTableDivHeight: "0px",
      businessCodeTrk: "tMiStock",
      rightToolbarShow: false,
      tableNo: 0,
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        // 保留原有的查询参数
      },
      storageList: [],
      form: {},
      rules: {},
      columns: [],
      charts: {
        inventoryDistribution: null,
        inventoryTrend: null,
        levelTypeDistribution: null,
        monthlyValueTrend: null
      },
      totalMoney: '',
      shelvesNum: '',
      selectedRowKeys: [],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/xnstock/importData",
      },
    };
  },
  created() {
    this.getStorageList();
    this.getList();
    this.getTotal();
  },
  mounted() {
    this.computedTableHeight();
    this.generateFilters();
    this.$nextTick(() => {
      this.initCharts();
    });
  },
  watch: {
    'showSearch': function () {
      this.computedTableHeight();
    },
    tMiStockLists: {
      handler() {
        this.$nextTick(() => {
          this.updateCharts();
        });
      },
      deep: true
    },
    'tMiStockList': {
      handler(newList) {
        newList.forEach(item => {
          // 确保price和shelvesNum都存在且为数字
          const price = parseFloat(item.price) || 0;
          const shelvesNum = parseFloat(item.shelvesNum) || 0;
          // 计算totalMoney并保留两位小数
          item.totalMoney = (price * shelvesNum).toFixed(2);
        });
      },
      deep: true
    }
  },
  methods: {
    /** 查询用户展示字段定义管理列表 */
    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;
      });
    },
    /** 查询仓库列表 */
    getStorageList() {
      selectStorageList({}).then((response) => {
        if (response.code == 200) {
          this.storageList = [];
          response.data.forEach((element, index) => {
            // 假设 element 有一个唯一的 id 属性可以用作 key
            this.storageList.push({...element, key: element.id || `unique-${index}`});
          });
        } else {
          this.$modal.msgError("查询仓库失败");
        }
      });
    },
    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 searchHeight = this.$refs.searchPanel.clientHeight;
        var tablePanelHeight = totalHeight - toolHeight - searchHeight - 14 - 5;
        this.mainTableDivHeight = tablePanelHeight + "px";
        this.mainTableHeight = tablePanelHeight - 25 + "px";
      });
    },
    async getTotal() {
      try {
        const response = await listTotal(this.queryParams);
        this.tMiStockLists = response.data;
        this.totalMoney = this.tMiStockLists.reduce((sum, item) => {
          return sum + (parseFloat(item.totalMoney) || 0); // 确保将 totalMoney 转换为数字
        }, 0).toFixed(2); // 保留两位小数
        this.shelvesNum = this.tMiStockLists.reduce((sum, item) => {
          return sum + (parseFloat(item.shelvesNum) || 0); // 确保将 shelvesNum 转换为数字
        }, 0).toFixed(2); // 保留两位小数
      } catch (error) {
        console.error('Error loading total data:', error);
      }
    },
    getList() {
      this.loading = true;
      listStock(this.queryParams).then((response) => {
        if (this.columns.length === 0) {
          this.columns = response.columns;
        }
        this.tMiStockList = response.rows;
        this.total = response.total;
        this.generateFilters();
        this.loading = false;

      });
    },
    generateFilters() {
      this.columns.forEach(column => {
        let uniqueValues;
        if (column.columnName === 'status') {
          // For the status column, use the common_status dictionary
          uniqueValues = [...new Set(this.tMiStockList.map(item => item[column.columnName]))];
          column.filters = uniqueValues.map(value => ({
            text: this.dict.type.common_status.find(status => status.value === value)?.label || value,
            value
          }));
          column.filterMethod = (value, row) => row[column.columnName] === value;

          // Add a formatter for the column to display the dictionary label
          column.formatter = (row, column, cellValue, index) => {
            return this.dict.type.common_status.find(status => status.value === cellValue)?.label || cellValue;
          };
        } else {
          // For other columns, keep the original logic
          uniqueValues = [...new Set(this.tMiStockList.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;
    },
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      const sumFields = ['shelvesNum', 'price', "totalMoney"];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
        } else 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] = ' ';
          }
        } else {
          sums[index] = '/';
        }
      });
      return sums;
    },
    formatCurrency(value) {
      return Number(value).toFixed(2);
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.getTotal();
    },
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
      this.$refs.filterTable.clearFilter();
    },
    handleExport() {
      this.download(
        "system/xnstock/export",
        {
          ...this.queryParams,
        },
        `tMiXnStock_${new Date().getTime()}.xlsx`
      );
    },
    // 多选框选中数据
    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 ''
    },
    initCharts() {
      this.charts.inventoryDistribution = echarts.init(this.$refs.inventoryDistributionChart);
      this.charts.inventoryTrend = echarts.init(this.$refs.inventoryTrendChart);
      this.charts.levelTypeDistribution = echarts.init(this.$refs.levelTypeDistributionChart);
      this.charts.monthlyValueTrend = echarts.init(this.$refs.monthlyValueTrendChart);
    },
    updateCharts() {
      this.updateInventoryDistributionChart();
      this.updateInventoryTrendChart();
      this.updateLevelTypeDistributionChart();
      this.updateMonthlyValueTrendChart();
    },
    updateInventoryDistributionChart() {
      if (!this.charts.inventoryDistribution || !this.tMiStockLists || this.tMiStockLists.length === 0) return;

      const storageData = this.tMiStockLists.reduce((acc, item) => {
        acc[item.storageShortName] = (acc[item.storageShortName] || 0) + 1;
        return acc;
      }, {});

      const chartData = Object.keys(storageData).map(key => ({
        name: `仓库 ${key}`,
        value: storageData[key]
      }));

      const option = {
        title: {
          text: '库存分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: chartData.map(item => item.name)
        },
        series: [
          {
            name: '库存分布',
            type: 'pie',
            radius: '50%',
            data: chartData
          }
        ]
      };

      this.charts.inventoryDistribution.setOption(option);
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "虚拟库库存导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/xnstock/importTemplate",
        {},
        `虚拟库存_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    updateInventoryTrendChart() {
      if (!this.charts.inventoryTrend || !this.tMiStockLists || this.tMiStockLists.length === 0) return;

      const monthlyData = this.tMiStockLists.reduce((acc, item) => {
        const date = new Date(item.wareDate);
        const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;

        if (!acc[monthKey]) {
          acc[monthKey] = {
            totalItems: 0,
            totalMoney: 0
          };
        }

        acc[monthKey].totalItems += 1;
        acc[monthKey].totalMoney += Number(item.totalMoney);

        return acc;
      }, {});

      const sortedMonths = Object.keys(monthlyData).sort().slice(-3);
      const itemsData = [];
      const moneyData = [];

      sortedMonths.forEach(month => {
        const data = monthlyData[month];
        itemsData.push(data.totalItems);
        moneyData.push(this.formatCurrency(data.totalMoney));
      });

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          data: ['库存条数', '库存金额']
        },
        xAxis: [
          {
            type: 'category',
            data: sortedMonths,
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '库存条数',
            min: 0,
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '库存金额',
            min: 0,
            axisLabel: {
              formatter: '{value} 元'
            }
          }
        ],
        series: [
          {
            name: '库存条数',
            type: 'bar',
            data: itemsData
          },
          {
            name: '库存金额',
            type: 'line',
            yAxisIndex: 1,
            data: moneyData
          }
        ]
      };

      this.charts.inventoryTrend.setOption(option);
    },
    updateLevelTypeDistributionChart() {
      if (!this.charts.levelTypeDistribution || !this.tMiStockLists || this.tMiStockLists.length === 0) return;

      const levelTypeData = this.tMiStockLists.reduce((acc, item) => {
        const levelType = this.dict.type.level_type.find(dict =>
          dict.value === item.levelType)?.label || '未知';
        acc[levelType] = (acc[levelType] || 0) + 1;
        return acc;
      }, {});

      const chartData = Object.keys(levelTypeData).map(key => ({
        name: key,
        value: levelTypeData[key]
      }));

      const option = {
        title: {
          text: '库级分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: chartData.map(item => item.name)
        },
        series: [
          {
            name: '库级分布',
            type: 'pie',
            radius: '50%',
            data: chartData
          }
        ]
      };

      this.charts.levelTypeDistribution.setOption(option);
    },
    updateMonthlyValueTrendChart() {
      if (!this.charts.monthlyValueTrend || !this.tMiStockLists || this.tMiStockLists.length === 0) return;

      const monthlyData = this.tMiStockLists.reduce((acc, item) => {
        const date = new Date(item.wareDate);
        const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;

        if (!acc[monthKey]) {
          acc[monthKey] = 0;
        }

        acc[monthKey] += Number(item.totalMoney);

        return acc;
      }, {});

      const sortedMonths = Object.keys(monthlyData).sort();
      const valueData = sortedMonths.map(month => this.formatCurrency(monthlyData[month]));

      const option = {
        title: {
          text: '月度金额趋势',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}: {c} 元'
        },
        xAxis: {
          type: 'category',
          data: sortedMonths
        },
        yAxis: {
          type: 'value',
          name: '金额',
          axisLabel: {
            formatter: '{value} 元'
          }
        },
        series: [{
          data: valueData,
          type: 'line',
          smooth: true
        }]
      };

      this.charts.monthlyValueTrend.setOption(option);
    },
  }
};
</script>

<style lang="scss">
.app-container {
  height: 100%;
  overflow-y: auto;
  padding: 20px;
}
.larger-font {
  font-size: 25px; /* 调整字体大小，根据需要修改 */
}
.box-card {
  margin-bottom: 20px;
}
.el-table {
  .selected-row {
    background-color: #71b7e7 !important;

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

    td {
      background-color: #71b7e7 !important;
    }
  }
}
</style>
