<template>
  <div v-loading="loading">
    <div class="search" style="align-items: center;">
      <div style="float:left;font-size:16px;line-height:30px">
        年度完成情况
      </div>

      <div style="float:right">
        <el-select size="small" style="margin-right:10px;width:160px" v-model="companyNo" @change="requestData"
          :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 no-padding" v-model="daytime" style=";width:65px" 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="requestData" />
      </div>
    </div>

    <el-row style="margin-top:10px;margin-top:10px" v-if="!isEmpty">
      <el-table border size="mini" :data="tableData" :header-cell-class-name="setHeaderClassName" :row-class-name="setRowClassName"
        :cell-class-name="setCellClassName">
        <el-table-column fixed="left" label="月度" prop="month" align="center" width="45px" />
        <el-table-column label="营收目标" align="center" min-width="115px">
          <template slot-scope="scope">
            {{ unit2TenThousand(scope.row.total_tips, isTenThound) }}
          </template>
        </el-table-column>
        <el-table-column label="营业收入(净)" align="center" min-width="115px">
          <template slot-scope="scope">
            <div :style="getCurrentValueStyle(scope.row.pure_sale, scope.row.total_tips, scope.row.month)">
              {{ unit2TenThousand(scope.row.pure_sale, isTenThound) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="营收完成%" align="center" min-width="95px">
          <template slot-scope="scope">
            <div :style="getCurrentRateStyle(scope.row.completion_rate, scope.row.month)">
              {{ Number(scope.row.completion_rate).toFixed(2) + "%" }}
            </div>
          </template>
        </el-table-column>

        <template v-if="costField">
          <el-table-column label="毛利目标" align="center" min-width="115px">
            <template slot-scope="scope">
              {{ unit2TenThousand(scope.row.cost_tips, isTenThound) }}
            </template>
          </el-table-column>
          <el-table-column label="毛利完成" align="center" min-width="115px">
            <template slot-scope="scope">
              <div :style="getCurrentValueStyle(scope.row.pure_profit, scope.row.cost_tips, scope.row.month)">
                {{ unit2TenThousand(scope.row.pure_profit, isTenThound) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="毛利完成%" align="center" min-width="95px">
            <template slot-scope="scope">
              <div :style="getCurrentRateStyle(scope.row.cost_rate, scope.row.month)">
                {{ Number(scope.row.cost_rate).toFixed(2) + "%" }}
              </div>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <div style="height:100px"></div>
    </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 { unit2TenThousand, subtraction, multiplication, division, addition } from "../newReport/src/_utils";
import { mapCompany } from "./mapCompany";
import dayjs from "dayjs"

export default {
  props: ['companies', 'costField', 'isTenThound'],
  data() {
    return {
      loading: false,
      daytime: "",
      tableData: [],
      companyNo: "",
      cp_companies: [],
      isEmpty: false
    }
  },
  mounted() {
    let hasCompose = false;
    const jxIndex = this.companies.findIndex((item) => item.label === "北京锦兴弘昌科技有限公司");
    const prIndex = this.companies.findIndex((item) => item.label === "北京普润心堂商贸有限公司");
    const zsIndex = this.companies.findIndex((item) => item.label === "北京知事文化产业发展有限公司");

    if (jxIndex !== -1 || prIndex !== -1 || zsIndex !== -1) hasCompose = true;
    this.cp_companies = this.companies.filter((item) => item.label !== "北京锦兴弘昌科技有限公司" && item.label !== "北京普润心堂商贸有限公司" && item.label !== "北京知事文化产业发展有限公司")
    if (hasCompose) this.cp_companies = [...this.cp_companies, { value: "GS2401181650538135", 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,index) => {
      let label = '';
      
      if (item.label === '所有公司') {
        label = '所有公司'
      }


      if (item.label === '北京万宇恒通国际科贸有限公司') {
        label = '平台公司: 万宇'
      }


      if (item.label === "普润&锦兴&知事") label = `业务公司: 普润&锦兴&知事`
      if (label === '') label = `业务公司: ${mapCompany[item.label]}`;
      return ({ ...item, label })
    })

    let list = ['所有公司','平台公司: 万宇','业务公司: 百辰','业务公司: 泓源','业务公司: 普润&锦兴&知事']
    const cp_list = this.cp_companies.map((item) => item.label);
    list = list.filter(item => cp_list.includes(item));
    this.cp_companies = list.map((item) => this.cp_companies.find((cp_item) => cp_item.label === item));
    this.companyNo = this.cp_companies[0].value;

    this.daytime = this.transformTime();
    this.requestData();
  },
  methods: {
    unit2TenThousand,
    setRowClassName({row}){
      if(row.month === '合计') return 'table-header-color'
    },
    getCurrentRateStyle(current, month) {
      const days = dayjs().daysInMonth();
      const currentMonth = dayjs().month() + 1;
      if (Number(month) > Number(currentMonth)) return;
      if (month === '合计') 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;
      if (month === '合计') return;
      const oneDay = Number(division(total, days)).toFixed(2);
      // console.log(month,oneDay)
      const currentDay = dayjs().date();
      const currentTotalTip = Number(multiplication(currentDay, oneDay)).toFixed(2);
      return Number(currentTotalTip) > Number(current) ? 'color: red' : '';
    },
    setCellClassName({ column,row }) {
      if(row.month === '合计') return;
      const { label } = column;
      // if (label === "营业收入(净)" || label === '当月成本合计') return "pure__cell";
      if (label === "营收目标") return "bg__success"
      if (label.indexOf('营业') !== -1 || label.indexOf('营收') !== -1) return "bg__success_1"
      if (label === "毛利目标") return "bg__primary"
      if (label.indexOf('毛利') !== -1) return "bg__primary_1"
      if (label.indexOf('成本') !== -1) return "bg__warning_1"
    },
    setHeaderClassName({ column }) {
      const { label } = column;
      if (label === "营收目标") return "bg__success"
      if (label.indexOf('营业') !== -1 || label.indexOf('营收') !== -1) return "bg__success_1"
      if (label === "毛利目标") return "bg__primary"
      if (label.indexOf('毛利') !== -1) return "bg__primary_1"
      if (label.indexOf('成本') !== -1) return "bg__warning_1"
    },
    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 result = await asyncRequest.companyEvery({ year: (this.daytime.split('-'))[0], companyNo: this.companyNo })

      // if(this.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(prItem['total_tips']).toFixed(2),
      //     }
      //   })
      // };
      // if(this.companyNo === ""){
      //   result.data.forEach((item) => item.total_tips = 0);
      //   for(const c of this.cp_companies.filter(({value}) => value !== "")){
      //     const res = await asyncRequest.companyEvery({ year: (this.daytime.split('-'))[0], companyNo: c.value });
      //     result.data = result.data.reduce((prev,curr,index) => {
      //       return [
      //         ...prev,
      //         {
      //           ...curr,
      //           total_tips:Number(addition(Number(curr.total_tips).toFixed(2),Number(res.data[index].total_tips).toFixed(2))).toFixed(2)
      //         }
      //       ]
      //     },[])
      //   }
      // }


      switch (Number(result.code)) {
        case 0:
          this.tableData = (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)
            }
          })


          const totalItem = this.tableData.reduce((prev, curr) => {
            return {
              pure_sale: Number(addition(prev.pure_sale, curr.pure_sale)).toFixed(2),
              pure_purch: Number( addition(prev.pure_purch, curr.pure_purch)).toFixed(2),
              pure_profit: Number(addition(prev.pure_profit, curr.pure_profit)).toFixed(2),
              completion_rate:Number( addition(prev.completion_rate, curr.completion_rate)).toFixed(2),
              pure_interest_rate:Number( addition(prev.pure_interest_rate, curr.pure_interest_rate)).toFixed(2),
              total_tips:Number( addition(prev.total_tips, curr.total_tips)).toFixed(2),
              cost_tips:Number( addition(prev.cost_tips, curr.cost_tips)).toFixed(2),
              cost_rate:Number( addition(prev.cost_rate, curr.cost_rate)).toFixed(2),
              month: '合计',
            }
          }, {
            pure_sale: 0,
            pure_purch: 0,
            pure_profit: 0,
            completion_rate: 0,
            pure_interest_rate: 0,
            month: '合计',
            cost_tips: 0,
            total_tips: 0,
            cost_rate: 0
          })

          totalItem.completion_rate = multiplication(division(totalItem.pure_sale, totalItem.total_tips) || 0, 100)
          totalItem.cost_rate = Number(totalItem.cost_tips) === 0 ? 0 : multiplication(division(totalItem.pure_profit, totalItem.cost_tips) || 0, 100).toFixed(2)
          this.tableData = [...this.tableData, totalItem];

          // const totalItem = createTotalItem(tableData)
          // totalItem.month = "年度合计"
          // /* 年度指标达成率 = (年度销售净额 / 年度销售指标) **/
          // totalItem.completion_rate = multiplication(division(totalItem.pure_sale,totalItem.total_tips),100)
          // /* 年度毛利润 = 年度销售额 - 年度采购额 **/
          // totalItem.pure_profit = subtraction(totalItem.pure_sale,totalItem.pure_purch)
          // /* 年度毛利率 = (年度毛利润 / 年度销售额) **/
          // totalItem.pure_interest_rate = multiplication(division(totalItem.pure_profit,totalItem.pure_sale),100)
          // this.tableData = [...tableData,totalItem]
          break
        default:
          break
      }
      // this.getHeight();
      this.loading = false;
    }
  }
}
</script>



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

