<template>
  <div style="width: 100%" v-loading="loading">
    <div class="titles">合同统计</div>
    <div class="warpper">
      <div class="left">
        <div class="date-range">
          <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="monthrange"
            range-separator="-" start-placeholder="开始月份" end-placeholder="结束月份" :default-time="['00:00:00', '23:59:59']"
            @change="queryList"></el-date-picker>
        </div>
        <!-- 每合同额柱状图 -->
        <div class="left-top" id="amountBar"></div>
        <div class="left-bottom">
          <div class="pie1" id="cwamountPie"></div>
          <div class="pie2" id="cwSourcePie"></div>
        </div>
      </div>
      <div class="middle" v-loading="subLoading">
        <div class="middle-top" id="subYearLine"></div>
        <div class="middle-bottom">
          <div class="bottom-left" id="subCwAmountPie"></div>
          <div class="bottom-right" id="subSourcePie"></div>
        </div>
      </div>
      <div class="right"></div>
    </div>
  </div>
</template>

<script>
import { echartsInit } from "@/utils/echarts";
import { getContractStatistic } from "@/api/oa/contract/contract";
import { getSubContractStatistic } from "@/api/oa/contract/subContract";
let amountChart,
  cwAmountChart,
  cwSourceChart,
  subAmountChart,
  subYearChart,
  subCwAmountChart,
  subSourceChart;
export default {
  props: {
    datas: {
      type: Object,
      require: true,
    },
  },
  data() {
    return {
      loading: true,
      dataLoading: true,
      contractAmount: {},
      contractCwAmount: {},
      contractSource: {},
      contractYear: {},
      paidAmount: {},
      paidCwAmount: {},
      paidYear: {},
      subAmount: {},
      subYearNum: {},
      subCwAmount: {},
      subSource: {},
      subPaidAmount: {},
      subPaidCwAmount: {},
      subPaidYear: {},
      subYear: 0,
      sumAomunt: 0,
      sumSubAomunt: 0,
      activeYear: "",
      subLoading: true,
      dateRange: [],
      mainChart: null,
    };
  },
  watch: {
    contractCwAmount() {
      this.initChartCwAomunt(this.activeYear);
    },
    contractSource() {
      this.initChartCwSource(this.activeYear);
    },
    subCwAmount() {
      this.initChartSubCwAomunt(this.activeYear);
    },
    subSource() {
      this.initChartSubCwSource(this.activeYear);
    },
    contractYear() {
      this.initChartSubYear();
    },
    contractAmount() {
      this.initAmountBar();
      let sum = Object.values(this.contractAmount).reduce(
        (accumulator, currentValue) => accumulator + currentValue,
        0
      );
      let subsum = Object.values(this.subAmount).reduce(
        (accumulator, currentValue) => accumulator + currentValue,
        0
      );
      this.sumAomunt = this.getTitleAmount(sum);
      this.sumSubAomunt = this.getTitleAmount(subsum);
    },
    subYearNum() {
      this.initChartSubYear();
    },
    subAmount() {
      this.initAmountBar();
    },
  },
  mounted() {
    this.initDatas();
    this.initChartCwAomunt("");
    this.initChartCwSource("");
  },
  methods: {
    async initDatas() {
      if (Object.keys(this.datas).length !== 0) {
        this.contractAmount = this.datas.yearAmount[0];
        this.contractCwAmount = this.datas.sourceAmount[0];
        this.contractSource = this.datas.sourceCount[0];
        this.contractYear = this.datas.yearCount[0];
        this.paidAmount = this.datas.paidYearAmount[0];
        this.paidCwAmount = this.datas.paidSourceAmount[0];
        this.paidYear = this.datas.paidYearCount[0];
        this.loading = false;
        let sum = Object.values(this.contractAmount).reduce(
          (accumulator, currentValue) => accumulator + currentValue,
          0
        );
        this.sumAomunt = (sum / 100000000).toFixed(2) + "亿元";
      }
      this.subLoading = true;
      let subDatas = await getSubContractStatistic();
      this.subAmount = subDatas.data.yearAmount[0];
      this.subYearNum = subDatas.data.yearCount[0];
      this.subCwAmount = subDatas.data.sourceAmount[0];
      this.subSource = subDatas.data.sourceCount[0];
      this.subPaidAmount = subDatas.data.paidYearAmount[0];
      this.subPaidCwAmount = subDatas.data.paidSourceAmount[0];
      this.subPaidYear = subDatas.data.paidYearCount[0];
      let sum = Object.values(this.subAmount).reduce(
        (accumulator, currentValue) => accumulator + currentValue,
        0
      );
      this.sumSubAomunt = (sum / 100000000).toFixed(2) + "亿元";
      this.initAmountBar();
      this.initChartSubYear();
      this.initChartSubCwAomunt("");
      this.initChartSubCwSource("");
      this.clickYear();
      this.subLoading = false;
    },
    async queryList() {
      let res1 = await getContractStatistic(this.addDateRange({}, this.dateRange));
      let res2 = await getSubContractStatistic(this.addDateRange({}, this.dateRange));
      this.contractCwAmount = res1.data.sourceAmount[0];
      this.contractSource = res1.data.sourceCount[0];
      this.subCwAmount = res2.data.sourceAmount[0];
      this.subSource = res2.data.sourceCount[0];
      if (this.dateRange) {
        this.contractYear = res1.data.monthCount[0];
        this.contractAmount = res1.data.monthAmount[0];
        this.paidAmount = res1.data.paidMonthAmount[0];
        this.paidYear = res1.data.paidMonthCount[0];
      } else {
        this.contractYear = res1.data.yearCount[0];
        this.contractAmount = res1.data.yearAmount[0];
        this.paidAmount = res1.data.paidYearAmount[0];
        this.paidYear = res1.data.paidYearCount[0];
      }
      if (this.dateRange) {
        this.subYearNum = res2.data.monthCount[0];
        this.subAmount = res2.data.monthAmount[0];
        this.subPaidAmount = res2.data.paidMonthAmount[0];
        this.subPaidYear = res2.data.paidMonthCount[0];
      } else {
        this.subYearNum = res2.data.yearCount[0];
        this.subAmount = res2.data.yearAmount[0];
        this.subPaidAmount = res2.data.paidYearAmount[0];
        this.subPaidYear = res2.data.paidYearCount[0];
      }
    },
    getTitleAmount(sum) {
      const units = [
        { value: 1e8, unit: '亿' },
        { value: 1e7, unit: '千万' },
        { value: 1e6, unit: '百万' },
        { value: 1e4, unit: '万' }
      ];
      let amount;
      for (const unit of units) {
        if (sum >= unit.value) {
          amount = (sum / unit.value).toFixed(2) + unit.unit;
          return amount
        }
      }
      return amount = (sum / 1e4).toFixed(2) + '万';
    },
    clickYear() {
      let that = this;
      this.mainChart.on("click", async function (event) {
        if (event) {
          that.activeYear = event.name;
          let year = event.name + "-01-01";
          if (event.name == "") {
            year = "";
          } else if (event.name.includes("月")) {
            return;
          }
          that.dataLoading = true;
          let res1 = await getContractStatistic({ signDate: year });
          let res2 = await getSubContractStatistic({ signDate: year });
          that.contractCwAmount = res1.data.sourceAmount[0];
          that.contractSource = res1.data.sourceCount[0];
          if (event.name != "") {
            that.contractYear = res1.data.monthCount[0];
            that.contractAmount = res1.data.monthAmount[0];
            that.paidAmount = res1.data.paidMonthAmount[0];
            that.paidYear = res1.data.paidMonthCount[0];
          } else {
            that.contractYear = res1.data.yearCount[0];
            that.contractAmount = res1.data.yearAmount[0];
            that.paidAmount = res1.data.paidYearAmount[0];
            that.paidYear = res1.data.paidYearCount[0];
          }

          that.subCwAmount = res2.data.sourceAmount[0];
          that.subSource = res2.data.sourceCount[0];
          if (event.name != "") {
            that.subYearNum = res2.data.monthCount[0];
            that.subAmount = res2.data.monthAmount[0];
            that.subPaidAmount = res2.data.paidMonthAmount[0];
            that.subPaidYear = res2.data.paidMonthCount[0];
          } else {
            that.subYearNum = res2.data.yearCount[0];
            that.subAmount = res2.data.yearAmount[0];
            that.subPaidAmount = res2.data.paidYearAmount[0];
            that.subPaidYear = res2.data.paidYearCount[0];
          }
          that.dataLoading = false;
        }
      });
    },
    initChartSubYear() {
      let yearTitle = this.activeYear ? this.activeYear + "合同数统计" : "合同数统计";
      let option = {
        title: {
          text: yearTitle,
          subtext:
            "承接合同总数：" +
            Object.values(this.contractYear).reduce(
              (accumulator, currentValue) => accumulator + currentValue,
              0
            ) +
            "个" +
            "\n" +
            "分包合同总数：" +
            Object.values(this.subYearNum).reduce(
              (accumulator, currentValue) => accumulator + currentValue,
              0
            ) +
            "个",
        },
        grid: {
          left: "1%",
          right: "1%",
          bottom: "0%",
          height: "60%",
          containLabel: true,
        },
        legend: {},
        graphic: [
          {
            type: "text",
            name: "",
            right: "0",
            top: "20%",
            style: {
              text: "返回",
              fill: "#000", // 文本颜色
              fontSize: 12, // 文本大小
              fontWeight: "", // 文本粗细
            },
          },
        ],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "none",
            label: {
              backgroundColor: "#6a7985",
            },
          },
        },
        xAxis: {
          // name: '',
          type: "category",
          data: Object.keys(this.contractYear),
        },
        yAxis: {
          type: "value",
          name: "单位：元",
        },
        series: [
          {
            name: "承接合同",
            data: Object.values(this.contractYear),
            type: "bar",
            // stack: 'one',
            smooth: true,
            label: {
              show: true,
              position: "top",
            },
          },
          {
            name: "分包合同",
            data: Object.values(this.subYearNum),
            type: "bar",
            // stack: 'two',
            smooth: true,
            label: {
              show: true,
              position: "top",
            },
          },
          {
            name: "已回款",
            data: Object.values(this.paidYear),
            type: "bar",
            // stack: 'one',
            smooth: true,
            label: {
              show: true,
              position: "top",
            },
          },
          {
            name: "已付款",
            data: Object.values(this.subPaidYear),
            type: "bar",
            // stack: 'two',
            smooth: true,
            label: {
              show: true,
              position: "top",
            },
          },
        ],
      };
      this.mainChart = echartsInit(amountChart, "amountBar", option);
    },
    initAmountBar() {
      let yearTitle = this.activeYear ? this.activeYear + "合同额统计" : "合同额统计";
      let option = {
        title: {
          text: yearTitle,
          subtext:
            "承接合同总额：" +
            Object.values(this.contractAmount)
              .reduce((accumulator, currentValue) => accumulator + currentValue, 0)
              .toFixed(2) +
            "元" +
            "(约: " +
            this.sumAomunt +
            ")\n" +
            "分包合同总额：" +
            Object.values(this.subAmount)
              .reduce((accumulator, currentValue) => accumulator + currentValue, 0)
              .toFixed(2) +
            "元" +
            "(约: " +
            this.sumSubAomunt +
            ")",
        },
        legend: {
          right: 0,
        },
        grid: {
          left: "1%",
          right: "1%",
          bottom: "0%",
          height: "60%",
          containLabel: true,
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            label: {
              backgroundColor: "#6a7985",
            },
          },
        },
        xAxis: {
          name: "",
          type: "category",
          data: Object.keys(this.contractAmount),
        },
        yAxis: {
          type: "value",
          name: "单位：元",
        },
        series: [
          {
            name: "承接合同",
            data: Object.values(this.contractAmount),
            type: "line",
            areaStyle: {},
            smooth: true,
            label: {
              show: true,
              position: "top",
              formatter: function (params) {
                var value = params.value;
                const units = [
                  { value: 1e8, unit: '亿' },
                  { value: 1e7, unit: '千万' },
                  { value: 1e6, unit: '百万' },
                  { value: 1e4, unit: '万' }
                ];
                for (const unit of units) {
                  if (value >= unit.value) {
                    return (value / unit.value).toFixed(2) + unit.unit;
                  }
                }
                return (value / 1e4).toFixed(2) + '万';
              },
            },
          },
          {
            name: "分包合同",
            data: Object.values(this.subAmount),
            type: "line",
            areaStyle: {},
            smooth: true,
            label: {
              show: true,
              position: "top",
              formatter: function (params) {
                var value = params.value;
                const units = [
                  { value: 1e8, unit: '亿' },
                  { value: 1e7, unit: '千万' },
                  { value: 1e6, unit: '百万' },
                  { value: 1e4, unit: '万' }
                ];
                for (const unit of units) {
                  if (value >= unit.value) {
                    return (value / unit.value).toFixed(2) + unit.unit;
                  }
                }
                return (value / 1e4).toFixed(2) + '万';
              },
            },
          },
          {
            name: "已回款",
            data: Object.values(this.paidAmount),
            type: "line",
            areaStyle: {},
            smooth: true,
            label: {
              show: true,
              position: "top",
              formatter: function (params) {
                var value = params.value;
                const units = [
                  { value: 1e8, unit: '亿' },
                  { value: 1e7, unit: '千万' },
                  { value: 1e6, unit: '百万' },
                  { value: 1e4, unit: '万' }
                ];
                for (const unit of units) {
                  if (value >= unit.value) {
                    return (value / unit.value).toFixed(2) + unit.unit;
                  }
                }
                return (value / 1e4).toFixed(2) + '万';
              },
            },
          },
          {
            name: "已付款",
            data: Object.values(this.subPaidAmount),
            type: "line",
            areaStyle: {},
            smooth: true,
            label: {
              show: true,
              position: "top",
              formatter: function (params) {
                var value = params.value;
                const units = [
                  { value: 1e8, unit: '亿' },
                  { value: 1e7, unit: '千万' },
                  { value: 1e6, unit: '百万' },
                  { value: 1e4, unit: '万' }
                ];
                for (const unit of units) {
                  if (value >= unit.value) {
                    return (value / unit.value).toFixed(2) + unit.unit;
                  }
                }
                return (value / 1e4).toFixed(2) + '万';
              },
            },
          },
        ],
      };
      echartsInit(subYearChart, "subYearLine", option);
    },
    initChartCwAomunt(year) {
      let option = {
        title: {
          text: year + "承接合同额分布情况",
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        legend: {
          top: "bottom",
        },
        series: [
          {
            name: "占比",
            type: "pie",
            radius: "40%",
            avoidLabelOverlap: false,
            data: Object.entries(this.contractCwAmount).map(([key, value]) => {
              return { name: key, value: value };
            }),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
            label: {
              alignTo: "none",
              formatter: function (params) {
                let value = params.value;
                if (value >= 100000000) {
                  // 亿
                  let v = (value / 100000000).toFixed(4) + "亿";
                  return params.name + "\n" + v + "元";
                } else {
                  // 千万元
                  let v = (value / 10000000).toFixed(4) + "千万";
                  return params.name + "\n" + v + "元";
                }
              },
              minMargin: 5,
              edgeDistance: 8,
              lineHeight: 15,
              rich: {
                time: {
                  fontSize: 10,
                  color: "#999",
                },
              },
            },
          },
        ],
      };
      echartsInit(cwAmountChart, "cwamountPie", option);
    },
    initChartCwSource(year) {
      let option = {
        title: {
          text: year + "承接合同来源分布",
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        legend: {
          top: "bottom",
        },
        series: [
          {
            name: "占比",
            type: "pie",
            radius: "40%",
            avoidLabelOverlap: false,
            data: Object.entries(this.contractSource).map(([key, value]) => {
              return { name: key, value: value };
            }),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
            label: {
              alignTo: "none",
              formatter: "{name|{b}}\n{value|{c}个}",
              minMargin: 5,
              edgeDistance: 8,
              lineHeight: 15,
              rich: {
                time: {
                  fontSize: 10,
                  color: "#999",
                },
              },
            },
          },
        ],
      };
      echartsInit(cwSourceChart, "cwSourcePie", option);
    },
    initChartSubAmount() {
      let option = {
        title: {
          text: "分包合同额统计",
          subtext:
            "合同额：" +
            Object.values(this.subAmount).reduce(
              (accumulator, currentValue) => accumulator + currentValue,
              0
            ) +
            "元" +
            "(约: " +
            this.sumSubAomunt +
            ")",
        },
        grid: {
          left: "1%",
          right: "1%",
          bottom: "0%",
          height: "60%",
          containLabel: true,
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "none",
            label: {
              backgroundColor: "#6a7985",
            },
          },
        },
        xAxis: {
          name: "",
          type: "category",
          data: Object.keys(this.subAmount),
        },
        yAxis: {
          type: "value",
          name: "单位：元",
        },
        series: [
          {
            data: Object.values(this.subAmount),
            type: "bar",
            smooth: true,
            label: {
              show: true,
              position: "top",
              formatter: function (params) {
                var value = params.value;
                if (value >= 10000) {
                  // 亿
                  return (value / 10000).toFixed(4) + "万元";
                }
              },
            },
            itemStyle: {},
          },
          {
            type: "line",
            data: Object.values(this.subAmount),
            smooth: true,
            itemStyle: {},
          },
        ],
      };
      echartsInit(subAmountChart, "subAmountBar", option);
    },

    initChartSubCwAomunt(year) {
      let option = {
        title: {
          text: year + "分包合同额分布情况",
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        legend: {
          top: "bottom",
        },
        series: [
          {
            name: "占比",
            type: "pie",
            radius: "40%",
            avoidLabelOverlap: false,
            data: Object.entries(this.subCwAmount).map(([key, value]) => {
              return { name: key, value: value };
            }),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
            label: {
              alignTo: "none",
              formatter: function (params) {
                let value = params.value;
                if (value >= 100000000) {
                  // 亿
                  let v = (value / 100000000).toFixed(4) + "亿";
                  return params.name + "\n" + v + "元";
                } else {
                  // 千万元
                  let v = (value / 10000000).toFixed(4) + "千万";
                  return params.name + "\n" + v + "元";
                }
              },
              minMargin: 5,
              edgeDistance: 8,
              lineHeight: 15,
              rich: {
                time: {
                  fontSize: 10,
                  color: "#999",
                },
              },
            },
          },
        ],
      };
      echartsInit(subCwAmountChart, "subCwAmountPie", option);
    },
    initChartSubCwSource(year) {
      let option = {
        title: {
          text: year + "分包合同来源分布",
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        legend: {
          top: "bottom",
        },
        series: [
          {
            name: "占比",
            type: "pie",
            radius: "40%",
            avoidLabelOverlap: false,
            data: Object.entries(this.subSource).map(([key, value]) => {
              return { name: key, value: value };
            }),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
            label: {
              alignTo: "none",
              formatter: "{name|{b}}\n{value|{c}个}",
              minMargin: 5,
              edgeDistance: 8,
              lineHeight: 15,
              rich: {
                time: {
                  fontSize: 10,
                  color: "#999",
                },
              },
            },
          },
        ],
      };
      echartsInit(subSourceChart, "subSourcePie", option);
    },
  },
};
</script>

<style lang="scss" scoped>
.titles {
  font-family: "puhuiti";
  font-size: 16px;
  margin-bottom: 16px;
}

.warpper {
  width: 100%;
  height: 100%;
  display: flex;

  .left {
    flex: 1.5;
    position: relative;

    .date-range {
      position: absolute;
      right: 66px;
      top: 54px;
      z-index: 1;
    }

    .left-top {
      width: 100%;
      height: 300px;
      padding: 10px;
      border: 1px solid #ececec;
    }

    .left-bottom {
      width: 100%;
      height: 300px;
      display: flex;

      .pie1 {
        flex: 1.5;
        height: 300px;
        padding: 10px;
        border: 1px solid #ececec;
      }

      .pie2 {
        flex: 1;
        height: 300px;
        padding: 10px;
        border: 1px solid #ececec;
      }
    }
  }

  .middle {
    flex: 1.5;

    .middle-top {
      height: 300px;
      padding: 10px;
      border: 1px solid #ececec;
    }

    .middle-bottom {
      display: flex;

      .bottom-left {
        flex: 1.5;
        height: 300px;
        padding: 10px;
        border: 1px solid #ececec;
      }

      .bottom-right {
        flex: 1;
        height: 300px;
        padding: 10px;
        border: 1px solid #ececec;
      }
    }
  }

}
</style>
