<template>
  <div>
     <el-table :data="treeDataList" height="490px" row-key="id" :key="'1'" show-overflow-tooltip :cell-style="TableCellStyle" size="mini" :span-method="arraySpanMethod" style="width: 100%;margin-bottom: 20px;" border default-expand-all :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column prop="text" label="姓名" width="240" fixed="left" v-if="stafforpro != '按项目查看'">
          <template slot-scope="scope">
              <!-- user.userNameNeedTranslate == 1 -->
              <span v-if="user.userNameNeedTranslate == 1 && scope.row.translationType == 'department'"><TranslationOpenDataText type='departmentName' :openid='scope.row.text'></TranslationOpenDataText></span>
              <span v-if="user.userNameNeedTranslate == 1 && scope.row.translationType == 'user'"><TranslationOpenDataText type='userName' :openid='scope.row.text'></TranslationOpenDataText></span>
              <span v-if="user.userNameNeedTranslate == 1 && (scope.row.translationType == 'null' || scope.row.translationType == null)">{{scope.row.text}}</span>
              <span v-if="user.userNameNeedTranslate != 1">{{scope.row.text}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="text" label="项目" width="240" fixed="left" v-if="stafforpro == '按项目查看'">
          <template slot-scope="scope">
            <span v-if="user.userNameNeedTranslate == 1 && scope.row.translationType == 'user'">
              <span v-for="(item, index) in scope.row.userNameList" :key="index">
                <!-- <TranslationOpenDataText type='userName' :openid='scope.row.text'></TranslationOpenDataText> -->
                <TranslationOpenDataText type='userName' :openid='item'></TranslationOpenDataText>
                <span v-if="index < scope.row.userNameList.length - 1">,</span>
              </span>
            </span>
            <span v-if="user.userNameNeedTranslate == 1 && scope.row.translationType == 'user'">{{scope.row.proNameText}}</span>
            <span v-if="user.userNameNeedTranslate == 1 && (scope.row.translationType == 'null' || scope.row.translationType == null)"> {{scope.row.text}}</span>
            <span v-if="user.userNameNeedTranslate != 1">{{scope.row.text}}</span>
          </template>
        </el-table-column>
        <el-table-column :label="item.name" v-for="(item, index) in headerData" :key="index">
            <el-table-column :label="items" v-for="items, idx in item.children" :key="idx" width="120px" align="center">
              <template slot-scope="scope">
                <div>
                  <!-- <span v-if="scope.row.translationType == 'user' && scope.column.label.indexof(scope.row.end_date) != '-1'">
                    <TranslationOpenDataText type='userName' :openid='scope.row.text'></TranslationOpenDataText>
                  </span> -->
                  <span v-if="scope.row.translationType != 'user' && stafforpro != '按项目查看'">
                    <!-- {{scope.row.end_date | dataValue(scope.column, scope.row)}} -->
                    <!-- {{scope.row.start_date | dataValue(scope.column, scope.row)}} -->
                    {{scope.row.con_data | dataValue(scope.column, scope.row)}}
                  </span>
                  <span v-if="stafforpro == '按项目查看'">
                    <!-- {{scope.row.end_date | dataValue(scope.column, scope.row)}} -->
                    <!-- {{scope.row.start_date | dataValue(scope.column, scope.row)}} -->
                    {{scope.row.con_data | dataValue(scope.column, scope.row)}}
                  </span>
                </div>
              </template>
            </el-table-column>
        </el-table-column>
     </el-table>
  </div>
</template>

<script>
export default {
  props: {
    stafforpro: {
        type: [String, Array, Object],
        default: false
    },
    valueDate:{
        type: [String, Array, Object],
        default: false
    },
    updatakey1:{
        type: [String, Array, Object],
        default: false
    },
    tasks: {
        type: Array,
        default: []
    }
  },
  components: {},
  data() {
    return {
        that: this,
        initialMonth: '', // 开始月份
        headerData: [], // 表头数据
        treeDataList: [],
        num: 0,
        mergeList: [],
        valueDateList: [],
        user: JSON.parse(sessionStorage.getItem("user")),
    };
  },
  filters: {
    // dataValue: function (endDate, item, value) {
    //   if(endDate) {
    //     let biaoto = item.label.split(' ')[0]
    //     if(biaoto == value.end_date) {
    //       if(value.text.indexOf('/') != '-1') {
    //         return value.text.split('/')[1]
    //       } else {
    //         return value.text
    //       }
    //     }
    //   }
    // }

    dataValue: function (endDate, item, value) {
      if(endDate) {
        let biaoto = item.label.split(' ')[0]
        let maxData =  value.numData
        let str = ''
        if(value.text.indexOf('/') != '-1') {
          str = value.text.split('/')[1]
        } else {
          str = value.text
        }

        if(maxData == 2 && biaoto == value.end_date) {
          return str
        } else if(maxData != 2 && biaoto == value.con_data){
          return str
        }

        // if(biaoto == endDate) {
        //   if(value.text.indexOf('/') != '-1') {
        //     return value.text.split('/')[1]
        //   } else {
        //     return value.text
        //   }
        // }
      }
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    console.log(this.dayjs('2023-04-14').diff('2023-04-12', 'day'), '值差异') 
    console.log(this.dayjs('2023-04-14').add(Math.ceil((3/2)),'day').format('YYYY-MM-DD'))
    console.log(this.stafforpro,'值')
    // 重置两个属性值
    this.num = 0,
    this.mergeList = []
    let dataList = []
    let allDataList = []
    this.valueDateList = this.valueDate
    let star = this.valueDate[0].split('-')
    let end = this.valueDate[1].split('-')
    this.initialMonth = star[0] + '-' + star[1]
    dataList = this.getYearAndMonth(star[0] + '-' + star[1], end[0] + '-' + end[1])
    allDataList = this.getdiffdate(this.valueDate[0], this.valueDate[1])
    this.combination(dataList, allDataList)
    // 递归加颜色
    console.log(this.tasks.data, '芜湖')

    this.treeDataList = this.recursive(this.tasks.data);

    console.log(this.mergeList, '合并数据')
    console.log(this.treeDataList, '合并完全的数据')
  },
  methods: {
    // 递归加颜色以及存储需要合并的数据
    recursive(data) {
      for (let i in data) {
            if(this.stafforpro == '按项目查看') {
              data[i].color = '#409EFF'
              if(data[i].translationType == 'user' && data[i].text) {
                let arr = []
                arr = data[i].text.split(',')
                for(var j in arr) {
                  if(arr[j].indexOf('/') != '-1') {
                    arr[j] = arr[j].split('/')[0]
                  }
                }
                data[i].userNameList = arr
              }

            }
            this.num++
            let obj = {
              ins: this.num,
              numDay: 1,
              column: 1
            }

            if(data[i].end_date) {
              var endData = ''
              var starData = ''
              if(data[i].end_date < this.valueDateList[1]) {
                endData = data[i].end_date
              } else {
                endData = this.valueDateList[1]
              }

              if(data[i].start_date < this.valueDateList[0]) {
                starData = this.valueDateList[0]
              } else {
                starData = data[i].start_date
              }

              obj.numDay = +this.dayjs(endData).diff(starData, 'day') + 1
              obj.column = +this.dayjs(starData).diff(this.valueDateList[0], 'day') + 1

              if(data[i].text == '209') {
                console.log(obj, '看看数据')
              }
              if(obj.numDay > 2) {
                data[i].con_data = this.dayjs(starData).add(1,'day').format('YYYY-MM-DD')
              } else {
                data[i].con_data = starData
              }
              data[i].numData = obj.numDay
            }

            // if(data[i].end_date) {
            //   let day = this.dayjs(data[i].end_date).diff(data[i].start_date, 'day') // 和并多少行
            //   let column = +this.dayjs(data[i].end_date).diff(this.valueDateList[0], 'day') + 1 // 从多少列开始
            //   if(day >= 1) {
            //     if(day >= 3) {
            //       if(this.valueDateList[0] > data[i].start_date) {
            //         obj.column = 1
            //         day >= column ? obj.numDay = column : obj.numDay = day
            //       } else {
            //         let num = this.dayjs(data[i].start_date).diff(this.valueDateList[0], 'day')
            //         obj.column = +num + 1
            //         day >= column ? obj.numDay = column : obj.numDay = day
            //       }
            //     } else {
            //       day >= column ? obj.numDay = column : obj.numDay = day
            //       obj.column = column
            //     }
            //   }
            // }
            // if(data[i].end_date != data[i].start_date && data[i].end_date != this.valueDateList[0]) {
            //   data[i].end_date = this.dayjs(this.valueDateList[0]).add('1','day').format('YYYY-MM-DD')
            //   if(data[i].end_date < data[i].start_date) {
            //     data[i].end_date = this.dayjs(data[i].start_date).add('1','day').format('YYYY-MM-DD')
            //   }
            // }

            this.mergeList.push(obj)
            if(data[i].id.indexOf(this.$t('chu-cha')) != '-1') {
              data[i].color = '#E6A23C'
            }
            if(data[i].id.indexOf(this.$t('other.AskForLeave')) != '-1') {
              data[i].color = '#F56C6C'
            }
            if(data[i].id.indexOf('任务') != '-1') {
              if(data[i].level == 0) {
                data[i].color = '#409EFF'
              }
              if(data[i].level == 1) {
                data[i].color = '#F56C6C'
              }
              if(data[i].level == 2) {
                data[i].color = '#E6A23C'
              }
            }
            if (data[i].children) {
                this.recursive(data[i].children);
            }
        }
        return data
    },
    // 截取两个日期的月份数
     getYearAndMonth(start, end) {
      console.log(start, end)
      let monthList = [];
      let starts = start.split('-');
      let ends = end.split('-');
      let staYear = parseInt(starts[0]);
      let staMon = parseInt(starts[1]);
      let endYear = parseInt(ends[0]);
      let endMon = parseInt(ends[1]);
      while (staYear <= endYear) {
        if (staYear === endYear) {
          while (staMon < endMon) {
            staMon++;
            var str = staYear + '-'+(staMon >= 10 ? staMon : '0' + staMon);
            monthList.push(str);
          }
          staYear++;
        } else {
          staMon++;
          if (staMon > 12) {
            staMon = 1;
            staYear++;
          }
          let str = staYear + '-'+(staMon >= 10 ? staMon : '0' + staMon);
          monthList.push(str);
        }
      }
      return monthList;
    },
    // 获取所有期间的日期
    getdiffdate(stime,etime){
      var diffdate = new Array();
      var i=0;
      while(stime<=etime){
          diffdate[i] = stime;
          var stime_ts = new Date(stime).getTime();
          var next_date = stime_ts + (24*60*60*1000);
          var next_dates_y = new Date(next_date).getFullYear()+'-';
          var next_dates_m = (new Date(next_date).getMonth()+1 < 10)?'0'+(new Date(next_date).getMonth()+1)+'-':(new Date(next_date).getMonth()+1)+'-';
          var next_dates_d = (new Date(next_date).getDate() < 10)?'0'+new Date(next_date).getDate():new Date(next_date).getDate();
          stime = next_dates_y+next_dates_m+next_dates_d;
          i++;
      }
      return diffdate
    },
    // 计算组合月份和日期
    combination(month, data) {
      let monthStr = [this.initialMonth, ...month]
      let arrList = []
      let weekArrayList = ['周日', '周一', '周二', '周三', '周四', '周五', '周六',]
      for(let i in monthStr) {
        let obj = {}
        obj.name = monthStr[i]
        obj.children = []
        for(let j in data) {
          let index = new Date(data[j]).getDay()
          if(data[j].indexOf(monthStr[i]) != '-1') { 
            obj.children.push(data[j] + ' (' + weekArrayList[index] + ')')
          }
        }
        arrList.push(obj)
      }
      this.headerData = arrList
      console.log(this.headerData)
    },
    // 接收的数据整合成树形结构
    integrationTree(data) {
       let treeData = []
       if(!Array.isArray(data)) {
           return treeData
       }
       data.forEach(item => {
           delete item.children;
       });
       let map = {};
       data.forEach(item => {
        if(item.text == '杨峰') {
          console.log(item)
        }
           map[item.id] = item;
       });
       data.forEach(item => {
           let parent = map[item.parent];
           if(parent) {
               (parent.children || (parent.children = [])).push(item);
           } else {
               treeData.push(item);
           }
       });
       return treeData;
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
        if (rowIndex == +this.mergeList[rowIndex].ins -1) {
          if(this.mergeList[rowIndex].numDay > 1) {
            if (columnIndex == +this.mergeList[rowIndex].column + 1) {
              return [1, +this.mergeList[rowIndex].numDay];
            } else if(columnIndex == 1){
              return [0, 0];
            }
          }
        }
    },
    // 设置每一个单元格的样式
    TableCellStyle(row) {
      let maxData =  +this.dayjs(row.row.end_date).diff(row.row.start_date, 'day') + 1
      if(row.row.color && maxData < 3) {
        let biaoto = row.column.label.split(' ')[0]
        if(biaoto == row.row.end_date) {
          if(row.row.color) {
            return 'background-color: '+ row.row.color +' !important;color: #fff'
          }
        }
      } else {
        let biaoto = row.column.label.split(' ')[0]
        if(biaoto == row.row.con_data) {
          return 'background-color: '+ row.row.color +' !important;color: #fff'
        }
      }

      // if(row.row.color) {
      //   let biaoto = row.column.label.split(' ')[0]
      //   if(biaoto == row.row.con_data) {
      //     if(row.row.color) {
      //       return 'background-color: '+ row.row.color +' !important;color: #fff'
      //     }
      //   }
      // }

    }
  },
};
</script>

<style>
</style>
