<template>
  <div class="app-container">
    <el-form size="mini" :inline="true">
      <el-form-item label="关联会议">
        <el-select size="small" placeholder="关联会议" clearable filterable v-model="meetingWeek" @change="changeWeekData()">
          <el-option v-for="(item,index) in meetingData" :label="item.meetingName" :key="item.id" :value="item.weeks"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-download" @click="generateWeekly()" v-show="false">周报生成</el-button>
      </el-form-item>
    </el-form>
    <div ref="exportPdf" id="exportPdf">
      <div>
        <h3>本周工作内容</h3>
        <el-table
          border
          stripe
          size="mini"
          style="width: 80%" v-model="workContents" :data="workContents"
          @row-click="rowClick" :span-method="objectSpanMethod" :highlight-current-row="true">
          <el-table-column label="分类" prop="classifyName" width="80">
          </el-table-column>
          <el-table-column label="项目" prop="projectName" width="120">
          </el-table-column>
          <el-table-column label="模块" prop="moduleName" width="150">
          </el-table-column>
          <el-table-column label="任务名称" prop="taskName" width="250">
          </el-table-column>
          <el-table-column label="工作反馈" prop="description">
            <template slot-scope="scope">
              <span v-if="scope.row.description!==''" v-for="(item,index) in scope.row.description.split(',') ">
                {{index+1}}.<span v-html="stripTags(item)"></span><br/>

              </span>
            </template>
          </el-table-column>
          <el-table-column label="最新进度" prop="scheduleValue" width="100">
            <template slot-scope="scope">
              {{scope.row.scheduleValue}}%
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div>
        <h3>下周工作计划</h3>
        <el-table
          border
          stripe
          size="mini"
          style="width: 80%" :data="workPlans">
          <el-table-column type="index" label="序号" width="60">
          </el-table-column>
          <el-table-column label="工作计划" prop="workPlan">
            <template slot-scope="scope">
              <el-input size="mini" type="textarea" :autosize="{ minRows: 4, maxRows: 10}" v-model="scope.row.planContent" ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="预计完成时间" prop="completionTimes">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.completionTimes"
                type="date"
                size="mini"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                placeholder="选择日期">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="所属项目" prop="projectId">
            <template slot-scope="scope">
              <el-select v-model="scope.row.projectId" placeholder="请选择" size="mini">
                <el-option
                  v-for="item in projects"
                  :key="item.id"
                  :label="item.projectName"
                  :value="item.id">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" prop="op" width="150" v-if="currentWeek===weeks">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="addRow()">添加</el-button>
              <el-button size="mini" type="danger" @click="deleteRow(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

    </div>
    <div style="margin-top: 50px;margin-right: 150px;  width: 65%;text-align: center">
      <el-button size="mini" type="primary" @click="saveWorkPlan()" v-if="currentWeek===weeks">保存工作计划</el-button>
    </div>

    <!-- 任务详情对话框 -->
    <el-dialog title="任务详情" :visible.sync="taskOpen" width="680px" append-to-body
               :close-on-click-modal="false">
      <task-detail :detail-form="taskForm"></task-detail>
    </el-dialog>

  </div>
</template>

<script>

import {list} from '@/api/meeting/meeting'
import { deleteWorkPlanById, getMeetingsAndWorkPlansByWeeks, getProjects, saveWorkPlans } from '@/api/meeting/work'
import {getTask} from "@/api/task/task";
import TaskDetail from "../task/components/taskDetail"


export default {
  name: 'weekly',
  components: {TaskDetail},
  data() {
    return {
      meetingWeek: null,
      meetingData: [],
      workContents: [],
      projects:[],
      workPlans: [{
        planContent: '请填写工作计划信息',
        id: null,
        meetingId: null,
        completionTimes: null,
        completionTime: null,
        projectId: null
      }],
      meetingStatus: null,
      weeks: null,
      currentWeek: null,
      meetingId: null,
      taskOpen: false,
      taskForm:{},
      mergeObj: {}, // 用来记录需要合并行的下标
      mergeArr: ['classifyName','projectName','moduleName'], // 表格中的列名
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    stripTags(html) {
      return html.replace(/<\/?[^>]+(>|$)/g, '');
    },
    getData() {
      list().then(response => {
        this.meetingData = response.data
        this.meetingId = this.meetingData.id
        //js 获取当前周
        const date = new Date();
        // 获取当前第几周
        let week = this.getYearWeek(date.getFullYear(), Number(date.getMonth()) + 1, date.getDate());
        let currentWeek = week ;
        this.meetingWeek = currentWeek
        this.getMeetingsAndWorkPlansByWeeksData(currentWeek)
      })
      getProjects().then(res=>{
        this.projects=res.data
      });
    },
    getMeetingsAndWorkPlansByWeeksData(currentWeek) {
      let weekss = currentWeek
      getMeetingsAndWorkPlansByWeeks(currentWeek).then(response => {
        this.workContents = response.data.workContent
        this.getSpanArr(this.workContents);
        if (response.data.workPlan != null && response.data.workPlan.length > 0) {
          this.workPlans = response.data.workPlan
        }else{
          this.workPlans=[{
            planContent: '请填写工作计划信息',
            id: null,
            meetingId: null,
            completionTimes: null,
            completionTime: null,
            projectId: null
          }]
        }
        this.weeks = response.data.weeks
        const date = new Date();
        // 获取当前第几周
        let week = this.getYearWeek(date.getFullYear(), Number(date.getMonth()) + 1, date.getDate());
        let currentWeek = week ;
        this.currentWeek = currentWeek;
        if (weekss !== currentWeek) {
          this.workPlans = response.data.workPlan
        }
        let obj = {};
        obj = this.meetingData.find(item => {
          return item.weeks === currentWeek;
        });
        this.meetingId =obj.id
      })
    },
    getYearWeek(a, b, c) {
      let date1 = new Date(a, parseInt(b) - 1, c),
        date2 = new Date(a, 0, 1),
        d = Math.round((date1.valueOf() - date2.valueOf()) / 86400000);
      return Math.ceil((d + (date2.getDay() + 1 - 1)) / 7);
    },
    getWorkData() {

    },
    generateWeekly() {
      if (this.meetingWeek == null || this.meetingWeek == undefined || this.meetingWeek === '') {
        this.$message({
          message: '请选择会议信息!',
          type: 'warning'
        });
        return
      }
      this.$PDFSave(this.$refs.exportPdf, "我的工作周报");
    },
    saveWorkPlan() {
      if (this.meetingWeek === null || this.meetingWeek === undefined || this.meetingWeek === '') {
        this.$message({
          message: '请选择会议信息!',
          type: 'warning'
        });
        return
      }
      //判断是否存在周会信息，无周会信息，就不保存工作计划
      let meetingId=this.meetingId
      if(meetingId===undefined || meetingId===null){
        this.$message.warning("请选择周会会议，再填写工作计划!")
        return
      }

      let workPlanss = this.workPlans;
      for (let i = 0; i < workPlanss.length; i++) {
        if(workPlanss[i].planContent==='' || workPlanss[i].completionTimes===''){
          this.$message({
            message: '请将工作计划填写完整!',
            type: 'warning'
          });
          return
        }
        workPlanss[i].completionTime = null;
      }
      let data = {
        weeks: this.meetingWeek,
        workPlans: workPlanss,
        id: this.workPlans.id,
        meetingId: this.meetingId
      }
      saveWorkPlans(data).then(res => {
        this.$message({
          message: '操作成功',
          type: 'success'
        });
        this.getData()
      });
    },
    addRow() {
      let row = {planContent: '', 'op': '', id: null, completionTimes: null}
      this.workPlans.push(row)
    },
    deleteRow(index, row) {
      if (index == 0) {
        this.$message({
          message: '不能删除此条数据',
          type: 'warning'
        });
        return;
      }
      this.workPlans.splice(index, 1)
      let id = row.id;
      if (id != null) {
        deleteWorkPlanById(id).then(res => {
          this.getMeetingsAndWorkPlansByWeeksData(this.meetingWeek)
        });
      }

    },
    changeWeekData() {
      this.getMeetingsAndWorkPlansByWeeksData(this.meetingWeek)

    },
    /** 查看任务详情*/
    rowClick(row, column, event) {
      getTask(row.taskId).then(res => {
        this.taskForm = res.data;
        this.taskOpen = true;
      })
    },
    objectSpanMethod({row, column, rowIndex, columnIndex}) {
      if (this.mergeArr.indexOf(column.property) !== -1) {
        // 判断其值是不是为0
        if (this.mergeObj[column.property][rowIndex]) {
          return [this.mergeObj[column.property][rowIndex], 1]
        } else {
          // 如果为0则为需要合并的行
          return [0, 0];
        }
      }
    },

    getSpanArr(data) {
      this.mergeArr.forEach((key, index1) => {
        let count = 0; // 用来记录需要合并行的起始位置
        this.mergeObj[key] = []; // 记录每一列的合并信息

        data.forEach((item, index) => {
          // index == 0表示数据为第一行，直接 push 一个 1
          if (index === 0) {
            this.mergeObj[key].push(1);
            //item.group=index;
          } else {
            // 判断当前行是否与上一行其值相等 如果相等 在 count 记录的位置其值 +1 表示当前行需要合并 并push 一个 0 作为占位
            if (item[key] === data[index - 1][key]) {
              this.mergeObj[key][count] += 1;
              this.mergeObj[key].push(0);
              //item.group = this.tableData[index - 1].group;
            } else {
              // 如果当前行和上一行其值不相等
              count = index; // 记录当前位置
              this.mergeObj[key].push(1); // 重新push 一个 1
              // item.group = this.tableData[index - 1].group + 1; //如果不一样 将组号设置为上一个数据的组号加1
            }
          }
        })

      })
    },
  }
}
</script>

<style scoped lang="scss">
.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
  margin-bottom: 10px;
}
</style>
