<template>
  <div class="SalesReportRejectedNew" v-loading="loading">
    <div class="picker-title" style="display: flex;align-items: center;justify-content: space-between;margin: 10px 0px;">
      <p style="margin:0">{{ title }}</p>
        <!-- <el-date-picker
          :pickerOptions="pickerOptions"
          style="width:150px"
          v-model="day"
          size="mini"
          type="date"
          placeholder="截止日期"
          @change="handleChange"
        /> -->
    </div>

    <el-table :data="tableData" size="mini" border :span-method="objectSpanMethod">
      <el-table-column width="70px" label="部门" prop="name" />
      <el-table-column width="90px" label="商品类型"  prop="0">
        <template slot-scope="scope">{{getType(scope.row["0"])}}</template>
      </el-table-column>
      <el-table-column   label="时效" align="center">
        <el-table-column label="A24小时"  prop="1" />
        <el-table-column label="B48小时"  prop="2" />
        <el-table-column label="C3-7天内" prop="3" />
        <el-table-column label="D14天内"  prop="4" />
        <el-table-column label="E30天内"  prop="5" />
        <el-table-column label="F超30天"  prop="6" />
      </el-table-column>

      <el-table-column   label="总计">
        <template slot-scope="scope">
          {{getTotal(scope.row)}}
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import asyncRequest from "@/api/newReport";
import setHeight from "@/mixins/index";
import { addition } from "./_utils";
import dayjs from "dayjs";

export default {
  name: "Consult",
  mixins: [setHeight],
  props: ['date', 'title'],
  watch: {
    date: function(val) {
      this.dataTime = val;
      if (val && val.length === 2) {
        this.searchList();
      }
    }
  },
  data() {
    return {
      loading:false,
      tableData:[],
      day:"",
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
          //  return time.getTime() > Date.now() - 8.64e7;
        }
      }
    };
  },
  async created() {
    window.onresize = () => {
      this.getHeight();
    };
  },
  mounted() {
    this.handleChange(dayjs(new Date()).format('YYYY-MM-DD'))
    this.$nextTick(() => {
      this.getHeight();
    });
    // this.searchList();
  },
  methods: {
    getType(sourceType){
      const mapType = {
        '库存品':'库存商品',
        '咨询采返':'反馈商品',
        '非库存品':'非库存商品'
      }
      return mapType[sourceType] || sourceType;
    },
    getTotal(row){
      const keys = ['1','2','3','4','5','6']
      return keys.reduce((prev, key) => (
        addition(row[key], prev)
      ),0)
    },
    handleChange(val){
      if(!val){
        this.$message.warning("请选择截止日期!")
        return
      }

      const day = dayjs(val).format('YYYY-MM-DD')
      this.day = day;
      this.searchList();
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 0) {
        //合并相同的名字
        let nameSpan = this.getSpanNumber(this.tableData, "name");
        return {
          rowspan: nameSpan[rowIndex],
          colspan: 1,
        };
      }
    },
    //获取要合并的行数
    getSpanNumber(data, prop) {
      //data要处理的数组，prop要合并的属性，比如name

      //数组的长度，有时候后台可能返回个null而不是[]
      let length = Array.isArray(data) ? data.length : 0;
      if (length > 0) {
        //用于标识位置
        let position = 0;
        //用于对比的数据
        let temp = data[0][prop];
        //要返回的结果
        let result = [1];
        //假设数据是AABCC，我们的目标就是返回20120
        for (let i = 1; i < length; i++) {
          if (data[i][prop] == temp) {
            //标识位置的数据加一
            result[position] += 1;
            //当前位置添0
            result[i] = 0;
          } else {
            //不相同时，修改标识位置，该位置设为1，修改对比值
            position = i;
            result[i] = 1;
            temp = data[i][prop];
          }
        }
        //返回结果
        return result;
      } else {
        return [0];
      }
    },
    async searchList() {
      this.loading = true;
      this.tableData = [];

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

      if (res.code === 0 && res.data && res.data.length > 0) {
        const list = []
        Object.keys(res.data).forEach(key => {
          const { name , result = {}} = res.data[key]
          if(result.length === 0){
            list.push({name, 0: '--',  1:0, 2:0, 3:0,  4:0, 5:0, 6:0 })
          }else{
            Object.keys(result).forEach(key => {
              list.push({ name, ...result[key] })
            })
          }
        })

        const totalItem = {
          0:'--',
          ...list.reduce((prev,current) => {
            const {name,...rest} = current;
            const keys = Object.keys(rest)
            return keys.reduce((pObj,key) => {
              return {
                ...pObj,
                [key]:addition(current[key] || 0,prev[key] || 0)
              }
            },{})
          }, {})
        }


        totalItem['name'] = '合计'
        totalItem['0'] = '--'
        list.push(totalItem)

        this.tableData = list
      } else {
        this.tableData = [];
      }

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