<template>
  <div class="app-container">
    <div class="app-content">
      <div class="title">
        产品销售统计
      </div>
      
      <el-form class="search-form" :inline="true">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="时间:">
              <el-select v-model="value" placeholder="请选择日期">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
             <el-form-item label="公司名:" prop="companyId">
              <el-select filterable v-model="companyId" @change="companyChange" placeholder="请选择公司名称" clearable size="small">
                <el-option
                  v-for="item in companys"
                  :key="item.companyId"
                  :label="item.companyName"
                  :value="item.companyId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门:">
              <treeselect :clearable="false" v-model="deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="员工:">
              <el-select filterable v-model="userIds" placeholder="请选择员工" clearable size="small">
                <el-option
                  v-for="item in users"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row> 
        
       
        
    
        
        
        <el-form-item label="筛选日期" prop="createTime">
          <el-date-picker clearable size="small" style="width: 205.4px"
            v-model="dateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="cyan" icon="el-icon-search" @click="storeProduct">搜索</el-button>
        </el-form-item>
      </el-form>
      
      <div class="data-box">
        <div class="echart-box">
          <div id="echart-customer"></div>
        </div>
        
        <!-- 产品销售统计数据表格 -->
        <div class="table-container">
          <h3 class="table-title">产品销售汇总</h3>
          <!-- <div class="export">
            <el-button type="primary" @click="handleExport">导出数据</el-button>
          </div> -->
          <el-table 
            :data="tableData"
            border
            stripe
            style="width: 100%; margin-top: 20px;"
            :row-class-name="tableRowClassName"
            :span-method="objectSpanMethod">
            
            <!-- 产品名称列 -->
            <el-table-column prop="name" label="产品名称" width="100" align="center" class-name="sticky-column">
              <template slot-scope="scope">
                <span :class="{'group-name': scope.row.isGroup}">{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            
            <!-- 动态生成订单类型列 - 使用多级表头 -->
            <el-table-column 
              v-for="orderType in orderTypeOptions" 
              :key="orderType.dictValue"
              :label="orderType.dictLabel" 
              align="center">
              
              <!-- 数量子列 -->
              <el-table-column 
                label="数量" 
                width="60" 
                align="center">
                <template slot-scope="scope">
                  {{ getOrderData(scope.row, orderType.dictValue, 'count') }}
                </template>
              </el-table-column>
              
              <!-- 金额子列 -->
              <el-table-column 
                label="金额" 
                width="80" 
                align="center">
                <template slot-scope="scope">
                  {{ getOrderData(scope.row, orderType.dictValue, 'amount') }}
                </template>
              </el-table-column>
              
            </el-table-column>
            
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { storeProduct } from "@/api/hisStore/statistics";
import { getUserListByDeptId } from "@/api/company/companyUser";
import echarts from 'echarts';
import resize from '../../dashboard/mixins/resize';
import { treeselect } from "@/api/company/companyDept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getCompanyList } from "@/api/company/company";

export default {
  name: 'ContentStatistics',
  mixins: [resize],
  components: { Treeselect },
  watch: {
    // 监听deptId
    'deptId': 'currDeptChange'
  },
  data() {
    return {
      companys: [],
      deptOptions: [],
      companyId: undefined,
      deptId: undefined,
      userIds: undefined,
      users: [],
      dateRange: [],
      chart: null,
      options: [{
        value: '1',
        label: '今天'
      }, {
        value: '2',
        label: '昨天'
      }, {
        value: '3',
        label: '本周'
      }, {
        value: '4',
        label: '上周'
      }, {
        value: '5',
        label: '本月'
      }, {
        value: '6',
        label: '上月'
      }, {
        value: '7',
        label: '本季度'
      }, {
        value: '8',
        label: '上季度'
      }, {
        value: '9',
        label: '本年'
      }, {
        value: '10',
        label: '上年'
      }],
      value: '5',
      list: [],
      dates: [],
      orderCount: [], // 修改变量名
      payPrice: [], // 修改变量名
      // 订单类型选项 - 用作表头
      orderTypeOptions: [],
      // 产品销售统计表格数据
      tableData: []
    }
  },
  created() {
    getCompanyList().then(response => {
      this.companys = response.data;
      if (this.companys != null && this.companys.length > 0) {
        this.companyId = this.companys[0].companyId;
        this.getTreeselect();
      }
    });
    
    // 获取订单类型字典
    this.getDicts("store_order_type").then((response) => {
      this.orderTypeOptions = response.data;
    });
  },
  methods: {
    companyChange(val) {
      console.log(val);
      this.companyId = val;
      this.getTreeselect();
    },
    currDeptChange(val) {
      console.log(val)
      this.deptId = val;
      this.getUserListByDeptId();
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      var that = this;
      var param = { companyId: this.companyId }
      treeselect(param).then((response) => {
        this.deptOptions = response.data;
        console.log(this.deptOptions)
        if (response.data != null && response.data.length > 0) {
          this.deptId = response.data[0].id;
          that.storeProduct()
        }
      });
    },
    handleExport() {
      var data;
      if (this.userIds != undefined) {
        data = { type: this.value, userIds: this.userIds + "", deptId: this.deptId }
      }
      else {
        data = { type: this.value, deptId: this.deptId }
      }
      // 导出产品销售统计数据
      console.log('导出产品销售统计数据', data);
    },
    getUserListByDeptId() {
      this.userIds = undefined;
      var data = { deptId: this.deptId };
      getUserListByDeptId(data).then(response => {
        this.users = response.data;
      });
    },
    storeProduct() {
      var data;
      if (this.userIds != undefined) {
        data = { type: this.value, userIds: this.userIds + "", deptId: this.deptId }
      }
      else {
        data = { type: this.value, deptId: this.deptId }
      }
      if(this.dateRange && this.dateRange.length > 0){
        data.type = null
        data.startTime = this.dateRange[0]
        data.endTime = this.dateRange[1]
      }
      
      storeProduct(data).then((response) => {
        this.dates = response.dates;
        this.orderCount = response.orderCount;
        this.payPrice = response.payPrice;
        
        // 处理表格数据，补全缺失的订单类型数据
        this.tableData = this.processTableData(response.tableData || []);
        
        setTimeout(() => {
          this.initEchart();
        }, 500);
      });
    },
    
    // 新增方法：处理表格数据，为每个产品补全所有订单类型的数据
    processTableData(rawTableData) {
      return rawTableData.map(item => {
        // 创建一个新的 productCounts 对象，包含所有订单类型
        const processedProductCounts = {};
        
        // 遍历所有订单类型选项，为每个类型设置默认值
        this.orderTypeOptions.forEach(orderType => {
          const dictValue = orderType.dictValue;
          if (item.productCounts && item.productCounts[dictValue]) {
            // 如果原数据中存在该订单类型的数据，使用原数据
            processedProductCounts[dictValue] = item.productCounts[dictValue];
          } else {
            // 如果原数据中不存在该订单类型的数据，设置默认值
            processedProductCounts[dictValue] = {
              count: 0,
              amount: 0.0
            };
          }
        });
        
        return {
          ...item,
          productCounts: processedProductCounts
        };
      });
    },
    
    initEchart() {
      var option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['订单数量', '金额']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: this.dates
          }
        ],
        yAxis: [
          {
            type: 'value',
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {
            name: '订单数量',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            data: this.orderCount // 修改为正确的变量名
          },
          {
            name: '金额',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            data: this.payPrice // 修改为正确的变量名
          }
        ]
      };
      this.chart = echarts.init(document.getElementById("echart-customer"));
      this.chart.setOption(option, true);
    },
    
    // 修改获取订单数据的方法，适配新的数据结构
    getOrderData(row, orderType, dataType) {
      // 使用 productCounts 而不是 orderData
      if (row.productCounts && row.productCounts[orderType]) {
        const value = row.productCounts[orderType][dataType] || 0;
        if (dataType === 'amount') {
          return value.toFixed(2);
        }
        return value;
      }
      return dataType === 'amount' ? '0.00' : 0;
    },
    
    // 表格行样式
    tableRowClassName({ row, rowIndex }) {
      if (row.isGroup) {
        return 'group-row';
      }
      return '';
    },
    // 表格合并方法
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      return {
        rowspan: 1,
        colspan: 1
      };
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  border: 1px solid #e6e6e6;
  padding: 12px;
  .app-content {
    background-color: white;
    .title {
      padding: 20px 30px 0px 30px;
      font-size: 18px;
      font-weight: bold;
      color: black;
    }
    .search-form {
      margin: 20px 30px 0px 30px;
    }
    .data-box {
      padding: 30px;
      background-color: rgb(255, 255, 255);
      height: 100%;
      .echart-box {
        margin: 0 auto;
        text-align: center;
      }
      .el-select {
        margin: 5px 10px;
      }
      .table-box {
        margin-top: 15px;
        .export {
          float: right;
          margin: 10px 0px;
        }
      }
      // 表格样式
      .table-container {
        margin-top: 30px;
        .table-title {
          font-size: 16px;
          font-weight: bold;
          color: #333;
          margin-bottom: 10px;
        }
        .export {
          float: right;
          margin: 10px 0px;
        }
      }
    }
  }
}

#echart-customer {
  width: 100%;
  height: 320px;
}

.vue-treeselect {
  width: 217px;
  height: 36px;
}

// 表格相关样式
::v-deep .group-row {
  background-color: #e8f5e8 !important;
  font-weight: bold;
}

::v-deep .group-name {
  font-weight: bold;
  color: #333;
}

::v-deep .el-table {
  font-size: 12px;
  
  .el-table__header-wrapper {
    th {
      background-color: #f5f7fa;
      font-weight: bold;
      color: #333;
    }
  }
  
  .el-table__body-wrapper {
    td {
      padding: 8px 0;
    }
  }
}

::v-deep .sticky-column {
  position: sticky;
  left: 0;
  z-index: 2;
  background-color: white;
  
  // 为表头也添加样式
  &.is-header-column {
    background-color: #f5f7fa;
  }
}

// 确保表格容器允许sticky定位
::v-deep .el-table__body-wrapper {
  overflow-x: auto;
}
</style>

<style>
.vue-treeselect__control {
  display: block;
}
</style>