<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="selDate">
        <el-date-picker
          v-model="queryParams.sDate"
          type="month"
          value-format="yyyy-MM"
          clearable
          placeholder="请输起始月"
        />
        <el-date-picker
          v-model="queryParams.eDate"
          type="month"
          value-format="yyyy-MM"
          clearable
          placeholder="请输截止月"
        />
      </el-form-item>
      <el-form-item label="同比年份" prop="duibiYear">
        <el-date-picker
          v-model="queryParams.duibiYear"
          type="year"
          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">{{
          $t("搜索")
        }}</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">
          {{ $t("重置") }}</el-button
        >
      </el-form-item>
      <el-form-item> </el-form-item>
    </el-form>
    <el-row>
      <el-form size="small" :inline="true" label-width="150px">
        <el-form-item label="">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="hhandleQueryAnalysis"
          >
            {{ $t("更多") }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <div
      ref="mainBar"
      :class="className"
      :style="{ height: height, width: width }"
    ></div>
    <!--
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />-->
  </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 * as echarts from "echarts";
require("echarts/theme/macarons");
import resize from "../../dashboard/mixins/resize";
import { getReportResult } from "@/api/report/customerreport";
import {
  getCurUserPermission,
  getDeptChild,
} from "@/api/report/EcwReportPermission";
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();
}

//2024-05-01合并
export default {
  name: "ReportCustomerreportIndex",
  components: {
    UserSelector,
    Treeselect,
  },
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "500px",
    },
    autoResize: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 总条数
      total: 0,
      // 显示搜索条件
      showSearch: true,
      showDept: true, //是否显示部门选择过滤条件
      showCustomsManage: true, //是否显示客户经理过滤条件
      deptOptions: undefined,
      chart: null,
      dateRangeCreateTime: [],
      queryParams: {
        sDate: CurDate.getFullYear() + "-01",
        eDate: currentTime(), //结束日期
        duibiYear: getLastYear(), //对比年份
        deptid: undefined, //部门
        salesmanid: undefined, //客户经理
        number: undefined, //客户编号
        pageNo: 1,
        pageSize: 30,
      },
      //报表权限信息
      objEcwReportPermission: {},
      DeptEx: { id: undefined, name: undefined, parentId: undefined },
      resultList: [],
    };
  },
  watch: {},
  mounted() {
    /*
    this.$nextTick(() => {
      this.initChart();
    });*/
  },
  created() {
    //获取当前用户报表权限
    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.initChart();
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      var chartDom = this.$refs["mainBar"];
      this.chart = echarts.init(chartDom, "macarons");
      this.chart.on("click", (params) => {
        if (this.isRight() == false) return;
        let p = {};
        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/customer_analysis",
          query: p,
        });
      });
      this.setOptions();
    },
    setOptions() {
      this.loading = true;
      getReportResult(this.queryParams).then((response) => {
        //全部列表数据
        this.total = response.data.total;
        this.resultList = response.data.resultList;
        let resultList2 = response.data.resultList;
        this.loading = false;
        this.chart.setOption({
          title: {
            text: "客户贡献排名",
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "shadow",
            },
            // 自定义提示框内容，使用回调函数
            formatter: function (params) {
              //params 是一个数组，数组中每个元素代表一个系列的数据信息
              var result = "";
              params.forEach(function (item) {
                //var s=JSON.stringify(item);
                //alert(s);
                //在数据中查询
                let sN = item.name;
                var arr = sN.split("_");
                let vR = resultList2.filter((r) => r.number === arr[1]);
                result += "客户：" + item.name + "<br/>";
                result += "客户编号：" + vR[0].number + "<br/>";
                result += "客户经理：" + vR[0].salesman + "<br/>";
                result += "总V值：" + item.value + "<br/>";
                result += "海运V值：" + vR[0].sumvolume1 + "<br/>";
                result += "空运V值：" + vR[0].sumweight3 + "<br/>";
                result += "对比年份：" + vR[0].duibiYear + "<br/>";
                result += "同比：" + vR[0].allsumvolumeTbMsg + "<br/>";
                result += "环比：" + vR[0].allsumvolumeTbMsg + "<br/>";
              });
              return result;
            },
          },
          legend: {},
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
          },
          xAxis: {
            type: "value",
            boundaryGap: [0, 0.5],
          },
          yAxis: response.data.objyAxis,
          series: response.data.obSseries,
        });
      });
    },

    hhandleQueryAnalysis() {
      if (this.isRight() == false) return;
      let p = {};
      Object.assign(p, this.queryParams);
      this.$router.push({
        path: "/report/customer_analysis",
        query: p,
      });
    },
    isRight() {
      //校验查询参数 lanbm 2024-04-07 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;
    },
    handleQuery() {
      if (this.isRight() == false) return;
      //查询统计结果
      this.initChart();
    },
    getList() {
      //this.initChart();
    },
    resetQuery() {
      this.queryParams = {
        sDate: undefined, //开始日期
        eDate: undefined, //结束日期
        duibiYear: undefined, //对比年份
        deptid: undefined, //部门
        salesmanid: undefined, //客户经理
        pageNo: 1,
        pageSize: 30,
      };
    },
    handleAdd() {},
    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>
      