<template>
  <div class="SalesReportRejectedNew" v-loading="loading">
    <el-table :data="tableData" size="mini" border>
      <el-table-column label="业务公司" prop="cgder" width="200px" />
      <el-table-column width="110px" label="采购单总量" prop="total_cgd" />
      <el-table-column label="库存商品" prop="tag_1" />
      <el-table-column label="非库存商品" prop="tag_2" />
      <el-table-column label="反馈商品" prop="tag_zx"/>
      <el-table-column label="TOC" prop="tag_c" />
      <el-table-column label="TOB" prop="tag_b" />
    </el-table>
  </div>
</template>

<script>
import asyncRequest from "@/api/newReport";
import setHeight from "@/mixins/index";
import { addition } from "./_utils";
export default {
  name: "Purchasee",
  mixins: [setHeight],
  props: ['date'],
  watch: {
    date: function(val) {
      this.dataTime = val;
      if (val && val.length === 2) {
        this.searchList();
      }
    }
  },
  data() {
    return {
      loading:false,
      tableData:[]
    };
  },
  async created() {
    window.onresize = () => {
      this.getHeight();
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.getHeight();
    });
    this.searchList();
  },
  methods: {
    async searchList() {
      this.loading = true;
      this.tableData = [];

      const res = await asyncRequest.cgdOrder({
        start: this.date[0] || "",
        end: this.date[1] || ""
      });

      if (res.code === 0 && res.data && res.data.length > 0) {
        this.tableData = res.data.reduce((prev,curr = { name:"", result: {}}) => {
          return [
            ...prev,
            ...Object.keys(curr.result).map(key => {
              return {
                name:curr.name,
                ...curr.result[key]
              }
            })]
        },[])


        const totalItem = {
          cgder:'合计',
          name:'--',
          ...this.tableData.reduce((prev,current) => {
            const {cgder,name,...rest} = current;
            const keys = Object.keys(rest)
            return keys.reduce((preObj,key) => ({ ...preObj,  [key]:addition(current[key] || 0, prev[key] || 0)}),{})
          },{})
        }


        this.tableData.push(totalItem)
      } else {
        this.tableData = [];
      }

      this.getHeight();
      this.loading = false;
    }
  }
};
</script>
