<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="120px"
    >
      <el-form-item label="客户" prop="name">
        <el-select
          v-model="queryParams.searchtype"
          clearable
          style="width: 100px"
        >
          <el-option
            v-for="dict in SearchTypeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <el-input
          style="width: 200px"
          v-model="queryParams.name"
          placeholder="请输入客户姓名/编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门" v-show="showDept">
        <treeselect
          v-model="queryParams.deptid"
          :options="deptOptions"
          :show-count="true"
          :multiple="true"
          :placeholder="$t('请选择部门')"
          :normalizer="normalizer"
        />
      </el-form-item>
      <el-form-item
        label="客户经理"
        prop="salesmanid"
        v-show="showCustomsManage"
      >
        <el-select
          clearable
          :multiple="true"
          v-model="queryParams.salesmanid"
          :placeholder="$t('请选择客户经理')"
          size="small"
        >
          <el-option
            v-for="dict in customerServiceList"
            :key="dict.id"
            :label="dict.nickname"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="首次成交" prop="delFlag">
        <el-select v-model="queryParams.first" clearable style="width: 200px">
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户业绩类型" prop="remark">
        <el-select
          v-model="queryParams.cusYjType"
          clearable
          style="width: 200px"
        >
          <el-option label="新客户" value="1"></el-option>
          <el-option label="老客户" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户来源" prop="remark">
        <el-select
          v-model="queryParams.source"
          :multiple="true"
          :placeholder="$t('请选择客户来源')"
        >
          <el-option
            v-for="dict in getDictDatas(DICT_TYPE.CUSTOMER_SOURCE)"
            :key="dict.value"
            :label="isChinese ? dict.label : dict.labelEn"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户角色" prop="customerrole">
        <el-select
          v-model="queryParams.customerrole"
          clearable
          :multiple="true"
          style="width: 200px"
        >
          <el-option
            v-for="dict in getDictDatas(DICT_TYPE.CUSTOMER_TYPE)"
            :key="dict.value"
            :label="isChinese ? dict.label : dict.labelEn"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户国家" prop="country">
        <el-select
          clearable
          :multiple="true"
          v-model="queryParams.country"
          :placeholder="$t('请选择国家')"
        >
          <el-option
            v-for="dict in countryList"
            :key="dict.id"
            :label="isChinese ? dict.nameZh : dict.nameEn"
            :value="parseInt(dict.id)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="总V值" prop="searchDataType1">
        <el-select
          v-model="queryParams.searchDataType1"
          clearable
          style="width: 130px"
        >
          <el-option
            v-for="dict in SearchDataTypeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <el-input
          v-model="queryParams.searchData1"
          style="width: 130px"
          placeholder="请输入数值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="海运拼柜" prop="searchDataType2">
        <el-select
          v-model="queryParams.searchDataType2"
          clearable
          style="width: 130px"
        >
          <el-option
            v-for="dict in SearchDataTypeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <el-input
          v-model="queryParams.searchData2"
          style="width: 130px"
          placeholder="请输入数值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="专线空运" prop="searchDataType3">
        <el-select
          v-model="queryParams.searchDataType3"
          clearable
          style="width: 130px"
        >
          <el-option
            v-for="dict in SearchDataTypeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <el-input
          v-model="queryParams.searchData3"
          style="width: 130px"
          placeholder="请输入数值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户创建时间">
        <el-date-picker
          v-model="queryParams.sdate4"
          type="date"
          style="width: 130px"
          value-format="yyyy-MM-dd"
          clearable
          placeholder="起始日期"
        />
        <el-date-picker
          v-model="queryParams.edate4"
          type="date"
          style="width: 130px"
          value-format="yyyy-MM-dd"
          clearable
          placeholder="截止日期"
        />
      </el-form-item>
      <el-form-item label="首次成交时间">
        <el-date-picker
          v-model="queryParams.sdate5"
          type="date"
          style="width: 130px"
          value-format="yyyy-MM-dd"
          clearable
          placeholder="起始日期"
        />
        <el-date-picker
          v-model="queryParams.edate5"
          type="date"
          style="width: 130px"
          value-format="yyyy-MM-dd"
          clearable
          placeholder="截止日期"
        />
      </el-form-item>
      <el-form-item label="业绩产生时间" prop="searchDateType">
        <el-date-picker
          v-model="queryParams.sdate"
          type="date"
          style="width: 130px"
          value-format="yyyy-MM-dd"
          clearable
          placeholder="起始日期"
        />
        <el-date-picker
          v-model="queryParams.edate"
          type="date"
          style="width: 130px"
          value-format="yyyy-MM-dd"
          clearable
          placeholder="截止日期"
        />
      </el-form-item>
      <el-form-item label="同比年份" prop="duibiYear">
        <el-date-picker
          v-model="queryParams.duibiYear"
          type="year"
          style="width: 130px"
          value-format="yyyy"
          placeholder="请选择同比年份"
        />
      </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-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          :loading="exportLoading"
          v-show="false"
        >
          {{ $t("导出") }}</el-button
        >
        <el-button type="primary" size="mini" @click="test" v-show="false">
          测试
        </el-button>

        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport2"
          :loading="exportLoading"
          v-show="objEcwReportPermission.exportdataq == 1"
        >
          {{ $t("导出") }}</el-button
        >
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="list" @sort-change="handleSort">
      <el-table-column label="排名" align="center" prop="px" />
      <el-table-column label="客户编号" align="center" prop="number">
        <template slot-scope="{ row }">
          <el-link
            type="primary"
            @click.native="$router.push('/customer/query/' + row.id)"
            >{{ row.number }}</el-link
          >
        </template>
      </el-table-column>
      <el-table-column label="客户姓名" align="center" prop="name" />
      <el-table-column label="客户经理" align="center" prop="salesman" />
      <el-table-column label="部门" align="center" prop="deptname" />
      <el-table-column
        label="总V值"
        align="center"
        prop="allsumvolume"
        sortable="allsumvolume"
      />
      <el-table-column
        label="总V值同比"
        align="center"
        prop="allsumvolumeTbShow"
      />

      <el-table-column
        label="海运拼柜"
        align="center"
        prop="sumvolumeV1"
        sortable="sumvolumeV1"
      />
      <el-table-column label="海运占比" align="center" prop="seaZb" />
      <el-table-column
        label="海运拼柜同比"
        align="center"
        prop="sumvolumeTbShow1"
      />

      <el-table-column
        label="专线空运"
        align="center"
        prop="sumweightV3"
        sortable="sumweightV3"
      />
      <el-table-column label="空运占比" align="center" prop="airZb" />
      <el-table-column
        label="专线空运同比"
        align="center"
        prop="sumweightTbShow3"
      />

      <el-table-column label="月均" align="center" prop="monthAvg" />
      <el-table-column label="月均同比" align="center" prop="monthAvgTbShow" />
      <el-table-column label="海运月均方数" align="center" prop="seaMonthAvg" />
      <el-table-column
        label="海运月均同比"
        align="center"
        prop="seaMonthAvgTb"
      />
      <el-table-column label="空运月均重量" align="center" prop="airMothAvg" />
      <el-table-column
        label="空运月均同比"
        align="center"
        prop="airMothAvgTb"
      />
      <el-table-column label="重货总V值" align="center" prop="weightSumV" />
      <el-table-column label="重货占比" align="center" prop="weithtSumZb" />
      <el-table-column label="泡货总V值" align="center" prop="phSumV" />
      <el-table-column label="泡货占比" align="center" prop="phSumZb" />
      <el-table-column label="控货总V值" align="center" prop="khSumV" />
      <el-table-column label="控货占比" align="center" prop="khSumZb" />
      <!--2024-05-06和张工确认这几个参数无取数逻辑，暂时隐藏-->
      <!--
      <el-table-column
        label="是否首次成交"
        v-show="false"
        align="center"
        prop="isFirst"
      />
      <el-table-column
        label="首次成交时间"
        v-show="false"
        align="center"
        prop="firstDate"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.firstDate) }}</span>
        </template>
      </el-table-column>-->
      <!--2024-05-06和张工确认这几个参数无取数逻辑，暂时隐藏-->
      <el-table-column label="提货率" align="center" prop="thL" />
      <el-table-column label="客户业绩类型" align="center" prop="cusYjType" />
      <el-table-column label="客户来源" align="center" prop="sourcename" />
      <el-table-column label="客户角色" align="center" prop="customerrole" />
      <el-table-column label="客户国家" align="center" prop="country" />
      <el-table-column
        label="客户创建时间"
        align="center"
        prop="createtime"
        width="200px"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createtime) }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

  <script>
//国家列表接口
import { getCountryListAll } from "@/api/ecw/country";
import { DICT_TYPE, getDictDatas, getDictDatas2 } from '@/utils/dict'
import UserSelector from "@/components/UserSelector";
import { listServiceUser2 } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
//自定义目录数样式
import "@/assets/styles/vue-treeselect.css";
import { listSimpleDepts } from "@/api/system/dept";
import {
  getListPage,
  exportExcel,
  exportExcel2,
} from "@/api/report/customeranalysis";
import {
  getCurUserPermission,
  getDeptChild,
  listServiceUser,
} from "@/api/report/EcwReportPermission";
import { MessageBox } from "element-ui";

function currentTime2() {
  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 day = date.getDay();
  let strDate = year + "-" + month + "-" + day;
  return strDate;
}

function formatDate2() {
  var date = new Date();
  const day = date.getDate().toString().padStart(2, "0");
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  // 月份是从0开始的
  const year = date.getFullYear();
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  const seconds = date.getSeconds().toString().padStart(2, "0");
  //`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  return `${year}-${month}-${day}`;
}

function formatDate3() {
  var date = new Date();
  // 月份是从0开始的
  const year = date.getFullYear();
  return `${year}-01-01`;
}

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

//获取月份的最后一天 lanbm 2024-04-27 add
function getLastDay(sDate) {
  var date = new Date(sDate);
  var year = date.getFullYear();
  //月份从0开始计算，需要加1
  var month = date.getMonth() + 1;
  var lastDay = new Date(year, month, 0).getDate();
  return lastDay;
}

//2024-05-01合并
export default {
  name: "ReportCustomer_analysisIndex",
  components: {
    UserSelector,
    Treeselect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      getDictDatas2,
      getDictDatas,
      DICT_TYPE,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      showDept: true, //是否显示部门选择过滤条件
      showCustomsManage: true, //是否显示客户经理过滤条件
      deptOptions: undefined,
      // 总条数
      total: 0,
      // 测试列表
      list: [],
      countryList: [], //国家列表
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dateRangeCreateTime: [],
      SearchTypeList: [
        { value: "in", label: "包含" },
        { value: "notin", label: "不包含" },
        { value: "eq", label: "等于" },
        { value: "noeq", label: "不等于" },
      ],
      // 禁止选择超出当前日期
      pickerOptions: {
        disabledDate(time) {
          const _now = Date.now();
          return time.getTime() <= _now;
        },
      },
      SearchDataTypeList: [
        { value: "1", label: "大于等于" },
        { value: "2", label: "等于" },
        { value: "3", label: "小于等于" },
      ],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        searchtype: undefined,
        name: undefined, //客户姓名
        number: undefined, //客户编号
        salesmanid: undefined, //客户经理
        deptid: undefined, //部门
        country: undefined, //客户国家
        source: undefined, //客户来源
        customerrole: undefined, //客户角色
        first: undefined, //是否首次成交
        cusYjType: undefined, //客户业绩类型，新客户还是老客户
        searchDataType1: undefined, //查询数据类型
        searchData1: undefined, //总V值查询
        searchDataType2: undefined, //海运拼柜
        searchData2: undefined, //海运拼柜
        searchDataType3: undefined, //专线空运
        searchData3: undefined, //专线空运
        searchDataType4: undefined, //时间筛选
        searchDateType: "createdate", //日期查询类型
        sdate: formatDate3(), //开始日期
        edate: formatDate2(), //结束日期
        duibiYear: getLastYear(), //对比年份
        sdate4: undefined, //客户创建时间
        edate4: undefined, //客户创建时间
        sdate5: undefined, //首次成交时间
        edate5: undefined, //首次成交时间
        orderfield:null,//排序字段
        ordertype:null,//排序方式
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      //报表权限信息
      objEcwReportPermission: {},
      DeptEx: { id: undefined, name: undefined, parentId: undefined },
      ParentPar: {},
      customerServiceList: [],
    };
  },
  created() {
    getCountryListAll().then((r) => {
      this.countryList = r.data;
    });

    listServiceUser2().then((r) => {
      this.customerServiceList = r.data;
    });
    this.doLoadData();
  },
  watch: {
    $route(to) {
      //lanbm 2024-05-06 解决重新进入参数不刷新的问题
      //this.$route.name == "客户分析" 用name做逻辑判断，有时候菜单名称会变化
      //"/report/customer_analysis"  调整为根据path做逻辑判断
      if (this.$route.path == "/report/customer_analysis") {
        this.doLoadData();
      }
    },
  },
  computed: {
    //这几个函数的执行顺序
    //created ------> computed ------> mounted ------> watch
  },
  methods: {
    handleSort(obj) {
      if (obj.order != null && obj.prop != null) {
        this.queryParams.orderfield=obj.prop;  //排序字段
        this.queryParams.ordertype=obj.order;   //排序方式
        this.getList();
      }
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      // 执行查询
      if (this.objEcwReportPermission.permissionFw == 1) {
        //只能看自己的，不能选择部门和客户经理
        this.queryParams.salesmanid = this.objEcwReportPermission.userId;
      } else if (this.objEcwReportPermission.permissionFw == 2) {
        //部门权限
        this.queryParams.deptid = parseInt(this.objEcwReportPermission.deptId);
      } else if (this.objEcwReportPermission.permissionFw == 3) {
        //全公司权限
      }
      getListPage(this.queryParams).then((response) => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    doLoadData() {
      //获取当前用户报表权限
      getCurUserPermission().then((response) => {
        //复制对象
        Object.assign(this.objEcwReportPermission, response.data);
        //this.objEcwReportPermission = response.data;
        if (this.objEcwReportPermission.permissionFw == 1) {
          //只能看自己的，不能选择部门和客户经理
          this.showCustomsManage = false;
          this.showDept = false;
        }
        //获取页面传参
        let sSalesmanid = this.$route.query.salesmanid;
        let sDeptid = this.$route.query.deptid;
        let s = this.$route.query.sDate;
        let e = this.$route.query.eDate;
        let bd = this.$route.query.duibiYear;
        //客户编号
        let number = this.$route.query.number;
        if (sSalesmanid != undefined && sSalesmanid != null) {
          this.queryParams.salesmanid = parseInt(sSalesmanid);
        }
        if (sDeptid != undefined && sDeptid != null) {
          this.queryParams.deptid = parseInt(sDeptid);
        }
        if (s != undefined && s != null) {
          this.queryParams.sdate = s + "-01";
        }
        if (e != undefined && s != null) {
          let lastDay = getLastDay(e + "-01");
          this.queryParams.edate = e + "-" + lastDay;
        }
        if (bd != undefined && bd != null) {
          this.queryParams.duibiYear = bd;
        }
        if (number != undefined && number != null) {
          this.queryParams.searchtype = "eq";
          this.queryParams.name = number;
        }
        this.getTreeselect();
        this.getList();
      });
    },
    isChinese() {
      //基础函数，判断系统显示语言是中文还是英文
      return this.$i18n.locale === "zh_CN";
    },
    handleView(row) {
      //查看客户详情
      this.$router.push("/customer/query/" + row.id);
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    resetQuery() {
      this.queryParams = {
        pageNo: 1,
        pageSize: 10,
        searchtype: undefined,
        name: undefined, //客户姓名
        number: undefined, //客户编号
        salesmanid: undefined, //客户经理
        deptid: undefined, //部门
        country: undefined, //客户国家
        source: undefined, //客户来源
        customerrole: undefined, //客户角色
        first: undefined, //是否首次成交
        cusYjType: undefined, //客户业绩类型，新客户还是老客户
        searchDataType: undefined, //查询数据类型
        searchDateType: undefined, //日期查询类型
        sdate: undefined, //开始日期
        edate: undefined, //结束日期
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (this.isRightPar() == true) {
        this.queryParams.pageNo = 1;
        this.getList();
      }
    },
    isRightPar() {
      if (
        this.queryParams.sdate == undefined ||
        this.queryParams.sdate == null ||
        this.queryParams.sdate == ""
      ) {
        MessageBox("请输入开始日期。");
        return false;
      }
      if (
        this.queryParams.edate == undefined ||
        this.queryParams.edate == null ||
        this.queryParams.edate == ""
      ) {
        MessageBox("请输入结束日期。");
        return false;
      }

      if (
        this.queryParams.duibiYear == undefined ||
        this.queryParams.duibiYear == null ||
        this.queryParams.duibiYear == ""
      ) {
        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;
    },
    /** 导出按钮操作 */
    handleExport() {
      if (this.isRightPar() == false) return;
      // 执行导出
      this.$modal
        .confirm("是否确认导出所有数据项?")
        .then(() => {
          this.exportLoading = true;
          return exportExcel(this.queryParams);
        })
        .then((response) => {
          this.$download.excel(response, "客户分析报表.xls");
          this.exportLoading = false;
        })
        .catch(() => {
          this.exportLoading = false;
        });
    },
    handleExport2() {
      if (this.isRightPar() == false) return;
      this.$modal
        .confirm("是否确认导出所有数据项?")
        .then(() => {
          this.exportLoading = true;
          return exportExcel2(this.queryParams);
        })
        .then((response) => {
          //放入后台队列需要注释此行代码
          //this.$download.excel(response, "客户分析报表.xls");
          this.exportLoading = false;
          this.$message.success(
            this.$t("已加入导出队列，请稍后在下载日志中下载")
          );
        })
        .catch(() => {
          this.exportLoading = false;
        });
    },

    /** 查询部门下拉树结构 + 岗位下拉 */
    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) => {
          this.deptOptions = [];
          this.deptOptions.push(...this.handleTree(response.data, "id"));
        });
      }
    },
    //格式化部门的下拉框
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    getNowDate() {
      let now = new Date();
      year = now.getFullYear();
      month = (now.getMonth() + 1).toString().padStart(2, "0"); //得到月份
      day = now.getDate().toString().padStart(2, "0"); //得到日期
      let strDate = year + "-" + month + "-" + day;
      return strDate;
    },
    test() {
      //当前路径
      let sP = this.$route.path;
      alert(sP);
      //当前参数
      let sPar = this.$route.params;
      alert(sPar);
      //路由名称
      let sRoute = this.$route.name;
      alert(sRoute);
      //路由查询参数
      let sQ = this.$route.query;
      alert(sQ.toString());
      //路由匹配项
      let sM = this.$route.matched;
      alert(sM.toString());

      return;

      this.DeptEx.id = this.objEcwReportPermission.deptId;
      listServiceUser(this.DeptEx).then((response) => {
        let json1 = JSON.stringify(response.data);
        alert(json1);
        return;
      });

      let json1 = JSON.stringify(this.deptOptions);
      alert(json1);
      return;

      //对象的拷贝 lanbm 2024-04-19 add
      let target = {};
      let source = { c: 3 };
      Object.assign(target, source);

      let json = JSON.stringify(this.objEcwReportPermission);
      alert(json);
    },
  },
};
</script>
