<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="选择日期" prop="DateQuery">
        <el-date-picker
          v-model="queryParams.sDate"
          type="month"
          style="width: 150px"
          value-format="yyyy-MM"
          clearable
          placeholder="请输起始月"
        />
        <el-date-picker
          v-model="queryParams.eDate"
          type="month"
          style="width: 150px"
          value-format="yyyy-MM"
          clearable
          placeholder="请输截止月"
        />
      </el-form-item>
      <el-form-item label="同比年份" prop="duibiYear">
        <el-date-picker
          v-model="queryParams.duibiYear"
          type="year"
          style="width: 150px"
          value-format="yyyy"
          placeholder="请选择同比年份"
        />
      </el-form-item>

      <el-form-item label="部门" prop="deptid" v-show="showDept">
        <treeselect
          v-model="queryParams.deptid"
          :options="deptOptions"
          :show-count="true"
          :placeholder="$t('请选择部门')"
          :normalizer="normalizer"
        />
      </el-form-item>
      <el-form-item
        label="客户经理"
        prop="salesmanid"
        v-show="showCustomsManage"
      >
        <user-selector
          manage
          v-model="queryParams.salesmanid"
          clearable
          @change="handleQuery"
          :prepend="{ id: 0, nickname: $t('未分配客户经理') }"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="panel-group" style="margin: 5px">
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel" @click="handleGoTo">
          <div class="card-panel-description">
            <div class="card-panel-text">
              {{ $t("业绩总览 Total") }}
            </div>
            <div class="card-panel-num">
              {{ SalesReportCountList1.curValue }}V
            </div>
            <div style="text-align: right">
              同比：{{ SalesReportCountList1.tbShow }}
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel" @click="handleGoTo">
          <div class="card-panel-description">
            <div class="card-panel-text">
              {{ $t("海运拼柜") }}
            </div>
            <div class="card-panel-num">
              {{ SalesReportCountList2.curValue }}M3
            </div>
            <div style="text-align: right">
              同比：{{ SalesReportCountList2.tbShow }}
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel" @click="handleGoTo">
          <div class="card-panel-description">
            <div class="card-panel-text">
              {{ $t("专线空运") }}
            </div>
            <div class="card-panel-num">
              {{ SalesReportCountList3.curValue }}KG
            </div>
            <div style="text-align: right">
              同比：{{ SalesReportCountList3.tbShow }}
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="10" class="panel-group" style="margin: 5px">
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel" @click="handleGoTo">
          <div class="card-panel-description">
            <div class="card-panel-text">
              {{ $t("成交总览 Total") }}
            </div>
            <div class="card-panel-num">
              {{ sumCustomerObject.sumCustomerCount }}
            </div>
            <div style="text-align: right">
              同比：{{ sumCustomerObject.tbShow }}
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel" @click="handleGoTo">
          <div class="card-panel-description">
            <div class="card-panel-text">
              {{ $t("首次成交") }}
            </div>
            <div class="card-panel-num">
              {{ fisCustomerObject.sumCustomerCount }}
            </div>
            <div style="text-align: right">
              同比：{{ fisCustomerObject.tbShow }}
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <div
      ref="mainBar"
      :class="className"
      :style="{ height: height, width: width }"
    />
  </div>
</template>
      
<script>
import UserSelector from "@/components/UserSelector";
import Treeselect from "@riophae/vue-treeselect";
//自定义目录数样式
import "@/assets/styles/vue-treeselect.css";
import { listSimpleDepts } from "@/api/system/dept";
//报表权限接口
import {
  getCurUserPermission,
  getDeptChild,
} from "@/api/report/EcwReportPermission";
import {
  SalesReportCount,
  FirstCustomerCount,
  CustomerTargetCount,
  getEChartData,
} from "@/api/report/salesreport";
import * as echarts from "echarts";
require("echarts/theme/macarons");
import resize from "../../dashboard/mixins/resize";
import SalesPanelGroup from "../../dashboard/SalesPanelGroup";
import { MessageBox } from "element-ui";

const CurDate = new Date();
function currentTime() {
  var date = new Date();
  var year = date.getFullYear();
  //月份从0~11，所以加一
  let month = date.getMonth() + 1;
  //如果格式是MM则需要此步骤，如果是M格式则此处注释掉
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  let strDate = year + "-" + month;
  return strDate;
}

function getLastYear() {
  //获取上一年份
  var date = new Date();
  date.setFullYear(date.getFullYear() - 1);
  let year = date.getFullYear();
  return year.toString();
}
function goPage() {
  alert(11);
}

//2024-05-01合并
//https://2zmzrd.axshare.com  报表原型地址
export default {
  name: "ReportSalesreportIndex",
  components: {
    SalesPanelGroup,
    UserSelector,
    Treeselect,
  },
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "1000px",
    },
    autoResize: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      showCustomsManage: true, //是否显示客户经理查询条件
      showDept: true, //是否显示部门查询条件
      chart: null,
      SalesReportCountList3: {},
      SalesReportCountList2: {},
      SalesReportCountList1: {},
      salesReportRespAll: [],
      sumCustomerObject: {}, //成交客户总数
      fisCustomerObject: {}, //首次成交客户户数
      dateRangeCreateTime: [],
      SalesReportRespShow: [],
      queryParams: {
        salesmanid: undefined, //销售经理
        deptid: undefined, //部门
        sDate: CurDate.getFullYear() + "-01", //开始日期
        eDate: currentTime(), //结束日期
        duibiYear: getLastYear(), //对比年份
      },
      deptOptions: [],
      deptData: [],
      //报表权限信息
      objEcwReportPermission: {},
    };
  },
  watch: {},
  mounted() {},
  created() {
    this.handleQuery();
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    getDept() {
      listSimpleDepts().then((response) => {
        //this.deptData.add
      });
    },
    getSalesReportCount() {
      //获取运输方式统计数 lanbm 2024-04-01 add
      //数据遍历参考地址
      //https://blog.csdn.net/weixin_49826079/article/details/132172368
      SalesReportCount(this.queryParams).then((response) => {
        this.SalesReportCountList1 = response.data[0];
        this.SalesReportCountList2 = response.data[1];
        this.SalesReportCountList3 = response.data[2];
      });
    },
    getCustomerTargetCount() {
      CustomerTargetCount(this.queryParams).then((response) => {
        this.sumCustomerObject = response.data;
      });
    },
    getFirstCustomerCount() {
      //获取首次成交客户数 lanbm 2024-04-01 add
      FirstCustomerCount(this.queryParams).then((response) => {
        //首次成交客户数
        this.fisCustomerObject = response.data;
      });
    },
    // 柱状图
    createChart() {
      getEChartData(this.queryParams).then((response) => {
        //图表参考网址
        //https://blog.csdn.net/m0_65983287/article/details/133909409
        let salesReportRespAll1 = response.data.salesReportRespAll;
        var chartDom = this.$refs["mainBar"];
        this.chart = echarts.init(chartDom, "macarons");
        this.chart.on("click", (params) => {
          if (this.isRight() == false) return;
          let p = {};
          if (params.componentType === "title") {
            this.$router.push({
              path: "/report/sales_analysis",
              query: p,
            });
            return;
          }

          /*
          this.queryParams.salesmanid = parseInt(
            this.resultList[params.dataIndex].salesmanid
          );
          this.queryParams.number = this.resultList[params.dataIndex].number;
          Object.assign(p, this.queryParams);*/
          this.$router.push({
            path: "/report/sales_analysis",
            query: p,
          });
        });
        this.option = {
          title: {
            text: "月度业绩分布", //主标题
            link: "", //主标题链接
            target: "self", //窗口打开方式self本窗口，blank新窗口
            textStyle: {
              //color: "skyblue", //主标题颜色
              fontSize: "20", //主标题大小
            },
            subtext: "更多...", //副标题
            sublink: "javascript:goPage()", //副标题链接
            subtarget: "self", //self/blank
            subtextStyle: {
              //color: "#0f0",
              fontSize: "10",
              textAlign: "right",
            },
            left: "left", //位置
            show: true, //是否显示true/false
            textAlign: "left", //水平对齐：auto/left,right,center
            textVerticalAlign: "auto", //垂直对齐：auto，top,middle,bottom
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "shadow",
            },
            formatter: function (params) {
              //params 是一个数组，数组中每个元素代表一个系列的数据信息
              var result = "";
              params.forEach(function (item) {
                let vR = salesReportRespAll1.filter(
                  (r) => r.strMonth === item.name
                );
                result = "统计月份:" + item.name + "<br/>";
                result +=
                  "Total:" +
                  vR[0].curValue +
                  "   同比：" +
                  vR[0].tbShow +
                  ",环比：" +
                  vR[0].hbShow +
                  "<br/>";
                result +=
                  "海运拼柜:" +
                  vR[0].curValue1 +
                  "   同比：" +
                  vR[0].tbShow1 +
                  ",环比：" +
                  vR[0].hbShow1 +
                  "<br/>";
                result +=
                  "专线空运:" +
                  vR[0].curValue3 +
                  "   同比：" +
                  vR[0].tbShow3 +
                  ",环比：" +
                  vR[0].hbShow3 +
                  "<br/>";
              });
              return result;
            },
          },
          legend: {},
          xAxis: {
            type: "value",
            boundaryGap: [0, 0.5],
          },
          yAxis: {
            type: "category",
            data: response.data.objyAxis.data,
            axisLabel: {
              showMaxLabel: true,
              interval: 0,
              rotate: 0,
            },
          },
          grid: {
            show: false,
            top: "5%",
            right: "5%",
            bottom: "5%",
            left: "10%",
          },
          series: [
            {
              name: "Total",
              data: response.data.obSseries[0].data,
              type: "bar",
              barGap: "0px",
              label: {
                show: true,
                position: "right", //在上方显示
                textStyle: {
                  //数值样式
                  fontSize: "16px",
                  color: "#999",
                },
                formatter: function (d) {
                  return d.data;
                },
              },
            },
            {
              name: "海运拼柜",
              data: response.data.obSseries[1].data,
              type: "bar",
              barGap: "0px",
              label: {
                show: true,
                position: "right", //在上方显示
                textStyle: {
                  //数值样式
                  fontSize: "16px",
                  color: "##999",
                },
                formatter: function (d) {
                  /*
                  let sum =
                    (
                      (d.data / (d.data + res[d.dataIndex].maleCount)) *
                      100
                    ).toFixed(2) + "%";
                    */
                  return d.data;
                },
              },
            },
            {
              name: "专线空运",
              data: response.data.obSseries[2].data,
              type: "bar",
              barGap: "0px",
              label: {
                show: true,
                position: "right", //在上方显示
                textStyle: {
                  //数值样式
                  fontSize: "16px",
                  color: "##999",
                },
                formatter: function (d) {
                  /*
                  let sum =
                    (
                      (d.data / (d.data + res[d.dataIndex].maleCount)) *
                      100
                    ).toFixed(2) + "%";
                    */
                  return d.data;
                },
              },
            },
          ],
        };
        this.option && this.chart.setOption(this.option);
      });
    },
    isChinese() {
      //基础函数，判断系统显示语言是中文还是英文
      return this.$i18n.locale === "zh_CN";
    },
    handleQuery() {
      if (this.isRight() == false) return;
      this.loading = true;
      //获取当前用户报表权限
      getCurUserPermission().then((response) => {
        this.objEcwReportPermission = response.data;
        if (this.objEcwReportPermission.permissionFw == 1) {
          //本人权限
          this.showCustomsManage = false;
          this.showDept = false;
          this.queryParams.salesmanid = this.objEcwReportPermission.userId;
        } else if (this.objEcwReportPermission.permissionFw == 2) {
          //本部门权限
          this.showCustomsManage = true;
          this.showDept = true;
          this.queryParams.deptid = parseInt(
            this.objEcwReportPermission.deptId
          );
        } else if (this.objEcwReportPermission.permissionFw == 3) {
          //全公司权限
          this.showCustomsManage = true;
          this.showDept = true;
        }

        this.getTreeselect();
        this.getSalesReportCount();
        this.getFirstCustomerCount();
        //获取成交客户数，出重结果
        this.getCustomerTargetCount();
        //获取权限后再初始化统计图表
        //this.initChart();
        this.createChart();
        this.loading = false;
      });
    },
    resetQuery() {
      this.queryParams = {
        salesmanid: undefined, //销售经理
        deptid: undefined, //部门
        sDate: undefined, //开始日期
        eDate: undefined, //结束日期
        duibiYear: undefined, //对比年份
      };
    },
    handleGoTo() {
      if (this.isRight() == false) return;
      let p = {};
      Object.assign(p, this.queryParams);
      this.$router.push({
        path: "/report/sales_analysis",
        query: p,
      });
    },
    isRight() {
      //校验查询参数 lanbm 2024-05-09 add
      if (this.queryParams.sDate == undefined) {
        MessageBox("请输入起始月份。");
        return false;
      }
      if (this.queryParams.eDate == undefined) {
        MessageBox("请输入截止月份。");
        return false;
      }
      if (this.queryParams.duibiYear == undefined) {
        MessageBox("请输入对比年份。");
        return false;
      } else {
        let y = parseInt(this.queryParams.duibiYear);
        if (y < 2023) {
          MessageBox("对比年份只能选2023年和2023年之后的年份。");
          return false;
        }
        var date = new Date();
        var year = date.getFullYear();
        if (y > year) {
          MessageBox("对比年份只能选当前年份之前的年份。");
          return false;
        }
      }
      return true;
    },
    handleAdd() {
      alert(1);
    },
    handleExport() {},
    /** 查询部门下拉树结构 + 岗位下拉 */
    getTreeselect() {
      if (this.objEcwReportPermission.permissionFw == 3) {
        listSimpleDepts().then((response) => {
          // 处理deptOptions 参数
          this.deptOptions = [];
          this.deptOptions.push(...this.handleTree(response.data, "id"));
        });
      } else if (this.objEcwReportPermission.permissionFw == 2) {
        this.DeptEx.id = this.objEcwReportPermission.deptId;
        getDeptChild(this.DeptEx).then((response) => {
          // 处理deptOptions 参数
          this.deptOptions = [];
          this.deptOptions.push(...this.handleTree(response.data, "id"));
        });
      }
    },
    //格式化部门的下拉框
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
  },
};
</script>


<style lang="scss" scoped>
.panel-group {
  margin-top: 18px;

  .card-panel-col {
    margin-bottom: 32px;
  }

  .card-panel {
    display: flex;
    justify-content: space-between;
    height: 108px;
    cursor: pointer;
    font-size: 12px;
    position: relative;
    overflow: hidden;
    color: #666;
    background: #fff;
    box-shadow: 4px 4px 40px rgba(0, 0, 0, 0.05);
    border-color: rgba(0, 0, 0, 0.05);

    &:hover {
      .card-panel-icon-wrapper {
        color: #fff;
      }

      .icon-people {
        background: #40c9c6;
      }

      .icon-message {
        background: #36a3f7;
      }

      .icon-money {
        background: #f4516c;
      }

      .icon-shopping {
        background: #34bfa3;
      }
    }

    .icon-people {
      color: #40c9c6;
    }

    .icon-message {
      color: #36a3f7;
    }

    .icon-money {
      color: #f4516c;
    }

    .icon-shopping {
      color: #34bfa3;
    }

    .card-panel-icon-wrapper {
      margin: 14px 0 0 14px;
      padding: 16px;
      transition: all 0.38s ease-out;
      border-radius: 6px;
    }

    .card-panel-icon {
      font-size: 48px;
    }

    .card-panel-description {
      font-weight: bold;
      margin: 10px;
      margin-left: 10px;

      .card-panel-text {
        line-height: 18px;
        color: rgba(0, 0, 0, 0.45);
        font-size: 16px;
        margin-bottom: 12px;
      }

      .card-panel-num {
        font-size: 20px;
      }
    }
  }
}

@media (max-width: 550px) {
  .card-panel-description {
    display: none;
  }

  .card-panel-icon-wrapper {
    float: none !important;
    width: 100%;
    height: 100%;
    margin: 0 !important;

    .svg-icon {
      display: block;
      margin: 14px auto !important;
      float: none !important;
    }
  }
}
</style>
      