<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="true"  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-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="订单类型:">
              <el-select v-model="orderType" placeholder="请选择订单类型" clearable size="small">
                <el-option
                  v-for="item in orderTypeOptions"
                  :key="item.dictLabel"
                  :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="媒体来源:">
              <el-select v-model="orderMedium" placeholder="请选择媒体来源" clearable size="small">
                <el-option
                  v-for="item in orderMediumOptions"
                  :key="item.dictLabel"
                  :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>




        <el-row :gutter="20">
          <el-col :span="6">
            <!-- 查询方式 下单时间 发货时间 -->
            <el-form-item label="下单时间:">
              <el-select v-model="queryType" placeholder="查询方式" size="small">
                <el-option
                  v-for="item in queryTypes"
                  :key="item.dictLabel"
                  :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>

          </el-col>
          <el-col :span="6">
            <el-form-item label="筛选日期" prop="createTime">
              <el-date-picker clearable size="small" style="width: 220px"
                v-model="dateRange"
                type="daterange"
                value-format="yyyy-MM-dd"
                        start-placeholder="开始日期" end-placeholder="结束日期"
                        >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <!-- 实收金额 金额等于0 金额大于0 -->
            <el-form-item label="实收金额:">
              <el-select v-model="amountType" placeholder="请选择金额" clearable size="small">
                <el-option
                  v-for="item in amountTypes"
                  :key="item.dictLabel"
                  :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>

          </el-col>
          <el-col :span="6">

          </el-col>
        </el-row>


        
        <el-form-item>
                    <el-button type="primary" icon="el-icon-search" plain   @click="storeOrderStatistics">搜索</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">
          <!-- 使用组件替换原有表格 -->
          <order-summary-table 
            title="员工下单汇总" 
            :table-data="tableData" 
            nameLable="员工姓名" />
            
          <order-summary-table 
            title="公司下单汇总" 
            :table-data="companyTableData" 
            nameLable="公司" />
            
          <order-summary-table 
            title="部门下单汇总" 
            :table-data="deptTableData" 
            nameLable="部门"/>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import OrderSummaryTable from '../components/OrderSummaryTable';
import { storeOrderStatistics } 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: 'storeOrderStatatic',
  mixins: [resize],
  components: { Treeselect,OrderSummaryTable },
  watch: {
    // 监听deptId
    'deptId': 'currDeptChange'
  },
  data() {
    return {
      queryTypes:[
        { dictLabel: '下单时间', dictValue: 1 },
        { dictLabel: '发货时间', dictValue: 2 }
      ],
      amountTypes:[
        { dictLabel: '金额等于0', dictValue: 1 },
        { dictLabel: '金额大于0', dictValue: 2 }
      ],
      queryType: 1,
      amountType: null,
      companys: [],
      deptOptions: [],
      companyId: undefined,
      deptId: undefined,
      userIds: undefined,
      users: [],
      dateRange: [],
      chart: null,
      orderTypeOptions:[],// 订单类型
      orderType:'',
      orderMediumOptions:[], // 媒体来源
      orderMedium:'',
      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: [],
      // 新增表格数据
      tableData: [],        // 员工下单汇总
      companyTableData: [], // 公司下单汇总
      deptTableData: []     // 部门下单汇总
    }
  },
  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;
    });
    // 媒体来源
    this.getDicts("crm_customer_source").then((response) => {
      this.orderMediumOptions = 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.storeOrderStatistics()
        }
      });
    },
    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 }
      }
      exportVoiceLogs(data).then((response) => {
        console.log(response)
        this.download(response.msg);
      });
    },
    getUserListByDeptId() {
      this.userIds = undefined;
      var data = { deptId: this.deptId };
      getUserListByDeptId(data).then(response => {
        this.users = response.data;
      });
    },
    storeOrderStatistics() {
      var data={};
      if(this.value){
        data.type = this.value
      }
      if(this.userIds){
        data.companyUserId = this.userIds
      }

      if(this.queryType){
        data.queryType = this.queryType
      }
      if(this.amountType){
        data.amountType = this.amountType
      }

      if(this.dateRange && this.dateRange.length>0){
        data.type = null
        data.startTime = this.dateRange[0]
        data.endTime = this.dateRange[1]
      }
      if(this.orderType){
        data.orderType = this.orderType
      }
      if(this.orderMedium){
        data.orderMedium = this.orderMedium
      }
      if(this.companyId){
        data.companyId = this.companyId
      }
      if(this.deptId){
        data.deptId = this.deptId
      }
      storeOrderStatistics(data).then((response) => {
        this.dates = response.dates;
        this.orderCount = response.orderCount;
        this.payPrice = response.payPrice;
        //表格数据
        this.tableData = response.userTableData || [];
        this.companyTableData = response.companyTableData || [];
        this.deptTableData = response.deptTableData || [];

        // setTimeout(() => {
        //   this.initEchart();
        // }, 500);
      });
    },
    initEchart() {
      var option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | '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);
    },
    // 表格行样式
    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;
  height: calc(100vh - 24px); // 设置容器高度
  display: flex;
  flex-direction: column;
  
  .app-content {
    background-color: white;
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    
    .title {
      padding: 20px 30px 0px 30px;
      font-size: 18px;
      font-weight: bold;
      color: black;
    }
    
    .search-form {
      margin: 20px 30px 0px 30px;
      position: sticky;
      top: 0;
      background-color: white;
      z-index: 100;
      padding: 20px 30px 0px 30px;
      margin: 0 30px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      flex-shrink: 0; // 防止收缩
    }
    
    .data-box {
      padding: 30px;
      background-color: rgb(255, 255, 255);
      flex: 1;
      overflow-y: auto; // 添加垂直滚动条
      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;
        }
      }
    }
  }
}

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