<template>
  <div class="app-container">
    <div style="display: flex;justify-content: space-between;margin-bottom: 8px">
      <div style="font-size: 24px">{{ m.meetingName }}</div>
      <div>
        <el-button @click="jumpPage"  size="mini">返回</el-button>
        <el-button v-if="m.status===1" size="mini" type="primary" @click="endMeetingClick(m)">结束会议
        </el-button>
        <el-button size="mini" @click="meetingResultConfirm"  v-if="meetingResultConfirmVisible" type="primary">会议结果确认</el-button>
        <el-button size="mini" @click="exportPdf" type="success" style="margin-right: 20px" v-if="workScoreVisible">导出</el-button>
      </div>
    </div>
    <el-descriptions title="" :column="2" :size="size" border>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-user"></i>
          会议时间
        </template>
        {{ m.beginTime }}至{{ m.endTime }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-user"></i>
          会议主持人
        </template>
        {{ m.emcee }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-location-outline"></i>
          会议地点
        </template>
        {{ m.meetingPlace }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-user"></i>
          会议记录人
        </template>
        {{ m.recorder }}
      </el-descriptions-item>
      <el-descriptions-item >
        <template slot="label">
          <i class="el-icon-user"></i>
          参会人员
        </template>
        <span v-if="m.innerAttendees!=''" v-for="(item,index) in JSON.parse(m.innerAttendees)">
          <el-badge is-dot v-if="item.flag==='1'" type="success">
          &nbsp;&nbsp;&nbsp; {{ item.name }}
          </el-badge>
           <el-badge is-dot v-else type="danger">
          &nbsp;&nbsp;&nbsp; {{ item.name }}
          </el-badge>
        </span>
      </el-descriptions-item>
      <el-descriptions-item >
        <template slot="label">
          <i class="el-icon-user"></i>
          参会时长
        </template>
        <el-input-number size="small" :disabled="workRemarkReadOnly" v-model="m.duration" @change="workMeetingsUpdate(m)"></el-input-number> 分钟
      </el-descriptions-item>
      <el-descriptions-item :span="2">
        <template slot="label">
          <i class="el-icon-office-building"></i>
          参会情况
        </template>
        <el-input  :readonly="workRemarkReadOnly" type="textarea" v-model="m.remark" :rows="3" @change="workMeetingsUpdate(m)"></el-input>
      </el-descriptions-item>
    </el-descriptions>
    <el-table
      style="width: 100%" border stripe :data="tableData" :highlight-current-row="true"
      :span-method="objectSpanMethod" @cell-click="addWorkPlanWin">
      <el-table-column prop="group" label="序号" width="60" align="center">
      </el-table-column>
      <el-table-column
        prop="userName"
        label="姓名" align="center"
        width="120">
        <template slot-scope="scope">
          {{scope.row.userName}}({{scope.row.weekCostWorkTime}})
        </template>
      </el-table-column>
      <el-table-column label="本周工作总结" min-width="450">
        <el-table-column label="工作内容" prop="taskName">
          <template slot-scope="scope">

            <div class="underline-on-hover"  @click="getTaskScheduleRemarks(scope.row)">
              <div v-if="scope.row.taskId!==undefined && scope.row.taskId!=null">
                {{scope.row.taskId}}、 {{ scope.row.taskName }}
                ({{scope.row.projectName}})&nbsp;&nbsp;&nbsp;&nbsp;花费工时:({{scope.row.taskCostWorkTime}})
              </div>
              <div v-else>
               1、 {{ scope.row.taskName }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="任务详情" prop="descriptions">
          <template slot-scope="scope">
            <div style="color: blue;float: right;display: inline-block" v-if="false" class="underline-on-hover" >任务详情</div>
            <div v-html="scope.row.description"> </div>
          </template>
        </el-table-column>
<!--        <el-table-column label="是否上周遗留" width="100" prop="lastWeekFlag" v-show="false">
          <template slot-scope="scope">
            <div v-if="scope.row.lastWeekFlag==='0'" style="color: darkred">是</div>
            <div v-else="scope.row.lastWeekFlag==='1'">否</div>
          </template>
        </el-table-column>-->
        <el-table-column label="完成情况说明" prop="progressValue" width="100">
          <template slot-scope="scope">
            <div style="color: darkgreen;">{{ scope.row.progressValue }}%
            </div>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column prop="workplan" label="下周工作计划">
        <el-table-column label="工作内容与完成时间" prop="planContent">
          <template slot-scope="scope">
            <div v-html="scope.row.planContent" >
            </div>
          </template>
        </el-table-column>
      </el-table-column>
<!--      <el-table-column prop="scores" label="评分" width="150" align="center" v-if="workScoreVisible">-->
<!--        <template slot-scope="scope">-->
<!--          <el-input-number size="mini" :precision="2" :step="0.1" :max="10" :min="0" v-model="scope.row.score" :value="0"-->
<!--                           @change="workComment(scope.row)">-->
<!--            {{ scope.row.score }}-->
<!--          </el-input-number>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column prop="remarks" label="备注">
        <template slot-scope="scope">
          <el-input v-model="scope.row.remark" :readonly="workRemarkReadOnly" type="textarea" :autosize="{ minRows: 4}" @change="workComment(scope.row)">
          </el-input>
        </template>
      </el-table-column>
<!--      <el-table-column prop="workComments" label="工作评论" v-if="workScoreVisible">
        <template slot-scope="scope">
          <el-input v-model="scope.row.workComment" type="textarea" :autosize="{ minRows: 4}" @change="workComment(scope.row)"></el-input>
        </template>
      </el-table-column>-->
    </el-table>

    <el-dialog
      :title="taskFeedbackTitle"
      :visible.sync="taskFeedbackVisible"
      width="30%"
      :close-on-click-modal="false">
      <div v-html="taskFeedbackContent"></div>
      <span slot="footer" class="dialog-footer">
      <el-button @click="taskFeedbackVisible = false" size="mini">取 消</el-button>
      <el-button type="primary" @click="taskFeedbackVisible = false" size="mini">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="workPlanTitle"  :visible.sync="workPlanVisible"  width="60%" center  @close="closeWorkPlanWin">
      <el-button type="primary" size="mini"  @click="addWorkPlan">添加</el-button>
      <el-table :data="workPlanDatas" stripe  style="width: 100%;margin-top: 5px;" size="mini">
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="planContent" label="任务名称" min-width="180" >
          <template slot-scope="scope">
            <el-input v-model="scope.row.planContent" placeholder="请输入任务名称"  size="mini"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="优先级" prop="priority" width="180">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.priority"
              placeholder="事项优先级">
              <el-option
                v-for="dict in dict.type.task_priority"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value">
                {{ dict.label }}
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="projectId" label="所属项目" width="150">
          <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 prop="completionTime" label="开始日期" width="150">
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.beginDate"
              type="date"
              size="mini"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              placeholder="选择日期" style="width: 140px">
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column prop="completionTime" label="截止日期" width="150">
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.completionTime"
              type="date"
              size="mini"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              placeholder="选择日期" style="width: 140px">
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column prop="op" label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="primary" v-if="(scope.row.taskId===undefined || scope.row.taskId===null) && scope.row.id!==null" size="mini"  @click="updateWorkPlan(scope.row)">修改</el-button>
            <el-button type="primary" v-if="(scope.row.taskId===undefined || scope.row.taskId===null) && scope.row.id===null" size="mini"  @click="addWorkPlanData(scope.row)">新增</el-button>
            <el-button type="danger"  v-if="(scope.row.taskId===undefined || scope.row.taskId===null) && scope.row.id!==null" size="mini"  @click="deleteWorkPlanByIds(scope.row)">删除</el-button>
            <el-button type="danger"  v-if="(scope.row.taskId===undefined || scope.row.taskId===null) && scope.row.id===null" size="mini"  @click="deleteRow(scope.$index, scope.row)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

  </div>
</template>
<script>

import {
  endMeeting,
  getMeetingByWeekss,
  getTaskScheduleRemark,
  getWeeksRecordsByWeeks, meetingAuthById, weekMeetingConfirms,
  workComments,
  workMeetingsUpdates
} from '@/api/meeting/meeting'

import {downloadPdf} from "@/api/meeting/meeting";
import {
  addWorkPlan,
  deleteWorkPlanById,
  getProjects,
  getWorkPlanByWeeks,
  getWorkPlanConfirmFlags,
  updateWorkPlan
} from '@/api/meeting/work'
import { editEnforceRemind } from '@/api/meeting/enforceRemind'

export default {
  name: 'weeklyRecords',
  dicts: [ 'task_priority'],
  data() {
    return {
      taskFeedbackTitle: '',
      taskFeedbackVisible: false,
      taskFeedbackContent: '',
      meetingResultConfirmVisible:false,
      title: '技术部周会',
      size: '',
      tableData: [],
      meetingId: null,
      weeks: null,
      m: {
        id: null,
        meetingName: '',
        external: 0,
        meetingType: 1,
        meetingPlace: null,
        beginTime: null,
        endTime: null,
        outAttendees: null,
        innerAttendees: '',
        emcee: null,
        recorder: null,
        createUserId: 1,
        createTime: null,
        status: 1,
        weeks: 46,
        duration:1
      },
      workContents: {
        col: 0,
        row: 0
      },
      mergeObj: {}, // 用来记录需要合并行的下标
      mergeArr: ['group', 'userName', 'planContent', 'scores', 'remarks', 'workComments'], // 表格中的列名
      workPlanDatas:[],
      workPlanTitle:'',
      workPlanVisible:false,
      projects:[],
      row:null,
      workScoreVisible:false,
      meetingConfirms:[],
      permissions:null,
      workRemarkReadOnly:true,
      meetingRemarkReadOnly:true
    }
  },
  created() {

  },
   mounted() {
     this.meetingId = this.$route.query.meetingId;
     this.weeks = this.$route.query.weeks;
     this.getData()
  },
  methods: {
    async executeCreate(){
      await this.getData()
      this.setPermissions()
    },
    setPermissions(){
      let loginUserId=this.$store.getters.userId
      //获取工作评分与工作评论权限
      let permissions= this.$store.getters.permissions;
      for(let i=0;i<permissions.length;i++){
        if(permissions[i]==='weekly:weekly:score'){
          this.workScoreVisible=true
          break;
        }
      }

      let meeting=this.m;
      let meetingStatus=meeting.status
      let workScoreVisible=this.workScoreVisible
      if(meetingStatus===2 && workScoreVisible===true){
        this.workScoreVisible=true
      }else{
        this.workScoreVisible=false
      }
      let innerAttendess=JSON.parse(meeting.innerAttendees)
      for(let i=0;i<innerAttendess.length;i++){
        let user=innerAttendess[i]
        if(Number(user.id)===Number(loginUserId)){
          if(user.flag==='0' && meetingStatus===2){
            this.meetingResultConfirmVisible=true
            break
          }
        }
      }
      let userName=this.$store.getters.name
      if((userName===meeting.recorder || userName===meeting.emcee) && meeting.status!==2 ){
        this.workRemarkReadOnly=false
      }
    },
    getData() {
      let loginUserId=this.$store.getters.userId
      let meetingId = this.meetingId
      let weeks = this.weeks
      if (meetingId != null && weeks != null) {
         getWeeksRecordsByWeeks(meetingId, weeks).then(res => {
          this.tableData = res.data.workContent
          this.getSpanArr(this.tableData);
          this.m = res.data.meeting
           let permissions=this.permissions;
           if(permissions===null){
             this.setPermissions();
             this.permissions=1
           }
        })
      } else {
        //获取当前周会会议id与所属周数
        getMeetingByWeekss().then(res => {
          let data = res.data;
          if(data===null || data.id===undefined){
            this.$message.warning('暂无属于你的周会会议!')
            return
          }
          if (data != null) {
            this.meetingId = data.id
            this.weeks = data.weeks
            getWeeksRecordsByWeeks(this.meetingId, this.weeks).then(res => {
              this.tableData = res.data.workContent
              this.getSpanArr(this.tableData);
              this.m = res.data.meeting
            })
          } else {
            this.tableData = []
          }
        })
      }

    },
    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
            }
          }
        })

      })
    },
    workComment(row) {
      let planContent=row.planContent;
      if(planContent.includes('下周暂无工作安排')){
        let userName=row.userName;
        let msg=userName+"下周工作计划未填写，请填写完后在评论评分!"
        this.$message({
          message: msg,
          type: 'warning'
        });
        return
      }
      let scoreId = row.scoreId
      let score = row.score
      let remark = row.remark
      let meetingId = row.meetingId
      let weeks = row.weeks;
      let userId = row.executor
      let workComment = row.workComment

      if (scoreId === meetingId) {
        scoreId = null
      }
      let data = {
        id: scoreId,
        score: score,
        remark: remark,
        weeks: weeks,
        userId: userId,
        workComment: workComment,
        meetingId:meetingId
      }
      workComments(data).then(res => {
        this.$message({
          message: '操作成功!',
          type: 'success'
        });
        this.getData()
      });
    },
    workMeetingsUpdate(m){
      let status=m.status
      if(status===2){
        this.$message.error("会议已经结束，不能更改会议相关信息!")
        return
      }
      workMeetingsUpdates(m).then(res => {
        this.$message({
          message: '操作成功!',
          type: 'success'
        });
        this.getData()
      })

    },
    getTaskScheduleRemarks(row) {
      if(row.taskId===undefined || row.taskId===null){
        this.taskFeedbackTitle=row.userName+''
        this.taskFeedbackContent='暂无反馈'
        this.taskFeedbackVisible = true
      }else {
        this.taskFeedbackTitle = row.userName + ":" + row.taskName

        getTaskScheduleRemark(row.taskId).then(res => {
          let content = res.data;
          let feedbackContent = '';
          let j = 1;
          for (let i = 0; i < content.length; i++) {
            feedbackContent += j + ":" + content[i].description + "&nbsp;&nbsp;&nbsp;&nbsp;" + content[i].value + "%" + "&nbsp;&nbsp;&nbsp" + '</br>'
            j++;
          }
          if (content.length === 0) {
            feedbackContent = '暂无反馈'
          }
          this.taskFeedbackContent = feedbackContent

        });
      }
      this.taskFeedbackVisible = true
    },
    exportPdf() {
      downloadPdf(this.meetingId, this.weeks)
    },
    meetingResultConfirm(){
      let m=this.m;
      if(m.status!==2){
        this.$message.warning("会议暂未结束，请结束后在确认会议结果!")
        return
      }
      weekMeetingConfirms(this.meetingId, this.weeks).then(res=>{
        let code=res.code;
        if(code==='2000'){
          this.$message({
            message: '操作成功!',
            type: 'success'
          });
          this.meetingResultConfirmVisible=false;
          this.getData()
        }else{
          this.$message({
            message: res.data,
            type: 'warning'
          });
        }
      })
    },
    addWorkPlanWin(row, column, cell, event){
      let label=column.label
      if(label==='工作内容与完成时间'){
        //已经确认的工作不能继续编辑工作计划，临时增加就去任务系统手动添加
        let meetingId=this.meetingId
        let data={
          weeks:this.weeks,
          userId:row.executor,
          meetingId:meetingId
        }
        getWorkPlanConfirmFlags(data).then(res=>{
          if(res.success!==true){
            this.$message.warning(res.data)
          }else{
            meetingAuthById(meetingId).then(res=> {
              if (res.success === false) {
                this.$message.error(res.data)
              }else{
                getProjects().then(res=>{
                  this.projects=res.data
                });

                let weeks=this.weeks
                let userId=row.executor
                let meetingId=this.meetingId
                this.workPlanTitle=row.userName+'下周工作计划'
                getWorkPlanByWeeks(weeks,userId,meetingId).then(res=>{
                  let datas=[]
                  let data=res.data
                  if(data.length>0){
                    for(let i=0;i<data.length;i++){
                      if(data[i].taskId!==undefined && data[i].taskId!==null){
                        continue
                      }
                      datas.push(data[i])
                    }
                  }
                  this.workPlanDatas=datas;
                })
                this.row=row
                this.workPlanVisible=true
              }
            });
          }
        })

      }
    },
    addWorkPlan(){
      let row={
        planContent: '',
        id: null,
        meetingId: null,
        completionTimes: null,
        completionTime: null,
        projectId: null,
        userId:null,
        taskId:null,
        beginDate:null,
        priority:'4'
      }
      this.workPlanDatas.push(row)
    },
    deleteRow(index, row){
      this.workPlanDatas.splice(index, 1)
    },
    addWorkPlanData(row){
      let content=row.planContent;
      if(content===null || content===''){
        this.$message.warning("请输入工作内容!")
        return
      }
      let beginDate=row.beginDate
      if(beginDate===null || beginDate===''){
        this.$message.warning("请选择开始日期!")
        return
      }
      let completionTime=row.completionTime
      if(completionTime===null || completionTime===''){
        this.$message.warning("请选择截止日期!")
        return
      }
      let userId=this.row.executor
      let weeks=this.weeks
      let data={
        planContent:row.planContent,
        projectId:row.projectId,
        completionTime:new Date(completionTime).getTime(),
        meetingId:this.meetingId,
        userId:userId,
        weeks:weeks,
        beginDate:new Date(beginDate).getTime(),
        priority:row.priority
      }
      addWorkPlan(data).then(res=>{
        this.$message.success("操作成功!")
        getWorkPlanByWeeks(weeks,userId,this.meetingId).then(res=>{
          let datas=[]
          let data=res.data
          if(data.length>0){
            for(let i=0;i<data.length;i++){
              if(data[i].taskId!==undefined && data[i].taskId!==null){
                continue
              }
              datas.push(data[i])
            }
          }
          this.workPlanDatas=datas
        })
      })
    },
    updateWorkPlan(row){
      let id=row.id;
      let beginDate=row.beginDate
      if(beginDate===null || beginDate===''){
        this.$message.warning("请选择开始日期!")
        return
      }
      let completionTime=row.completionTime
      if(completionTime===null || completionTime===''){
        this.$message.warning("请选择截止时间!")
        return
      }
      let data={
        id:id,
        planContent:row.planContent,
        projectId:row.projectId,
        completionTime:new Date(completionTime).getTime(),
        beginDate:new Date(beginDate).getTime(),
        priority:row.priority
      }
      updateWorkPlan(data).then(res=>{
        this.$message.success("操作成功!")
      })
    },
    deleteWorkPlanByIds(row){
      let id=row.id
      let userId=row.userId
      let weeks=row.weeks
      deleteWorkPlanById(id).then(res=>{
        this.$message.success("操作成功!")
        getWorkPlanByWeeks(weeks,userId,this.meetingId).then(res=>{
          let datas=[]
          let data=res.data
          if(data.length>0){
            for(let i=0;i<data.length;i++){
              if(data[i].taskId!==undefined && data[i].taskId!==null){
                continue
              }
              datas.push(data[i])
            }
          }
          this.workPlanDatas=datas
        })
      })
    },
    closeWorkPlanWin(){
      this.getData()
    },
    endMeetingClick(row) {
      let id = row.id;
      let remark=row.remark
      meetingAuthById(id).then(res => {
        if (res.success === false) {
          this.$message.error(res.data)
        } else {
          if(remark===undefined || remark===null || remark==='' || remark.replace(/\s+/g, "")===''){
            this.$message.error("请将参会情况填写完整!")
          }else{
            endMeeting(id).then(res => {
              this.$message({
                message: '操作成功!',
                type: 'success'
              });
              this.m.status=2
              this.setPermissions()
              this.getData();
              this.workRemarkReadOnly=false
            })
          }
        }
      })
    },
    jumpPage(){
      this.$router.go(-1);
    }
  }
}
</script>
<style scoped lang="scss">
.underline-on-hover {
  cursor: pointer;
  text-decoration: none; /* 默认情况下不显示下划线 */
}

.underline-on-hover:hover {
  text-decoration: underline; /* 鼠标移入时显示下划线 */
}
</style>


