<!-- 事项甘特图 -->
<template>
  <div class="gantt-chart">
    <div class="condition-legend-bar">
      <Select
        class="system-select"
        width="217"
        :isReadOnly="true"
        tipPlace="top"
        caption="系统名称："
        v-model="systemId"
        :selectdata="systemList"
        :placeholder="'请选择'"
        @change="changeSystem"
        hideClear
      />
      <div class="legend-container">
        <div v-for="(item) in legends" :key="'key_' + item.id" class="item-legend">
          <div :style="{'background': item.backgroundColor, 'border-color': item.borderColor}"></div>
          <div>{{item.text}}</div>
        </div>
        <div>
          <el-radio-group v-model="timeType" @change="changeView">
            <el-radio style="line-height: 32px;margin-right: 16px;" label="month">月视图</el-radio>
            <el-radio style="line-height: 32px;" label="day">日视图</el-radio>
          </el-radio-group>
        </div>
      </div>
    </div>
    <div class="main-gantt-container">
      <div class="task-title">
        <div class="title">任务标题</div>
        <div>
          <Tree :data="treeData" @openNode="toggleNode" />
        </div>
      </div>
      <div class="chart-container" id="chartContainer" ref="chartContainer">
        <div id="ganttContainer"></div>
      </div>
      <el-dialog :title="ganttDetail.name" :visible.sync="showDetail" width="840px">
        <div class="dialog-container">
          <div class="row task-status">
            <div>
              <Task class="icon" />
              <div class="title">任务状态</div>
            </div>
            <div v-show="ganttDetail.status" :style="{'background': ganttDetail.color && ganttDetail.color[1]?ganttDetail.color[1] : '', 'color': ganttDetail.color && ganttDetail.color[0]?ganttDetail.color[0] : ''}">{{ganttDetail.status}}</div>
          </div>
          <div class="row">
            <div>
              <PlanTime class="icon" />
              <div class="title">计划时间</div>
            </div>
            <div class="info">{{ganttDetail.planTime}}</div>
          </div>
          <div class="row">
            <div>
              <RealTime class="icon" />
              <div class="title">实际执行时间</div>
            </div>
            <div class="info">{{ganttDetail.realTime}}</div>
          </div>
          <div class="row picture">
            <div>
              <Picture class="icon" />
              <div class="title">照片</div>
            </div>
            <div>
              <div>
                <div class="num">{{pictureList.length}}张</div>
                <div v-if="pictureList.length > 0" class="more" @click="() => showImgDetail = true">查看更多</div>
              </div>
              <div class="pictrue-container">
                <div v-for="(item) in pictures" :key="'id_' + item.id" @click="showImgContainer(item.id)" class="item">
                  <img src="../../assets/imgs/analysis/picture.png" alt />
                  <div class="info" :title="item.name">{{item.name}}</div>
                </div>
              </div>
            </div>
          </div>
          <div class="row picture">
            <div>
              <Report class="icon" />
              <div class="title">报告</div>
            </div>
            <div>
              <div>
                <div class="num">{{accessoryList.length}}张</div>
              </div>
              <div class="accessory-container" :style="{'max-height': accessoryIsExpand?'' : '115px'}">
                <a :href="item.url?item.url : 'javascript:void(0)'" target="_blank" v-for="(item) in accessoryList" :key="'id_' + item.id" class="item">
                  <img src="../../assets/imgs/analysis/report_pdf.png" alt />
                  <div class="info" :title="item.name">{{item.name}}</div>
                </a>
                <div v-if="accessoryList.length > 0" class="expand-more" @click="() => accessoryIsExpand = !accessoryIsExpand">
                  <ExpandArrow :class="{'expand': accessoryIsExpand}"/>
                  展开更多
                </div>
              </div>
            </div>
          </div>
          <div class="row test-content">
            <div>
              <Menu class="icon" />
              <div class="title">检测内容</div>
            </div>
            <el-table :data="tableData" max-height="300">
              <el-table-column property="sbjc" label="设备简称"></el-table-column>
              <el-table-column property="sbjbm" label="设备编号"></el-table-column>
              <el-table-column property="cnt" label="设备数"></el-table-column>
              <el-table-column property="wzjc" width="300" label="空间位置"></el-table-column>
            </el-table>
          </div>
        </div>
      </el-dialog>
      <div class="img-detail-container">
        <el-dialog :title="'图片预览'" :visible.sync="showImgDetail" width="1260px">
          <div class="detail-container">
            <div class="pictures-menu">
              <div v-for="(item) in pictureList" :key="'id_' + item.id" class="item" @click="changeCurImg(item.id)" :class="{'active': item.isActive}">
                <img :src="item.url?item.url : ''" alt="">
                <div class="name" :title="item.name">{{item.name}}</div>
              </div>
            </div>
            <div class="cur-img-container">
              <img v-if="curImg && curImg.url" :src="curImg.url" alt="">
            </div>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { queryGanttChart, queryGanttDetail } from "../../api/ganttChart";
import { querySystemList, queryDetailData } from "../../api/coreDeviceReport";
import { Tree } from "meri-design";
import _ from "lodash";
import moment from "moment";
// import '../../utils/ganttChart/g.js';
import { GanttChartDay } from "../../utils/ganttChart/GanttChart_day.js";
import { GanttChartMonth } from "../../utils/ganttChart/GanttChart_month.js";
import { parse } from "path";
import Task from "../../assets/svg/task.svg";
import PlanTime from "../../assets/svg/plan_time.svg";
import RealTime from "../../assets/svg/real_time.svg";
import Picture from "../../assets/svg/picture.svg";
import Report from "../../assets/svg/report.svg";
import Menu from "../../assets/svg/menu.svg";
import ExpandArrow from "../../assets/svg/expand_arrow.svg";
export default {
  data() {
    return {
      plazaId: 1000423, // 广场id
      systemList: [], // 系统列表
      systemId: "", // 系统名称
      legends: [
        {
          id: 1,
          text: "按时完成",
          backgroundColor: "#E7E9EA",
          borderColor: "#C3C7CB"
        },
        {
          id: 2,
          text: "未开始/进行中",
          backgroundColor: "rgba(91, 143, 249, 0.2)",
          borderColor: "#5B8FF9"
        },
        {
          id: 3,
          text: "逾期完成",
          backgroundColor: "#FBCE99",
          borderColor: "#F58300"
        },
        {
          id: 4,
          text: "逾期未完成",
          backgroundColor: "#FBB8B5",
          borderColor: "#F54E45"
        }
      ], // 图例
      timeType: "month", // 甘特图时间类型
      treeData: [], // 树结构数据
      startTime: null, // 甘特图开始时间
      endTime: null, // 甘特图结束时间

      // 弹窗相关
      showDetail: false, // 弹框显示状态
      // detailTitle: "", // 弹窗标题
      pictures: [
        // {
        //   id: 1,
        //   imgSrc: require("../../assets/imgs/analysis/picture.png"),
        //   title: "2019年5月高压用具检测报告.jpg"
        // },
        // {
        //   id: 2,
        //   imgSrc: require("../../assets/imgs/analysis/picture.png"),
        //   title: "2019年5月高压用具检测报告.jpg"
        // }
      ], // 照片
      ganttDetail: {}, // 甘特图明细
      tableData: [], // 表数据
      curTask: {}, // 当前查看的任务
      pictureList: [
        // {id: 1, url: require('../../assets/images/login_back.png'), name: '图层名称1.jpg', isActive: true},
        // {id: 2, url: require('../../assets/images/matter_pop3.png'), name: '图层名称2.jpg', isActive: false},
        // {id: 3, url: require('../../assets/images/login_back.png'), name: '图层名称3.jpg', isActive: false},
      ], // 图片
      curImg: {}, // 当前查看的图片
      accessoryList: [], // 附件
      accessoryIsExpand: false, // 附件是否展开

      showImgDetail: false, // 查看更多图片弹框显示状态

    };
  },

  components: {
    Task,
    PlanTime,
    RealTime,
    Picture,
    Report,
    Menu,
    ExpandArrow
  },

  computed: {},

  beforeMount() {
    let PLAZAID = localStorage.getItem('PLAZAID');
    this.plazaId = Number(PLAZAID) || 1000423;
  },
  mounted() {
    document.addEventListener('click', () => {
      setTimeout(() => {
        if (this.isClickAccessory) {
          this.isClickAccessory = false;
          return
        }
        this.showAccessory = false;
      }, 20)
    })
    this.initChartTime();
    this.getSystemList();
  },

  methods: {
    /**
     * 初始化甘特图请求时间
     */
    initChartTime() {
      let endTime = new Date().getTime(),
          startTime = endTime - 1000*60*60*24*365;
      this.startTime = moment.unix(startTime / 1000).format('YYYYMMDDHHmmss');
      this.endTime = moment.unix(endTime / 1000).format('YYYYMMDDHHmmss');
    },
    /**
     * 获取系统列表数据
     */
    getSystemList() {
      querySystemList().then(res => {
        if (res.result === "success") {
          let data = res.data;
          let newData = [];
          _.forEach(data, item => {
            newData.push({
              id: item.code,
              name: item.name
            });
          });
          this.systemList = newData;
          const { query } = this.$route;
          if (!_.isEmpty(query) && query.smsxt) {
            this.systemId = query.smsxt;
          } else {
            this.systemId = newData[0].id;
          }
          this.getGanttChartData();
        }
      });
    },
    /**
     * 处理请求数据的时间
     */
    disQueryTime() {
      let startTime, endTime;
      let curTime = new Date(),
        curYear = curTime.getFullYear(),
        curMonth = curTime.getMonth() + 1;
      if (this.timeType === "month") {
        startTime = `${curYear}0101000000`;
        endTime = `${curYear + 1}0101000000`;
      } else {
        startTime = `${curYear}${curMonth}01000000`;
        if (curMonth + 1 > 12) {
          endTime = `${curYear + 1}0101000000`;
        } else {
          endTime = `${curYear}${curMonth + 1}01000000`;
        }
      }
      return [startTime, endTime];
    },
    /**
     * 切换系统
     */
    changeSystem() {
      if (window.gc) {
        gc.gCanvas.destroy();
        window.gc = null;
      }
      this.getGanttChartData();
    },
    /**
     * 切换视图
     */
    changeView() {
      console.log('timeType', this.timeType)
      if (window.gc) {
        gc.gCanvas.destroy();
        window.gc = null;
      }
      this.getGanttChartData();
    },
    /**
     * 获取甘特图数据
     */
    getGanttChartData() {
      let time = this.disQueryTime();
      let param = {
        smsxt: this.systemId,
        plazaId: this.plazaId,
        startDate: this.startTime, // time[0]
        endDate: this.endTime // time[1]
      };
      queryGanttChart("/data/base/queryGanttChart", param).then(res => {
        const { dsfList, wbList, zwList, result } = res;
        console.log("res", res);
        if (result === "success") {
          let newData = [],
            data = [wbList, zwList, dsfList],
            name = ["维保", "专维", "第三方检测"];
          _.forEach(data, (item, index) => {
            newData.push({
              index: index,
              id: index + 1,
              name: name[index],
              open: true,
              // children: name[index] === '专维'?[] : this.disGanttData(dsfList)
              children: this.disGanttData(data[index])
            });
          });
          this.treeData = newData;

          let taskData = _.map(_.cloneDeep(newData), item => {
            return {
              id: item.id,
              type: item.name,
              open: item.open,
              dataList: _.map(item.children, _item => {
                return {
                  id: _item.id,
                  title: _item.name,
                  tasks: _item.originData
                };
              })
            };
          });
          console.log("taskData", taskData);
          if (!window.gc) {
            let width = this.$refs.chartContainer.offsetWidth;
            let handleFn = null;
            if (this.timeType === 'month') {
              handleFn = GanttChartMonth
            } else {
              handleFn = GanttChartDay
            }
            window.gc = new handleFn({
              chartParentContainer: "chartContainer",
              chartContainer: "ganttContainer",
              viewWidth: width,
              cWidth: 3 * width,
              tasks: taskData,
              daysCount: this.timeType === 'month'? (365*1.5) : parseInt((3 * width) / 40),
              callback: this.showDialog,
              pageToCallback: (data)=>{
                const { startAt, endAt } = data;
                this.startTime = moment.unix(new Date(startAt).getTime() / 1000).format('YYYYMMDDHHmmss');
                this.endTime = moment.unix(new Date(endAt).getTime() / 1000).format('YYYYMMDDHHmmss');
                this.getGanttChartData();
              }
            });
            gc.main();
          } else {
            gc.changeTasks(taskData)
          }
        }
      });
    },
    /**
     * 处理甘特图数据
     */
    disGanttData(arr) {
      let data = [];
      _.forEach(arr, item => {
        data.push({
          id: item.id,
          name: item.name,
          checked: "uncheck",
          originData: _.map(item.data, _item => {
            // _item.startDate = moment.unix((new Date().getTime() - 1000*60*60*24*7)/1000).format('YYYY-MM-DD HH:mm:ss');
            _item.startDate = moment.unix(_item.startDate / 1000).format("YYYY-MM-DD HH:mm:ss");
            // _item.endDate = moment.unix(new Date().getTime()/1000).format('YYYY-MM-DD HH:mm:ss');
            _item.endDate = moment.unix(_item.endDate / 1000).format("YYYY-MM-DD HH:mm:ss");
            _item.description = _item.parentname;
            return _item;
          })
        });
      });
      return data;
    },
    /**
     * 展开收起节点
     */
    toggleNode(status, item) {
      console.log("status", status, item);
      window.gc.toggle(item.index);
    },
    /**
     * 显示弹窗
     */
    showDialog(task) {
      this.showDetail = true;
      // this.detailTitle = task._pdata.description;
      this.curTask = task;
      this.getGanttDetailData();
      this.getPictureOrReportData(0);
      this.getPictureOrReportData(1);
    },
    /**
     * 获取甘特图详情
     */
    getGanttDetailData() {
      const { id, statusType } = this.curTask._pdata;
      let param = {
        plazaId: this.plazaId,
        type: statusType,
        id: id
      };
      queryGanttDetail("/data/base/queryGanttChartDetails", param).then(res => {
        const { result, data } = res;
        if (result === "success") {
          if (!data) {
            this.ganttDetail = {}
            return
          }
          const {
            status,
            planStartDate,
            planEndDate,
            realStartDate,
            realEndDate,
            statusType,
            name
          } = data;
          let color;
          switch (statusType) {
            case 1:
              color = ['#c3c7cb', '#e7e9ea'];
              break
            case 2:
              color = ['#5b8ff9', '#5b8ff933'];
              break
            case 3:
              color = ['#f58300', '#fbce99'];
              break
            case 4:
              color = ['#f54e45', '#fbb8b5'];
              break
            default:
              color = ['#f54e45', '#fbb8b5'];
              break
          }
          let newData = {
            status,
            color: color,
            name: name,
            planTime: this.dealDetailTime(planStartDate, planEndDate),
            realTime: this.dealDetailTime(realStartDate, realEndDate)
          };
          this.ganttDetail = newData;
          this.tableData = data.assetList;
        }
      });
    },
    /**
     * 处理时间
     */
    dealDetailTime(startTime, endTime) {
      let start = moment.unix(startTime / 1000).format("YYYY.MM.DD HH:mm:ss"),
        end = moment.unix(endTime / 1000).format("YYYY.MM.DD HH:mm:ss");
      return `${start}-${end}`;
    },
    /**
     * 获取甘特图的图片/报告详情
     */
    getPictureOrReportData(type) {
      const { id, statusType } = this.curTask._pdata;
      let param = {
        plazaId: this.plazaId,
        file_type: statusType,
        // file_type: 0,
        file_type_id: id,
        // file_type_id: 9886,
        type: type,
      };
      queryDetailData("/data/base/queryFileDetails", param).then(res => {
        console.log("photo", res);
        const { result, data } = res;
        if (result === 'success') {
          let newData = [];
          _.forEach(data, (item, index) => {
            newData.push({
              id: item.id,
              url: item.urlname,
              isActive: index === 0,
              name: item.description
            });
          });
          if (type === 0) {
            this.pictureList = newData;
            this.curImg = newData[0];
            this.pictures = this.pictureList.slice(0, 2);
          } else {
            this.accessoryList = newData;
          }
        }
      });
    },
    /**
     * 切换当前预览大图
     */
    changeCurImg(id) {
      _.map(this.pictureList, (o) => {return o.isActive = o.id === id});
      this.curImg = _.find(this.pictureList, (o) => {return o.isActive});
    },
    /**
     * 展示图片
     */
    showImgContainer(id) {
      console.log('id', id)
      _.map(this.pictures, (o) => {return o.isActive = o.id === id});
      this.curImg = _.find(this.pictures, (o) => {return o.isActive});
      this.showImgDetail = true;
    }
  },
  beforeDestroy() {
    window.gc = null;
  }
};
</script>

<style lang='less' scoped>
.gantt-chart {
  padding-left: 16px;
  padding-right: 16px;
  padding-top: 12px;
  padding-bottom: 16px;
  width: 100%;
  height: 100%;
  background: #fff;
  .condition-legend-bar {
    margin-bottom: 12px;
    display: flex;
    justify-content: space-between;
  }
  .legend-container {
    display: flex;
    .item-legend {
      padding-left: 18px;
      position: relative;
      font-size: 14px;
      color: #646c73;
      line-height: 32px;
      &:not(:nth-of-type(4)) {
        margin-right: 20px;
      }
      > div:first-child {
        position: absolute;
        left: 0;
        top: calc(50% - 6px);
        width: 12px;
        height: 12px;
        border: 1px solid;
      }
      &:nth-of-type(4) {
        margin-right: 32px;
      }
    }
  }
  .main-gantt-container {
    width: 100%;
    height: calc(100% - 44px);
    background: #f2f5f7;
    border: 1px solid rgba(239, 240, 241, 1);
    border-radius: 4px;
    display: flex;
    .task-title {
      width: 404px;
      height: 100%;
      border-right: 1px solid #eff0f1;
      .title {
        padding-left: 32px;
        padding-top: 15px;
        padding-bottom: 15px;
        font-size: 14px;
        color: #646c73;
        line-height: 19px;
        border-bottom: 1px solid #eff0f1;
      }
      > div:nth-of-type(2) {
        max-height: calc(100% - 50px);
        overflow: auto;
      }
    }
    .chart-container {
      flex: 1;
      overflow: hidden;
      background: #fff;
    }
  }
  .dialog-container {
    max-height: 580px;
    overflow: auto;
    padding-right: 5px;
    .row {
      display: flex;
      > div:first-child {
        margin-right: 24px;
        display: flex;
        align-items: center;
      }
      &:not(:last-of-type) {
        margin-bottom: 14px;
      }
      .info {
        font-size: 14px;
        color: #1f2429;
        line-height: 22px;
      }
    }
    .icon {
      margin-right: 6px;
      width: 16px;
    }
    .title {
      width: 84px;
      font-size: 14px;
      color: #646c73;
      line-height: 22px;
      font-weight: 400;
    }
    .task-status > div:nth-of-type(2) {
      padding-left: 8px;
      padding-right: 8px;
      // width: 58px;
      height: 24px;
      background: rgba(91, 143, 249, 0.2);
      border-radius: 2px;
      color: #5b8ff9;
      line-height: 24px;
      text-align: center;
    }
    .picture {
      margin-bottom: 19px !important;
      > div:first-child {
        align-items: baseline;
      }
      > div:nth-of-type(2) {
        flex: 1;
      }
      > div:nth-of-type(2) > div:first-child {
        margin-bottom: 12px;
        display: flex;
      }
      .num,
      .more {
        font-size: 14px;
        line-height: 22px;
        font-weight: 400;
      }
      .num {
        margin-right: 22px;
        color: #1f2429;
      }
      .more {
        color: #025baa;
        cursor: pointer;
      }
    }
    .pictrue-container,
    .accessory-container {
      .item {
        padding: 10px 16px;
        width: 400px;
        border-radius: 4px;
        border: 1px solid rgba(233, 233, 233, 1);
        display: flex;
        align-items: center;
        cursor: pointer;
        > img {
          width: 24px;
          margin-right: 15px;
        }
        .info{
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      .item:not(:last-of-type) {
        margin-bottom: 8px;
      }
    }
    .accessory-container{
      position: relative;
      overflow: hidden;
      .expand-more{
        position: absolute;
        left: 444px;
        bottom: 0;
        color: #025baa;
        cursor: pointer;
        display: flex;
        align-items: center;
        >svg{
          margin-right: 4px;
          width: 16px;
          transition: transform .36s;
        }
        .expand{
          transform: rotate(180deg);
        }
      } 
    }
    .test-content {
      display: block;
      > div:first-child {
        margin-bottom: 13px;
      }
    }
  }
  .detail-container {
    display: flex;
    height: 600px;
  }
  .pictures-menu {
    margin-right: 21px;
    padding-top: 16px;
    padding-bottom: 16px;
    padding-right: 5px;
    height: 100%;
    overflow: auto;
    .item {
      > img {
        width: 180px;
        border: 4px solid rgba(245, 246, 247, 1);
        border-radius: 4px;
      }
      .name {
        width: 180px;
        font-size: 12px;
        color: #1f2429;
        line-height: 16px;
        margin-top: 12px;
        text-align: center;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      &:not(:last-of-type) {
        margin-bottom: 20px;
      }
    }
    .active>img{
      border-color: rgba(31, 35, 41, 0.15);
    }
  }
  .cur-img-container {
    padding: 20px;
    flex: 1;
    height: 100%;
    background: #f5f6f7;
    display: flex;
    justify-content: center;
    align-items: center;
    > img {
      max-width: 730px;
      max-height: 530px;
    }
  }
}
</style>