<template>
  <div v-loading="loading">
    <div class="search clear" style="align-items: center;">
      <el-switch @change="setOptions" :disabled="isEmpty" style="margin-right: 10px;" v-model="isTenThound" active-text="万元"
        inactive-text="元" />

      <!-- <el-select size="small" style="margin-right:10px;width:145px" v-model="companyNo" @change="setOptions"
        :disabled="isEmpty">
        <el-option v-for="depart in cp_companies" :key="depart.id" :value="depart.value" :label="depart.label" />
      </el-select> -->

      <el-date-picker class="fr picker" v-model="daytime" style=";width:100px" value-format="yyyy" :editable="false"
        :disabled="isEmpty" :clearable="false" :size="'small'" type="year" format="yyyy" align="right" placeholder="选择日期"
        :picker-options="{ disabledDate(time) { return time.getTime() > Date.now(); } }" @change="setOptions" />
    </div>

    <el-row style="margin-top:10px" v-if="!isEmpty">
      <div id="middle-container" />
    </el-row>

    <template v-else>
      <div style="text-align:center;line-height:60px;user-select:none">当前账号没有访问权限</div>
    </template>
  </div>
</template>


<script>
import asyncRequest from "@/api/newResults";
import { unit2TenThousand2, subtraction, multiplication, division, addition } from "../newReport/src/_utils";
import { mapCompany } from "./mapCompany";

// import echarts from "echarts"
import dayjs from "dayjs"

export default {
  props: ['companies', 'costField'],
  data() {
    return {
      loading: false,
      isTenThound: true,
      daytime: "",
      tableData: [],
      companyNo: "",
      cp_companies: [],
      isEmpty: false,
      options: {},
      chart: null
    }
  },
  mounted() {
    const hasCompose = false;
    const jxIndex = this.companies.findIndex((item) => item.label === "北京锦兴弘昌科技有限公司");
    const prIndex = this.companies.findIndex((item) => item.label === "北京普润心堂商贸有限公司");
    if (jxIndex !== -1 || prIndex !== -1) this.hasCompose = true;
    this.cp_companies = this.companies.filter((item) => item.label !== "北京锦兴弘昌科技有限公司" && item.label !== "北京普润心堂商贸有限公司")
    if (this.hasCompose) this.cp_companies = [...this.cp_companies, { value: "GS2302231124114965", label: "普润&锦兴&知事" }]
    if (this.cp_companies.length === 4) this.cp_companies = [{ value: "", label: "所有公司" }, ...this.cp_companies];
    this.isEmpty = this.cp_companies.length === 0;
    if (this.isEmpty) return;
    this.cp_companies = this.cp_companies.map(item => ({ ...item, label: mapCompany[item.label] || item.label }))

    this.companyNo = this.cp_companies[0].value;
    this.daytime = this.transformTime();

    this.initialChart();
  },
  beforeDestory(){
    window.removeEventListener('resize', this.chart.resize);
  },
  methods: {
    unit2TenThousand2,
    async generateOptions() {
      await this.requestData();
      const months = new Array(12).fill(0).map((item, index) => `${index + 1}月`);

      let xAxisData = [];

      if(!this.companyNo) {
         xAxisData = this.cp_companies.map((item) => item.label).filter(item => item !== "所有公司")
      } else {
        xAxisData = [this.cp_companies.find(item => item.value === this.companyNo).label]
      }

      const tableData = xAxisData.reduce((prev, key) =>  [...prev, ({...this.tableData[key], company: key})], [])

      const options = months.map((item,index) => ({
          title: { text: item },
          series: [{ data:  tableData.map(item => item.pure_sale) },{ data: tableData.map(item => item.pure_profit) }]
        }))


      return {
        baseOption: {
          timeline: {
            axisType: 'category',
            autoplay: false,
            data: months,
            playInterval: 1000
          },
          calculable: true,
          tooltip: {},
          grid: {
            top: 80,
            bottom: 100,
            tooltip: { trigger: 'axis' }
          },
          xAxis: [
            {
              type: 'category',
              axisLabel: { interval: 0 },
              data: xAxisData,
              splitLine: { show: false }
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: this.isTenThound ? '万元' : '元'
            }
          ],
          series: [
            { name: '当月营收完成', type: 'bar' },
            { name: '当月毛利完成', type: 'bar' },
            {
              name: '当月营收完成',
              type: 'pie',
              center: ['85%', '15%'],
              radius: '20%',
            },
            {
              name: '当月毛利完成',
              type: 'pie',
              center: ['85%', '45%'],
              radius: '20%',
            }
          ]
        },
        options: months.map((item,index) => ({
          title: { text: item },
          series: [
            { data: tableData.map(item => this.isTenThound ? Number(unit2TenThousand2(item[index].pure_sale)).toFixed(2) : Number(item[index].pure_sale).toFixed(2) ) },
            { data: tableData.map(item => this.isTenThound ? Number(unit2TenThousand2(item[index].pure_profit)).toFixed(2) : Number(item[index].pure_profit).toFixed(2) ) },
            {
              data: tableData.map((item,i) => ({
                name: item.company,
                value: this.isTenThound ? Number(unit2TenThousand2(item[index].pure_sale)).toFixed(2) : Number(item[index].pure_sale).toFixed(2)
              })),
            },
            {
              data: tableData.map((item,i) => ({
                name: item.company,
                value: this.isTenThound ? Number(unit2TenThousand2(item[index].pure_profit)).toFixed(2) : Number(item[index].pure_profit).toFixed(2)
              })),
            }
          ]
        }))
      }
    },

    async setOptions(){
      const options = await this.generateOptions();
      this.chart.setOption(options);
    },
    initialChart() {
      this.$nextTick(async () => {
        const dom = document.getElementById("middle-container");
        this.chart = echarts.init(dom);
        await this.setOptions();
        window.addEventListener('resize', this.chart.resize);
      })
    },
    getCurrentRateStyle(current, month) {
      const days = dayjs().daysInMonth();
      const currentMonth = dayjs().month() + 1;
      if (Number(month) > Number(currentMonth)) return;
      const oneDay = Number(division(100, days)).toFixed(2);
      const currentDay = dayjs().date();
      const currentTotalTip = Number(multiplication(currentDay, oneDay)).toFixed(2);
      return Number(currentTotalTip) > Number(current) ? 'color:red' : ''
    },
    getCurrentValueStyle(current, total, month) {
      const days = dayjs().daysInMonth();
      const currentMonth = dayjs().month() + 1;
      if (Number(month) > Number(currentMonth)) return;
      const oneDay = Number(division(total, days)).toFixed(2);
      const currentDay = dayjs().date();
      const currentTotalTip = Number(multiplication(currentDay, oneDay)).toFixed(2);
      return Number(currentTotalTip) > Number(current) ? 'color: red' : '';
    },
    setCellClassName({ column }) {
      const { label } = column;
      if (label === "当月营收目标") return "bg__yellow"
      if (label === "当月毛利目标") return "bg__red"
    },
    setHeaderClassName({ column }) {
      const { label } = column;
      if (label === "当月营收目标") return "bg__yellow"
      if (label === "当月毛利目标") return "bg__red"
    },
    transformTime() {
      let time = new Date();
      let y = time.getFullYear();
      let M = time.getMonth() + 1;
      let d = time.getDate();
      return y + "-" + (M < 10 ? "0" + M : M) + "-" + (d < 10 ? "0" + d : d);
    },
    async requestData() {
      this.loading = true;
      const tableData = {};

      if(!this.companyNo){
        for (const company of this.cp_companies) {
          if (company.label === "锦兴") continue;
          tableData[company.label === '普润' ? '普润&锦兴&知事' : company.label] = await this.getCompanyData(company.value)
          tableData['所有公司'] = await this.getCompanyData()
        }
      } else {
        const label = this.cp_companies.find(item => item.value === this.companyNo).label;
        tableData[label] = await this.getCompanyData(this.companyNo);
      }
      this.loading = false;
      this.tableData = tableData;
    },
    async getCompanyData(companyNo) {
      const result = await asyncRequest.companyEvery({ year: (this.daytime.split('-'))[0], companyNo })

      if (companyNo === "GS2302231124114965") {
        const jxResult = await asyncRequest.companyEvery({ year: (this.daytime.split('-'))[0], companyNo: "GS2304031312553746" })

        result.data = result.data.map((_, index) => {
          const prItem = result.data[index];
          const jxItem = jxResult.data[index];

          return {
            month: prItem.month,
            cgd_th_total: Number(addition(prItem['cgd_th_total'], jxItem['cgd_th_total'])).toFixed(2),
            cgd_total: Number(addition(prItem['cgd_total'], jxItem['cgd_total'])).toFixed(2),
            cost_tips: Number(addition(prItem['cost_tips'], jxItem['cost_tips'])).toFixed(2),
            sale_total: Number(addition(prItem['sale_total'], jxItem['sale_total'])).toFixed(2),
            th_total: Number(addition(prItem['th_total'], jxItem['th_total'])).toFixed(2),
            total_tips: Number(addition(prItem['total_tips'], jxItem['total_tips'])).toFixed(2),
          }
        })
      };

      let data = "";

      switch (Number(result.code)) {
        case 0:
          data = (result.data || []).map(tableItem => {
            /* 销售净额 = 销售额 - 退货额 **/
            const pure_sale = subtraction(tableItem.sale_total, tableItem.th_total)
            /* 指标达成率 = 销售净额 / 销售指标 **/
            const completion_rate = multiplication(division(pure_sale, tableItem.total_tips), 100)
            /* 采购净额 = 采购额 - 采购退货额 **/
            const pure_purch = subtraction(tableItem.cgd_total, tableItem.cgd_th_total)
            /* 毛利润 = (本月销售净额 - 本月采购净额) **/
            const pure_profit = subtraction(pure_sale, pure_purch)
            /*  毛利率 = (本月毛利润 / 本月销售净额) * 100 **/
            const pure_interest_rate = multiplication(division(pure_profit, pure_sale) || 0, 100)

            return {
              pure_sale,
              pure_purch,
              pure_profit,
              completion_rate,
              pure_interest_rate,
              month: tableItem.month,
              cost_tips: tableItem.cost_tips,
              total_tips: tableItem.total_tips,
              cost_rate: Number(tableItem.cost_tips) === 0 ? 0 : multiplication(division(pure_profit, tableItem.cost_tips) || 0, 100).toFixed(2)
            }
          })
          break
        default:
          data = {};
          break
      }
      return data;
    }
  }
}
</script>



<style lang="scss" scoped>
.new-results {
  .search {
    height: 36px;
    display: flex;
    justify-content: flex-end;
    padding: 0px 10px;
    margin-top: 10px
  }

  #middle-container {
    position: relative;
    height: 600px;
    overflow: hidden;
    width: 100vw;

    canvas {
      width: 100%;
    }
  }
}
</style>

