<template>
  <div class="SalesReportRejectedNew">
    <div class="table-header">{{index}}.{{companyName || '--'}}</div>

    <el-table class="table-sub__header" :data="[stats]" size="mini" border style="margin-top:10px;margin-bottom:-1px">
      <!-- <span>月指标:</span>{{ stats.total_tips }} -->
      <el-table-column align="center" prop="total_tips" label="月指标" />
      <el-table-column align="center" prop="month" label="完成额" />
      <el-table-column align="center"  prop="completionRate" label="完成率" />
    </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 prop="type" label="业绩类型"  width="70">
        <template slot-scope="scope">
          {{ getTypeLabel(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column label="本日销售额" max-width="120" align="center">
        <template slot-scope="scope">
            {{ unit2TenThousand(scope.row.dayinfo.sale_total) }}
          </template>
      </el-table-column>
      <el-table-column label="本月销售额" max-width="120" align="center">
        <template slot-scope="scope">
            {{ unit2TenThousand(scope.row.monthinfo.msale_total) }}
          </template>
      </el-table-column>
      <el-table-column label="月占比" prop="proportion" align="center">
        <template slot-scope="scope">
            {{ scope.row.proportion }}%
          </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { mapReponseType,getTypeLabel,addition, division, multiplication, unit2TenThousand, subtraction} from "./_utils"
import dayjs from "dayjs"
import asyncRequest from "@/aapi/report";
import setHeight from "@/mixins/index";
export default {
  name: "DepartmentReport",
  props: ["date","companyNo","index"],
  mixins: [setHeight],
  watch: {
    date: function(val) {
      this.dataTime = val;
      if (val) {
        this.searchList();
      }
    }
  },
  computed:{
    stats(){
      const { month, monthReturn ,total_tips} = this.total;
      /* 完成额 = 月销售额 - 月退货额 **/
      const completion = subtraction(month, monthReturn)
      /* 完成率 = 完成额 / 月指标 **/
      const completionRate = multiplication(division(completion,total_tips) || 0, 100)
      return {
        /* 完成额 **/
        month: unit2TenThousand(completion),
        /* 月指标 **/
        total_tips: unit2TenThousand(total_tips),
        /* 完成率 **/
        completionRate: completionRate ? completionRate.toFixed(2) + '%'  : completionRate + '%'
      }
    }
  },
  data() {
    return {
      total:{
        day:0,
        month:0,
        total_tips: 0,
        monthReturn:0
      },
      companyName:"",
      mapReponseType,
      dataTime: this.date,
      loading: false,
      maxHeight: "0",
      tableData: []
    };
  },
  async created() {
    window.onresize = () => {
      this.getHeight();
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.getHeight();
    });
    this.searchList();
  },
  methods: {
    getTypeLabel,
    unit2TenThousand,
    tableRowClassName({ row, rowIndex }) {
      if ((row && row.child && row.child.length > 0) || rowIndex === 0) {
        return "warning-row";
      } else {
        return "";
      }
    },
    getDiffDay() {
      let totalDays, diffDate
      const myDate_1 = Date.parse(this.date)
      const myDate_2 = Date.parse('2023-04-17 00:00:00')
      // eslint-disable-next-line prefer-const
      diffDate = myDate_1 - myDate_2
      // eslint-disable-next-line prefer-const
      totalDays = Math.floor(diffDate / (1000 * 3600 * 24))
      return totalDays // 相差的天数
    },
    async searchList() {
      this.loading = true;
      this.tableData = [];
      const res = await asyncRequest.departmentReport({
        daytime: this.date,
        companyNo: this.companyNo
      });

      const isBeforeDate = this.getDiffDay() < 0 && this.companyNo === "GS2302231323386950"

      if (res.code === 0 && res.data && res.data.length > 0) {
        const { monthinfo = [], dayinfo = [], total_tips = 0, companyName } = res.data[0] || [];

        monthinfo[1] = {
          ...(isBeforeDate ? {
            msale_total:addition(monthinfo[1].msale_total,monthinfo[2].msale_total),
            mth_total:addition(monthinfo[1].mth_total,monthinfo[2].mth_total),
            type:'2'
          } : monthinfo[1])
        }

        monthinfo[0] = {
          ...(isBeforeDate ? {
            msale_total:0,
            mth_total:0,
            type:'1'
          } : monthinfo[0])
        }

        monthinfo[2] = {
          ...(isBeforeDate ? {
            msale_total:0,
            mth_total:0,
            type:'3'
          } : monthinfo[2])
        }

    
        this.companyName = companyName
        const types = Object.keys(mapReponseType)

        this.total = {
          total_tips: Number(total_tips),
          day: dayinfo.reduce((prev, {sale_total = "0"}) => addition(prev,sale_total),0),
          month: monthinfo.reduce((prev, {msale_total = "0"}) => addition(prev,msale_total),0),
          monthReturn:  monthinfo.reduce((prev, {mth_total = "0"}) => addition(prev,mth_total),0),
        }

        this.tableData = types.map(type => {
          const _monthinfo = monthinfo.find(month => String(month.type) === type) || {}
          const _dayinfo = dayinfo.find(day => String(day.type) === type) || {}
          const msale_total = subtraction(_monthinfo.msale_total,_monthinfo.mth_total) || 0
          const total = subtraction(this.total.month,this.total.monthReturn)

          return {
            type,
            dayinfo: {
              ..._dayinfo,
              /** 日销售额 = 日销售额 - 日退货额 */
              sale_total: subtraction(_dayinfo.sale_total,_dayinfo.th_total) || 0
            },
            monthinfo:{
              ...monthinfo,
              /** 月销售额 = 月销售额 - 月退货额 */
              msale_total
            },
             /* 月占比 = (当前业绩类型月销售额 / 总月销售额) / 100 **/
            proportion:multiplication( division(msale_total,Number(total).toFixed(2)) || 0 ,100).toFixed(2)
          }
        })

      } 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>
