<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="year" 
          size="mini" 
          type="year" 
          placeholder="选择年份" 
          @change="handleChange" 
        />
    </div>
    
    <el-table :data="tableData" size="mini" border :span-method="objectSpanMethod">
      <el-table-column  width="120px" label="申请人所属部门" prop="name" />

      <el-table-column label="订单状态" width="110px">
        <template slot-scope="scope">
          {{ scope.row.result.status }}
        </template>
      </el-table-column>
      <el-table-column label="下单月份" align="center" v-if="months">
        <el-table-column :label="month.length > 1 ? month : '0' + month" v-for="month in months" :key="month" min-width="100px">
          <template slot-scope="scope">
              {{getField(month, scope.row, scope.row.name === '无地址订单总金额')}}
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="总计" width="110px">
        <template slot-scope="scope">
          {{getTotal(scope.row, scope.row.name === '无地址订单总金额')}}
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

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

function unit2TenThousand(value){
  if(value === NaN || value === "NaN" || Number(value) === 0) return '0'
  if(value < 1000 && value > 0 || value < 0 && value > -1000) return value
  return division(value, 10000).toFixed(2) + 'W'
}

export default {
  name: "Consult",
  mixins: [setHeight],
  props: ['title'],
  watch: {
    date: function(val) {
      this.dataTime = val;
      if (val && val.length === 2) {
        this.searchList();
      }
    }
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          //  return time.getTime() > Date.now() - 8.64e7;
          return time.getTime() > Date.now();
        }
      },
      tableData:[],
      date:"",
      year:"",
      months: ['1','2','3','4','5','6','7','8','9','10','11','12'],
      loading:false,
      statusOptions: [
        { id: "0", label: "待发货" },
        { id: "1", label: "待发货完成" },
        { id: "2", label: "发货已完成" },
        { id: "3", label: "订单已取消" }
      ]
    };
  },
  async created() {
    this.handleChange(dayjs(new Date()).format('YYYY'))
    window.onresize = () => {
      this.getHeight();
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.getHeight();
    });
    // this.searchList();
  },
  methods: {
    getStatus(row){
      const key = Object.keys(row.result).find(month => row.result[month] && row.result[month]['1'] && row.result[month]['1'].send_status)
      if(!key) return '--'
      return (this.statusOptions.find(({id}) => {
        return id === row.result[key]['1'].send_status
      }) || {}).label || '--'
    },
    handleChange(val){
      if(!val){
        this.$message.warning("请选择年份!")
        return
      }

      const year = dayjs(val).format('YYYY')
      this.year = year;
      this.searchList();
    },
        //获取要合并的行数
    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];
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 0) {
        //合并相同的名字
        let nameSpan = this.getSpanNumber(this.tableData, "name");
        return {
          rowspan: nameSpan[rowIndex],
          colspan: 1,
        };
      }
    },
    getTotal(row, isTotalPrice){
      if(isTotalPrice){
        const total =  this.months.reduce((prev, month) => {
          return addition(prev, row.result[month] ? row.result[month]['total_price'] : 0)
        },0)
        return Number(total) === 0 ? "0元" : unit2TenThousand(total) + "元"
      }


      return this.months.reduce((prev, key) => {
        return addition(prev, ((row.result[key] || {})['1'] || {}).num || 0)
      },0)
    },
    getField(month, row, isTotalPrice){
      if(Array.isArray(row.result[month])) return 0
      if(month === 'status') {
        return 0
      }

      if(isTotalPrice){
        const { total_price } =  row.result[month]
        return Number(total_price) === 0 ? "0元" : unit2TenThousand(total_price) + "元"
      }

      return ((row.result[month] || {})['1'] || {}).num || 0
    },
    async searchList() {
      // if(!this.year){
      //   return
      // }
      this.loading = true;
      this.tableData = [];

      const res = await asyncRequest.wsendOrder({
        start_y: this.year,
      });

      if (res.code === 0 && res.data) {
        const result = Object.keys(res.data.result).reduce((prev, key) => ([...prev, res.data.result[key]]),[])
        this.tableData = result
        const { noAddr } = res.data

        const tableData = []
        for(const item of result){
          const { name, result } = (item || {});
          for(let i = 0; i < 2; i++){
            tableData.push({name,
              result: Object.keys(result).reduce((prev,month) => ({
                ...prev,
                status: i === 0 ? '待发货' : '待发货完成',
                [month]: {
                  '1':Array.isArray(result[month]) 
                  ? { num : 0 ,send_status : null} 
                  : { num : result[month][i + 1] ? result[month][i + 1].num :  0,
                      send_status : result[month][i + 1] ? result[month][i + 1].send_status : null
                   }
                }
              }), {})
            })
          }
        }

        this.tableData = tableData.reduce((prev,current) => {
            return [...prev, {
              name: current.name,
              result: this.months.reduce((pre,month) => {
               return {
                ...pre,
                status:current.result.status ? current.result.status : '--',
                [month]:{
                  '1': current.result[month] && current.result[month]['1'] ? { ... current.result[month]['1']} : {num: 0 ,send_status : null},
                  '2': current.result[month] && current.result[month]['2'] ? {...current.result[month]['2']} : {num: 0, send_status : null },
                }
              }
              },{})
            }]
        },[])


        const totalItemDefault = this.months.reduce((prev,month) => ({
          ...prev,
          [month]:{ 1:{ num:0 }}
        }), {})

        const totalItem = {
          name:'合计',
          result: this.tableData.reduce((prev,current) => {
            const { result} = current;
            return this.months.reduce((pre,month) => {
              const res = Array.isArray(result[month]) ? ({num : 0}) : (result[month]['1'] || {num : 0});
              const { num } = res;
              const newNum = addition(prev[month]['1'].num, num)
              return { ...pre, [month]: { 1: { num:newNum }}
              }
            }, {})
          },{...totalItemDefault})
        }


        totalItem.result.status = "--"
        this.tableData.push(totalItem)

        noAddr.name = "无地址订单总金额"
        
        noAddr.result = this.months.reduce((prev,month) => ({
          ...prev,
          [month]:{
            total_price:noAddr.result[month] && noAddr.result[month].total_price 
            ? noAddr.result[month].total_price 
            : 0 
          }
        }),{})

        noAddr.result.status = "--"
        this.tableData.push(noAddr)
      } else {
        this.tableData = [];
      }

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