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

      <el-select size="small" style="margin-right:10px" v-model="companyNo" @change="requestData">
        <el-option 
          v-for="depart in companies" 
          :key="depart.value" 
          :label="depart.label" 
          :value="depart.value" 
         />
      </el-select>

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

    <el-row style="margin-top: 10px; display: flex;">
      <el-table border size="mini" :data="list" :span-method="spanMethod" :cell-class-name="setCellClassName">
        <el-table-column fixed="left" label="公司" prop="company" align="center" width="140px" />
        <el-table-column fixed="left" label="部门" prop="depart" align="center" width="140px" />
        <el-table-column label="当日营业收入"  align="center" width="120px">
          <template slot-scope="scope">{{ unit2TenThousand(scope.row.dayinfo.sale_total,isTenThound) }}</template>
        </el-table-column>
        
        <el-table-column label="当月营收目标" align="center" width="120px">
          <template slot-scope="scope">{{ unit2TenThousand(scope.row.total_tips,isTenThound) }}</template>
        </el-table-column>

        <el-table-column label="当月营业收入(净)" align="center" width="400px">
          <template slot-scope="scope">
            <div style="display:flex;flex-direction: column;">
              <p style="text-align: center;">{{ unit2TenThousand(scope.row.monthinfo.monthNetSales,isTenThound)}}</p>
              <el-table border size="mini" :data="scope.row.currentMonthPure">
                <el-table-column align="center" label="直营/自营">
                  <template slot-scope="scope">{{ unit2TenThousand(scope.row.zy,isTenThound) }}</template>
                </el-table-column>
                <el-table-column align="center" label="渠道">
                  <template slot-scope="scope">{{unit2TenThousand(scope.row.qd,isTenThound)}}</template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="成本" align="center" min-width="400px">
          <el-table-column align="center" label="直营/自营">
            <template slot-scope="scope">{{unit2TenThousand(scope.row.zy_cost,isTenThound)}}</template>
          </el-table-column>

          <el-table-column align="center" label="渠道">
            <template slot-scope="scope">{{unit2TenThousand(scope.row.qd_cost,isTenThound)}}</template>
          </el-table-column>
        </el-table-column>

        <el-table-column align="center" label="毛利" min-width="400px">
          <el-table-column align="center" label="直营/自营">
            <template slot-scope="scope">{{unit2TenThousand(scope.row.zy_gross,isTenThound)}}</template>
          </el-table-column>

          <el-table-column align="center" label="渠道">
            <template slot-scope="scope">{{unit2TenThousand(scope.row.qd_gross,isTenThound)}}</template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </el-row>
  </div>
</template>


<script>
import asyncRequest from "@/api/newResults";
import setHeight from "@/mixins/index";

import { 
  addition, 
  division, 
  subtraction, 
  multiplication, 
  unit2TenThousand 
} from "../newReport/src/_utils";

export default {
  mixins: [ setHeight ],
  data(){
    return {
      list: [],
      daytime: "",
      companyNo: "GS2203161855277894",
      loading: false,
      isTenThound: true,
      companies:[
        { value:"GS2302231125079621",label: "北京百辰荣达国际科贸有限公司"},
        { value:"GS2302231323386950",label: "北京泓源广诚国际商贸有限公司"},
        { value:"GS2203161855277894",label: "北京万宇恒通国际科贸有限公司"},
        { value:"GS2302231124114965",label: "普润&锦兴&知事"}
      ]
    }
  },
  computed:{
    currentCompanyName(){
      return this.companies.find(item => item.value === this.companyNo).label;
    }
  },
  mounted() {
    this.daytime = this.transformTime();
    this.requestData();
  },
  watch:{ daytime:{ handler(){ this.requestData() }}},
  methods: {
    unit2TenThousand,
    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);
    },
      /* 表格合并列和行 */
    spanMethod({ rowIndex, columnIndex }) {
		  if (columnIndex === 0) {
		   const _row = this.flitterData(this.list).one[rowIndex];
		   const _col = _row > 0 ? 1 : 0;
		   return { rowspan: _row, colspan: _col };
		  }
	  },
	  /**合并表格的第一列，处理表格数据 */
	  flitterData(arr) {
      let spanOneArr = [];
      let concatOne = 0;
	     arr.forEach((item, index) => {
	     if (index === 0) {
	       spanOneArr.push(1);
	     } else {
	      //注意这里的quarterly是表格绑定的字段，根据自己的需求来改
	       if (item.company === arr[index - 1].company) {
	         //第一列需合并相同内容的判断条件
	         spanOneArr[concatOne] += 1;
	         spanOneArr.push(0);
	       } else {
	         spanOneArr.push(1);
           concatOne = index;
	       }
	     }
	    });

	    return { one: spanOneArr };
	  },
    setCellClassName({ column }) {
      const { label } = column; return label === "当月营业收入(净)" ? "pure__cell" : "";
    },
    async requestData() {
      this.loading = true;
      this.list = [];

      const res = await asyncRequest.departmentEveryDay({ daytime: this.daytime, companyNo: this.companyNo });

      if (res.code === 0 && res.data && res.data.length > 0) {
        let list = (res.data || [])
        .map(({depart, msale_total, mth_total, sale_total, th_total, total_tips ,mzy_sale_total, mchannel_sale_total,channel_cost_total,zy_cost_total}) => {
          return {
            depart, total_tips,mzy_sale_total, mchannel_sale_total, channel_cost_total, zy_cost_total,
            dayinfo: { sale_total, th_total }, monthinfo:{ msale_total, mth_total }
          }
        });

        this.total = list.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}
        )


        let mapDepart = ["百辰","泓源","普润","平台"]


        list = mapDepart.map(d => list.find(({ depart }) => depart === d))
        const mapToDepartment = { 百辰:"客服部@百辰荣达", 泓源:"网络部@泓源广诚", 普润:"	项目部@普润心堂", 平台:"	平台部@万宇恒通" }

        const company = this.companies.find(item => item.value === this.companyNo);

        console.log(this.companies,'===',this.companyNo)
        this.list = list.map(({depart,total_tips,dayinfo,monthinfo,mchannel_sale_total,mzy_sale_total,zy_cost_total,channel_cost_total}) => {
          /* 月净销售 = 月销售 - 月退货 **/
          const monthNetSales = subtraction(monthinfo.msale_total, monthinfo.mth_total)
          /* 月经销售完成率 = 月净销售 / 销售指标 **/
          const monthProportion = multiplication(division(monthNetSales,total_tips),100).toFixed(2)
          return {
            total_tips, // 营收目标
            zy_cost: zy_cost_total, // 自营成本
            qd_cost: channel_cost_total, // 渠道成本
            depart: mapToDepartment[depart],
            company: company.label,
            currentMonthPure:[ { zy : mzy_sale_total, qd: mchannel_sale_total } ], // 当月营业收入(净)
            zy_gross:Number(subtraction(mzy_sale_total,zy_cost_total)).toFixed(2), // 自营毛利  = 自营营收 - 自营成本
            qd_gross:Number(subtraction(mchannel_sale_total,channel_cost_total)).toFixed(2), // 渠道毛利 = 渠道营收 - 渠道成本
            dayinfo:{ ...dayinfo, /** 日销售额 = 日销售额 - 日退货额 */  sale_total:subtraction(dayinfo.sale_total,dayinfo.th_total) },
            /* 占比 =  (当前部门销售额 / 各部门总销售额) / 100 **/
            proportion:multiplication( division(monthinfo.msale_total,this.total.month) || 0 ,100) || 0,
            monthinfo:{ monthNetSales,monthProportion: monthProportion }
          }
        })
      } else {
        this.list = [];
      }
      this.getHeight();
      this.loading = false;
    },
  },
}

</script>

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

