<template>
  <div class="container">
    <div class="gantt_head">
      <div class="head_RorX">
        <div class="filter-lefts">
          <el-radio-group v-model="radio1" @change="selChange()" size="small">
            <el-radio-button :label="$t('an-ren-yuan-cha-kan')" value="renyuan"></el-radio-button>
            <el-radio-button :label="$t('an-xiang-mu-cha-kan')" value="xiangmu"></el-radio-button>
            <el-radio-button :label="$t('zi-yuan-xu-qiu')" value="demand"></el-radio-button>
          </el-radio-group>
          <!-- <el-checkbox v-if="radio1 != $t('zi-yuan-xu-qiu') && user.companyId == 876" v-model="justWaitForMe" style="margin-left: 14px;" @change="selChange()">待我审核</el-checkbox> -->
        </div>
      </div>
      <!-- 时间段筛选  -->
      <div class="head_date" v-if="isDataLoaded">
      <span>{{ $t('message.period') }}</span>
      <el-date-picker
        style="margin-left:9px;width:15vw"
        size="small"
        v-model="valueDate"
        type="daterange"
        :range-separator="$t('other.to')"
        :start-placeholder="$t('time.startDate')"
        :end-placeholder="$t('time.endDate')"
        value-format="yyyy-MM-dd"
        @change="dateupdata()">
      </el-date-picker>
      </div>
      <!-- 任务类型筛选 -->
      <div v-if="radio1 == $t('an-xiang-mu-cha-kan')" class="head_taskType">
        <span>{{ $t('ren-wu-lei-xing') }}</span>
        <el-select clearable filterable v-model="taskType" :placeholder="$t('defaultText.pleaseChoose')" size="small" style="margin-left:9px;width:10vw" @change="taskTypeSel()">
        <el-option :label="$t('other.task')" :value="0"></el-option>
        <el-option :label="$t('other.milestone')" :value="1"></el-option>
      </el-select>
      </div>
      <!-- 任务分组筛选 -->
      <div v-if="reqpar1" class="head_taskgroup">
        <span>{{ $t('other.taskGroup') }}</span>
        <el-select clearable filterable v-model="valuex2" :placeholder="$t('defaultText.pleaseChoose')" size="small" style="margin-left:9px;width:10vw" @change="taskgroupSel()">
        <el-option
          v-for="item in taskgroupList"
          :key="item.name"
          :label="item.name"
          :value="item.name"
          >
        </el-option>
      </el-select>
      </div>
      <!-- 人员/项目筛选 -->
      <div class="head_select">
        <span>{{(this.radio1 == $t('an-ren-yuan-cha-kan') ? $t('ren-yuan') : $t('other.project'))}}</span>
          <el-select v-if="reqpar1" clearable filterable v-model="valuex" :placeholder="$t('defaultText.pleaseChoose')" size="small" style="margin-left:9px;width:10vw" @change="optupdata()">
            <el-option v-for="item in screenList" :key="item.id" :label="item.projectName" :value="item.id">
              <span v-if="reqpar1" style="float: left;color: #8492a6;">{{ item.projectCode }}</span>
              <span v-if="reqpar1" style="float: right;font-size: 13px;margin-left: 20px">{{ item.projectName }}</span>
            </el-option>
          </el-select>
          <el-select v-if="!reqpar1 && user.userNameNeedTranslate != '1'" clearable filterable v-model="valuex" :placeholder="$t('defaultText.pleaseChoose')" size="small" style="margin-left:9px;width:10vw" @change="optupdata()">
            <el-option v-for="item in screenList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <selectCat v-if="!reqpar1 && user.userNameNeedTranslate == '1'" style="margin-left:9px;" :size="'small'" :widthStr="'153'" :subject="screenList" :subjectId="valuex" :distinction="'1'" @selectCal="selectCal"></selectCat>
      </div>
      <!-- 资源需求导入/导出 -->
      <div class="head_files" v-if="!isDataLoaded">
        <div style="margin-left:10px;float:left;">
          <el-link type="primary" :underline="false" :href="'./upload/'+$t('zi-yuan-xu-qiu-dao-ru-mo-ban')+'.xlsx'" download="资源需求导入模板.xlsx">{{ $t('Downloadthetemplate') }}</el-link>
        </div>
        <el-upload ref="upload" style="margin-left:10px;float:left;" action="#" :limit="1" :http-request="importProject" :show-file-list="false">
          <el-link type="primary" :underline="false" >{{ $t('dao-ru-xu-qiu') }}</el-link>
        </el-upload>
        <div style="margin-left:10px;float:left;">
        <el-link type="primary" :underline="false" @click="exportProjectData" download="资源需求导出.xlsx">{{ $t('dao-chu-xu-qiu') }}</el-link>
        </div>
      </div>
    </div>

    <gantt v-if="isDataLoaded && user.userNameNeedTranslate != 1" ref="ganttTable1" class="left-container" :tasks="tasks" 
    :stafforpro="radio1"
    :valueDate="valueDate"
    :key="updatakey1" @closeBounced="closeBounced"></gantt>
    <vueGantt v-if="isDataLoaded && user.userNameNeedTranslate == 1" ref="ganttTable1" :stafforpro="radio1"
    :valueDate="valueDate"
    :key="updatakey1" :tasks="tasks"></vueGantt>

  <div class="demand-container" v-if="!isDataLoaded">
    <el-table height="75vh" :loading="demandListLoading" :data="demandList">
      <el-table-column :label="user.companyId == '7030' ? '项目令号' : $t('Itemno')" prop="projectCode" width="160"></el-table-column>
      <el-table-column :label="$t('headerTop.projectName')" prop="projectName" min-width="240"></el-table-column>
      <el-table-column :label="$t('jin-qi-ri-huo-yue-ren-yuan')" prop="activeUsers" min-width="240">
        <template slot-scope="scope">
          <div>
            <span v-if="user.userNameNeedTranslate == 1">
              <span v-for="(item, index) in scope.row.activeUsers" :key="index">
                <TranslationOpenDataText type='userName' :openid='item'></TranslationOpenDataText>
                <span v-if="index < scope.row.activeUsers.length - 1">,</span>
              </span>
            </span>
            <span v-if="user.userNameNeedTranslate != 1">
              {{scope.row.activeUsers}}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('starttimes')  +' - '+ $t('time.endTime')" min-width="240">
        <template slot-scope="scope">
          <span>{{scope.row.startDate ? scope.row.startDate + ' ~ ' + scope.row.endDate : ''}}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('he-tong-yao-qiu')" prop="contractReq" min-width="240" show-overflow-tooltip></el-table-column>
      <el-table-column :label="$t('li-cheng-bei-jin-du')" prop="milepost" min-width="280">
        <template slot-scope="scope">
           <span>{{scope.row.milepost ? scope.row.milepost.name + '\u3000'+$t('wan-cheng-shi-jian')+':' + scope.row.milepost.finishDate : ''}}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('ren-yuan-xu-qiu')" prop="membReq" min-width="280"></el-table-column>
      <el-table-column :label="$t('ren-wu-xu-qiu')" prop="taskReq" min-width="280"></el-table-column>
      <el-table-column :label="$t('can-yu-bu-men-jin-du')" prop="departmentSpeed" min-width="280"></el-table-column>
      <el-table-column :label="$t('operation')" width="120" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button @click="demandEdit(scope.row)" size="small">{{ $t('xiu-gai') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="poss">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageIndex"
        :page-sizes="[20, 50, 100, 200]"
        :page-size="20"
        layout="total, sizes, prev, pager, next"
        :total="total">
      </el-pagination>
    </div>

    <!-- 资源需求修改 -->
  <el-dialog v-if="demandEditDialog" width="500px" append-to-body :visible.sync="demandEditDialog" :title="$t('xiu-gai') +' - ' + editParameter.projectName">
    <el-form label-width="150">
      <el-form-item :label="$t('starttimes')">
        <el-date-picker
        style="width:350px"
        v-model="editDate1"
        type="date"
        :placeholder="$t('defaultText.pleaseChoose')"
        value-format="yyyy-MM-dd"></el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('time.endTime')">
        <el-date-picker
        style="width:350px"
        v-model="editDate2"
        type="date"
        :placeholder="$t('defaultText.pleaseChoose')"
        value-format="yyyy-MM-dd"></el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('ren-yuan-xu-qiu')">
        <el-input style="width:350px" v-model="editParameter.membReq" clearable></el-input>
      </el-form-item>
      <el-form-item :label="$t('ren-wu-xu-qiu')">
        <el-input style="width:350px" v-model="editParameter.taskReq" clearable></el-input>
      </el-form-item>
      <el-form-item :label="$t('he-tong-yao-qiu')">
        <el-input style="width:350px" v-model="editParameter.contractReq" clearable></el-input>
      </el-form-item>
      <el-form-item :label="$t('bu-men-jin-du')">
        <el-input style="width:350px" v-model="editParameter.departmentSpeed" clearable></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
              <el-button type="default" @click="demandEditDialog = false">{{ $t('btn.cancel') }}</el-button>
              <el-button type="primary" @click="demandEditSure" >{{ $t('btn.determine') }}</el-button>
            </div>
  </el-dialog>
  </div>
  
  </div>
</template>

<script>
import { error } from 'dingtalk-jsapi';
import Gantt from './gantt.vue';
import vueGantt from './vueGantt.vue'
// 自定义select组件
import SelectCat from "@/components/select.vue"

export default {
  name: 'project_gantt',
  props: {},
  components: {Gantt, vueGantt, SelectCat},
  data() {
    return {
      taskType: '',
      isDataLoaded:false,
      tasks: {
        data : [],
        links: []
      },
      tasks1: {links:[]},
      updatakey1: 1,
      updatakey2: -1,
      radio1:this.$t('an-ren-yuan-cha-kan'),
      valueDate:[],
      options:[{value:this.$t('xuan-xiang-1'),label:this.$t('all')},{value:this.$t('xuan-xiang-2'),label:this.$t('ren-yuan')+"1"}],
      valuex:'',
      screenList:[],

      // 请求参数
      reqpar1:0,
      reqpar2:[],
      demandListLoading: false,
      demandList: [],
      pageIndex: 1,
      pageSize: 20,

      demandEditDialog: false,
      editParameter: {},
      editDate1: '',
      editDate2: '',
      taskgroupList: [],
      valuex2: '',

      user: JSON.parse(sessionStorage.getItem("user")),
      justWaitForMe: false
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    let nowdate = new Date()
    let nowmonth = nowdate.getMonth() + 1
    let startdate = nowdate.getFullYear() + "-" + (nowmonth < 10 ? "0" + nowmonth : nowmonth) + "-" + (nowdate.getDate() < 10 ? "0" + nowdate.getDate() : nowdate.getDate())
    let udate = new Date(nowdate.getFullYear(),nowdate.getMonth(),nowdate.getDate() + 31)
    let endmonth = udate.getMonth() + 1
    let enddate = udate.getFullYear() + "-" + (endmonth < 10 ? "0" + endmonth : endmonth) + "-" + (udate.getDate() < 10 ? "0" + udate.getDate() : udate.getDate())
    this.valueDate = [startdate,enddate]
    this.valueDate2 = this.valueDate
    this.reqpar2 = this.valueDate
    // console.log("date",this.valueDate);
    this.getList();
    this.getScreen()
    // this.tasks1 = this.tasks
    this.isDataLoaded = true
  },
  methods: {
    parentLevelOpensPopUpWindowGantt(row) {
      setTimeout(() => {
        this.$refs.ganttTable1.detaliTaskExposure(row);
      }, 1000)
    },
    closeBounced(obj) {
      if(obj.submitInsert) {
        this.dateupdata()
      }
    },
    selectCal(obj) {
      if(obj.distinction == '1') {
          this.valuex = obj.id
          this.optupdata()
      }
    },
    setGroup() {
          this.$refs.ganttTable1.setGroup();
          // this.$refs.ganttTable2.setGroup();
      },
      taskTypeSel(){
        console.log(this.taskType);
        
        this.getList()
      },
      // 资源需求导出
      exportProjectData() {
        let parameter = {}
        if(this.valuex){
          parameter.projectId = this.valuex
        }
        if(this.valuex2){
          parameter.groupName = this.valuex2
        }
                this.http.post('/project-requirement/exportData',parameter,
                res => {
                    if (res.code == "ok") {
                        let filePath = res.data;
                        const a = document.createElement('a'); // 创建a标签
                        a.setAttribute('download', this.$t('zi-yuan-xu-qiu-dao-chu')+'.xlsx');// download属性
                        a.setAttribute('href', filePath);// href链接
                        a.click(); //自执行点击事件
                        a.remove();
                    } 
                },
                error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                    }
                );
            },
      // 资源需求导入
      importProject(item) {
                //首先判断文件类型
                let str = item.file.name.split(".");
                let format = str[str.length - 1];
                if (format != "xls" && format != "xlsx") {
                    this.$message({
                        message: this.$t('other.PleaseselecttheXLSorXLSXfile'),
                        type: "error"
                    });
                } else {
                    let formData = new FormData();
                    formData.append("multipartFile", item.file);
                    this.http.uploadFile('/project-requirement/importData', formData,
                    res => {
                        this.$refs.upload.clearFiles();
                        if (res.code == "ok") {
                            this.$message({
                                message: this.$t('other.importSuccess'),
                                type: "success"
                            });
                            this.getDemandList();
                        } else {
                            this.$message({
                                message: res.msg,
                                type: "error"
                            });
                        }
                    },
                    error => {
                        this.$refs.upload.clearFiles();
                        this.$message({
                            message: error,
                            type: "error"
                        });
                    });
                }
            },
      // 人员/项目切换
      selChange(){
        this.valuex = null
        // console.log("切换按钮",this.radio1);
        if (this.radio1 == this.$t('an-ren-yuan-cha-kan')) {
          this.isDataLoaded = true
          this.reqpar1 = 0
          this.getList()
          this.getScreen()
        }else if(this.radio1 == this.$t('an-xiang-mu-cha-kan')){
          this.isDataLoaded = true
          this.reqpar1 = 1
          this.getList()
          this.getXmScreen()
          this.getTaskgroupList()
        }else {
          this.reqpar1 = 1
          this.isDataLoaded = false
          this.pageIndex = 1
          this.pageSize = 20
          this.valuex = ''
          this.valuex2 = ''
          this.getDemandList()
          this.getXmScreen()
          this.getTaskgroupList()
          
        }
      },
      // 时间段改变
      dateupdata(){
        this.reqpar2 = this.valueDate
        if(this.isDataLoaded){
          this.getList()
        }else {
          this.getDemandList()
        }
      },
      // 人员/项目筛选改变
      optupdata(){
        // console.log(this.valuex);
        if(this.isDataLoaded){
          this.getList()
        }else{
          this.getDemandList()
        }
      },
      // 任务分组筛选改变
      taskgroupSel(){
        // console.log(this.valuex2);
        if(this.isDataLoaded){
          this.getList()
        }else{
          this.getDemandList()
        }
        
      },

      handleSizeChange(val){
        this.pageSize = val
        this.pageIndex = 1
        this.getDemandList()
      },
      handleCurrentChange(val){
        this.pageIndex = val
        this.getDemandList()
      },
      // 资源需求修改
      demandEdit(row){
        console.log(row);
        this.demandEditDialog = true
        this.editParameter = JSON.parse(JSON.stringify(row))
        this.editDate1 = this.editParameter.startDate
        this.editDate2 = this.editParameter.endDate
        // console.log('edit',this.demandEditDialog);
      },
      demandEditSure(){
        this.editParameter.startDate = this.editDate1
        this.editParameter.endDate = this.editDate2
        delete this.editParameter.reStartDate
        delete this.editParameter.reEndDate
        delete this.editParameter.milepost
        this.http.post('/project-requirement/addOrMod',this.editParameter,
        res => {
          if(res.code == 'ok'){
            this.$message({
              message: this.$t('message.modifyTheSuccess'),
              type: 'success'
            })
            this.demandEditDialog = false
            this.getDemandList()
          }else {
            this.$message({
              message: res.msg,
              type: 'error'
            })
          }
        },err => {
          this.$message({
            message: err,
            type: 'error'
          })
        })
      },

      // 获取人员项目筛选列表
      getScreen(){
        this.http.get('/project/getMyUsers',
            res => {
              if (res.code == "ok") {
                this.screenList = res.data
              }else{
                this.$message({
                  message: res.msg,
                  type: "error"
                });
              }
            },
            error => {
              this.$message({
                message : error,
                type : "error"
              })
            }
        )
      },
      getXmScreen(){
        this.http.get('/project/getProjectList',
            res => {
              if (res.code == "ok") {
                this.screenList = res.data
                // console.log("screen",this.screenList);
              }else{
                this.$message({
                  message: res.msg,
                  type: "error"
                });
              }
            },
            error => {
              this.$message({
                message : error,
                type : "error"
              })
            }
        )
      },
      // 获取任务分组筛选列表
      getTaskgroupList(){
        this.http.post('/task-group/getGroupNames',{},
        res => {
          if(res.code == 'ok'){
            this.taskgroupList = res.data
          }else {
            this.$message({
              message: res.msg,
              type: 'error'
            })
          }
        },err => {
          this.$message({
            message: err,
            type: 'error'
          })
        })
      },
      // 获取甘特图数据
      getList() {
        let getlistcs = {type : this.reqpar1 , startDate : this.reqpar2[0] , endDate : this.reqpar2[1]}
        if(this.reqpar1) {
          if(this.valuex != ''){
            getlistcs.projectId = this.valuex
          }
          if(this.valuex2 != ''){
            getlistcs.groupName = this.valuex2
          }
          getlistcs.taskType = this.taskType
          
        }else {
          if(this.valuex != ''){
            getlistcs.userId = this.valuex
          }
        }
        if(this.justWaitForMe) {
          getlistcs.justWaitForMe = 1
        }
        var urls = ''
        if(this.user.userNameNeedTranslate == '1') {
          urls = '/project/getGanttDataNew'
        } else {
          urls = '/project/getGanttData'
        }
        this.http.post(urls, getlistcs,
        // this.http.post('/project/getGanttDataNew', getlistcs,
                        res => {
                            if (res.code == "ok") {
                                for(var i in res.data) {
                                  if(res.data[i].id.indexOf(this.$t('chu-cha')) != '-1') {
                                    res.data[i].color = '#E6A23C'
                                  }
                                  if(res.data[i].id.indexOf(this.$t('other.AskForLeave')) != '-1') {
                                    res.data[i].color = '#F56C6C'
                                  }
                                }
                                this.tasks = {data:res.data};
                                if(this.user.userNameNeedTranslate != '1') {
                                  let taskson = []
                                  for(let m in this.tasks.data){
                                    this.tasks.data[m].render = null
                                    if(this.tasks.data[m].time != 0){
                                      
                                      if(this.tasks.data[m].id != this.tasks.data[m].userId){
                                        this.tasks.data[m].render = 'split'
                                        let item = JSON.parse(JSON.stringify(this.tasks.data[m]))
                                        item.parent = this.tasks.data[m].id
                                        item.id = this.tasks.data[m].id + 'son'
                                        taskson.push(item)
                                        this.tasks.data[m].time = 0
                                      }
                                      
                                    }
                                  }
                                  this.tasks.data.push.apply(this.tasks.data,taskson) 
                                  for(let i in this.tasks.data){
                                    if(this.tasks.data[i].time == 0){
                                      delete this.tasks.data[i].start_date
                                      delete this.tasks.data[i].end_date
                                      this.tasks.data[i].type = 'milestone'
                                    }
                                    if(this.tasks.data[i].end_date){
                                      let date = new Date(this.tasks.data[i].end_date)
                                      let date2 = new Date(date.getFullYear(),date.getMonth(),date.getDate() + 1)
                                      let dmonth = date2.getMonth() + 1
                                      let dday = date2.getDate()
                                      this.tasks.data[i].end_date = date2.getFullYear() + '-' + (dmonth < 10 ? '0' + dmonth : dmonth) + '-' + (dday < 10 ? '0' + dday : dday)
                                    }
                                  }
                                }
                                console.log('ganttData',this.tasks.data);
                                this.$nextTick(()=>{
                                  this.updatakey1 += 1
                                })
                        
                            } else {
                                this.$message({
                                    message: res.msg,
                                    type: "error"
                                });
                            }
                        },
                        error => {
                            this.$message({
                                message: error,
                                type: "error"
                            });
                            }
                        );
          
      },
      // 获取资源需求列表
      getDemandList(){
        let parameter = {
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
        }
        if(this.valuex != ''){
          parameter.projectId = this.valuex
        }
        if(this.valuex2 != ''){
          parameter.groupName = this.valuex2
        }
        this.demandListLoading = true
        this.http.post('/project-requirement/listByPage',parameter,
        res => {
          if(res.code == 'ok'){
            this.demandListLoading = false
            this.total = res.data.total
            if(this.user.userNameNeedTranslate == 1) {
              for(let i in res.data.records) {
                if(res.data.records[i].activeUsers){
                  res.data.records[i].activeUsers = res.data.records[i].activeUsers.split(',')
                }
              }
            }
            this.demandList = res.data.records
          }else {
            this.demandListLoading = false
            this.$message({
              message: res.msg,
              type: 'error'
            })
          }
        },err => {
          this.demandListLoading = false
          this.$message({
              message: err,
              type: 'error'
            })
        })
      },
  },
};
</script>

<style scoped lang="scss">
.container {
    height: 100%;
    width: 100%;
  }
  .filter-lefts {
    display: flex;
    align-items: center;
  }
  .left-container {
    overflow: hidden;
    position: relative;
    height: 80vh;
  }
  .demand-container{
    overflow: hidden;
    position: relative;
    height: 92%;
  }
  .gantt_head{
    width: 100%;
    height: 80px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .gantt_head .head_RorX{
    width: 380px;
  }
  .gantt_head .head_date{
    width: 22vw;
  }
  .gantt_head .head_taskgroup{
    width: 15vw;
  }
  .gantt_head .head_taskType{
    width: 15vw;
  }
  
  .gantt_head .head_select{
    width: 15vw;
  }
  .gantt_head .head_files{
    width: 17vw;
  }
  .poss {
    height: 8%;
    float: right;
    padding-top: 5px;
}
</style>
