<template>
  <div class="SalesReportRejectedNew">
    <h3>
      整体搞了 {{unit2TenThousand(total.completion)}}元（万宇平台+业务公司供应商端）
    </h3>


    <el-table size="mini" border style="margin-bottom:-1px" :data="[total]">
      <el-table-column label="月指标" prop="total_tips">
        <template slot-scope="scope">
        {{unit2TenThousand(scope.row.total_tips)}}
        </template>
      </el-table-column>
      <el-table-column label="完成额" prop="completion">
        <template slot-scope="scope">
          {{unit2TenThousand(scope.row.completion)}}
        </template>
      </el-table-column>
      <el-table-column label="完成率">
        <template slot-scope="scope">
          {{ scope.row.completionRate}}
        </template>
      </el-table-column>
    </el-table>

    <el-table
      :data="tableData"
      v-loading="loading"
      border
      :max-height="maxHeight"
      :size="'mini'"
      style="width: 100%"
      row-key="id"
      default-expand-all
      :tree-props="{ children: 'child', hasChildren: 'hasChildren' }"
    >
      <el-table-column label="部门" fixed="left" width="80" prop="depart">
        <template slot-scope="scope">{{getCompanyCompletionLabel(scope.row.depart)}}</template>
      </el-table-column>
      <el-table-column label="本日销售额" min-width="100" align="center">
         <template slot-scope="scope">
            {{ unit2TenThousand(scope.row.dayinfo.sale_total) }}
         </template>
      </el-table-column>
      <el-table-column label="本月金额" min-width="120" align="center">
        <el-table-column label="销售指标" align="center">
          <template slot-scope="scope">
            {{ unit2TenThousand(scope.row.total_tips) }}
          </template>
        </el-table-column>
        <el-table-column label="净销售" align="center">
          <template slot-scope="scope">
            {{ unit2TenThousand(scope.row.monthinfo.monthNetSales) }}
          </template>
        </el-table-column>
        <el-table-column label="净销售完成率" align="center">
          <template slot-scope="scope">
            {{ scope.row.monthinfo.monthProportion }}%
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import asyncRequest from "@/aapi/report";
import setHeight from "@/mixins/index";
import { 
  unit2TenThousand,
  getCompanyCompletionLabel,
  multiplication,
  subtraction,
  addition, 
  division
} from "./_utils";

export default {
  name: "WanyuCompletion",
  props: ["date"],
  mixins: [setHeight],
  watch: {
    date: function(val) {
      this.dataTime = val;
      if (val) {
        this.searchList();
      }
    }
  },
  data() {
    return {
      total:{
          completion: 0,
          total_tips:0,
      },
      dataTime: this.date,
      loading: false,
      maxHeight: "0",
      tableData: []
    };
  },
  computed:{
    stats(){
      const { day, month ,total_tips} = this.total;
      return {
        day: unit2TenThousand(day),
        month: unit2TenThousand(month),
        total_tips: unit2TenThousand(total_tips),
        completionRate: multiplication(division(month, total_tips) || 0, 100) + '%'
      }
    }
  },
  async created() {
    window.onresize = () => {
      this.getHeight();
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.getHeight();
    });
    this.searchList();
  },
  methods: {
    getCompanyCompletionLabel,
    unit2TenThousand,
    division,
    tableRowClassName({ row, rowIndex }) {
      if ((row && row.child && row.child.length > 0) || rowIndex === 0) {
        return "warning-row";
      } else {
        return "";
      }
    },
    async searchList() {
      this.loading = true;
      this.tableData = [];
      const res = await asyncRequest.companyReport({
        daytime: this.date,
        companyNo: "GS2203161855277894"
      });

      const result = await asyncRequest.departmentReport({
        daytime: this.date,
      });

      if ((res.code === 0 && res.data && res.data.length > 0) && (result.code === 0 && result.data && result.data.length > 0)) {
        const mapCompanySupplierSale = result.data.reduce((prev,current) => ({
           ...prev,
           [current.companyName]:subtraction(current.monthinfo[2].msale_total,current.monthinfo[2].mth_total)
          }),{})

          const mapCompanySupplierSaleDay = result.data.reduce((prev,current) => ({
           ...prev,
           [current.companyName]:subtraction(current.dayinfo[2].sale_total,current.dayinfo[2].th_total)
          }),{})

        let tableData = (res.data || []).map(({
          depart,
          msale_total,
          mth_total,
          sale_total,
          th_total,
          total_tips
        }) => ({
            depart,
            total_tips,
            dayinfo: { sale_total, th_total },
            monthinfo:{ msale_total, mth_total }
        }));

        tableData = ["百辰","泓源","普润","平台"].map(c => {
          return tableData.find(({depart}) => depart === c)
        })

        this.total = tableData.reduce((prev,current) => {
          const { total_tips = 0, day = 0, month = 0 } = current;
          return {
            total_tips:addition(total_tips,prev.total_tips),
            month:addition(month,prev.month),
            day:addition(day, prev.day),
          }
        },{
          total_tips:0,
          month:0,
          day:0
        })

        this.tableData = tableData.map(({depart,total_tips,dayinfo,monthinfo}) => {
          /* 月净销售 = 月销售 - 月退货 **/
          let monthNetSales = subtraction(monthinfo.msale_total, monthinfo.mth_total)
          let dayNetSale = subtraction(dayinfo.sale_total,dayinfo.th_total)

          const supplierSalekey = Object.keys(mapCompanySupplierSale).find(key => key.includes(depart))
          const supplierSaleDaykey = Object.keys(mapCompanySupplierSaleDay).find(key => key.includes(depart))

          if(supplierSalekey){
            monthNetSales = addition(monthNetSales,mapCompanySupplierSale[supplierSalekey])
          }

          if(supplierSaleDaykey){
            dayNetSale = addition(dayNetSale,mapCompanySupplierSaleDay[supplierSaleDaykey])
          }

          // if(supplierSalekey === '北京普润心堂商贸有限公司'){
          //   monthNetSales = addition(monthNetSales,mapCompanySupplierSale['北京锦兴弘昌科技有限公司'])
          // }
          // if(supplierSaleDaykey === '北京普润心堂商贸有限公司'){
          //   dayNetSale = addition(dayNetSale,mapCompanySupplierSaleDay['北京锦兴弘昌科技有限公司'])
          // }

          /* 月经销售完成率 = 月净销售 / 销售指标 **/
          const monthProportion = multiplication(division(monthNetSales,total_tips),100).toFixed(2)
          return {
            depart,
            total_tips,
            dayinfo:{
              ...dayinfo,
              /** 日销售额 = 日销售额 - 日退货额 */
              sale_total:dayNetSale
            },
            monthinfo:{
              monthNetSales,
              monthProportion: monthProportion
            },
            /* 占比 =  (当前部门销售额 / 各部门总销售额) / 100 **/
            proportion:multiplication(
              division(monthinfo.msale_total,this.total.month) || 0
            ,100) || 0
          }
        })
        
        this.tableData.forEach(item => {
          console.log(item.monthinfo.monthNetSales);
          console.log(item.depart);
        })

        this.total = {
          /* 月完成额 **/
          completion: this.tableData.reduce((prev,current) => addition(prev,current.monthinfo.monthNetSales),0),
          /* 月指标 **/
          total_tips:this.tableData.reduce((prev,current) => addition(prev,current.total_tips),0),
        }
        const completionRate = multiplication(division(this.total.completion,this.total.total_tips) || 0, 100).toFixed(2) + '%'
        
        this.total = {
          ...this.total,
          completionRate
        }

      } else {
        this.tableData = [];
      }
      this.getHeight();
      this.loading = false;
    }
  }
};
</script>

<style lang="scss" scoped>

.table-header {
  font-size: 14px;
  border-bottom: none;
}

.table-sub__header {

  span{
    font-weight: bold !important;
  }
}
</style>

