<template>
  <div :class="$style.mainDiv">
    <a-spin :spinning="spinning" :wrapper-class-name="$style.loadSpin">
      <div :class="$style.headerDiv">
        <!-- 选择年份下拉列表 -->
        <a-select
          :class="$style.yearSelect"
          :value="projectYear"
          :options="yearoptions"
          @change="changeYear"
        >
        </a-select>
        {{ projectYear }}年度{{ deptName }}计划跟踪表
        <!-- 导出按钮 -->
        <a-button
          type="primary"
          :class="$style.exportBtn"
          :loading="exporting"
          @click="exportExcel"
        >
          导出
        </a-button>
      </div>
      <div :class="$style.contentDiv">
        <div :class="$style.bannerDiv">
          <div :class="$style.changeDiv">
            <div
              :class="[$style.currentDiv, selectType === 'curday' ? $style.selectd : '']"
              @click="changeSelectType('curday')"
            >
              今天</div
            >
            <div
              :class="[$style.dayDiv, selectType === 'days' ? $style.selectd : '']"
              @click="changeSelectType('days')"
              >日</div
            >
            <div
              :class="[$style.weekDiv, selectType === 'weeks' ? $style.selectd : '']"
              @click="changeSelectType('weeks')"
              >周</div
            >
            <div
              :class="[$style.monthDiv, selectType === 'months' ? $style.selectd : '']"
              @click="changeSelectType('months')"
              >月</div
            >
          </div>
          <div :class="$style.colorDiv">
            <div :class="$style.outDiv"> <div :class="$style.planDiv"></div>计划 </div>
            <div :class="$style.outDiv"><div :class="$style.trueDiv"></div>实际</div>
          </div>
        </div>
        <div :class="$style.mainGantt">
          <!-- <div class="gantt"></div> -->
          <div class="gantt"></div>
        </div>
      </div>
    </a-spin>
  </div>
</template>

<script>
import download from '@/common/services/download'
import { Message } from 'ant-design-vue'
import moment from 'moment'
import { getUserInfo } from '@/common/store-mixin'
import axios from '@/common/services/axios-instance'
import components from './_import-components/iam-audit-plan-tracking-view-import'

// 初始化方法
function go(source, selectType, planYear) {
  window.$('.gantt').gantt({
    planYear: planYear,
    source: source,
    navigate: 'scroll', // buttons  scroll
    scale: selectType, // months  weeks days  hours
    months: [
      '一月',
      '二月',
      '三月',
      '四月',
      '五月',
      '六月',
      '七月',
      '八月',
      '九月',
      '十月',
      '十一月',
      '十二月',
    ],
    dow: ['7', '1', '2', '3', '4', '5', '6'],
    maxScale: 'months',
    minScale: 'days',
    itemsPerPage: 50,
    onItemClick: function(data) {
      // alert(data)
    },
    onAddClick: function() {
      // alert('这里是无数据区域点击')
    },
    onRender: function() {},
  })
}

export default {
  name: 'IamAuditPlanTrackingView',
  metaInfo: {
    title: '计划跟踪',
  },
  components,
  data() {
    return {
      exporting: false,
      yearoptions: [],
      projectYear: null,
      deptName: '',
      selectType: 'weeks',
      source: [],
      curYear: new Date().getFullYear(),
      spinning: true,
    }
  },
  mounted() {
    // 获取发布的年份列表
    axios({
      url: `api/xcoa-mobile/v1/iamauditplan/getPlanYear`,
    }).then((res) => {
      if ((res.data === '') | (res.data.length === 0)) {
        this.projectYear = this.curYear
        Message.info('未获取到已结束审计计划信息', 1)
        this.spinning = false
        return
      }
      res.data.forEach((item) => {
        this.yearoptions.push({
          value: parseFloat(item),
          label: parseFloat(item) + '',
        })
        // 如果有当前年份，则直接展示当前年份份
        if (parseFloat(item) === this.curYear) {
          this.projectYear = this.curYear
        }
      })
      if (this.projectYear === null) {
        // 如果只有一个年份，则直接展示这个年份
        if (res.data.length === 1) {
          this.projectYear = parseFloat(res.data[0])
        }
        if (res.data.length === 0) {
          this.projectYear = this.curYear
        }
      }
      // 初始化数据
      this.initData()
    })

    // 初始化数据
    // this.deptName = getUserInfo().deptName
    axios({
      url: 'api/xcoa-mobile/v1/iam-statistics/getCurrUserGroup',
      method: 'get',
    }).then((res) => {
      this.deptName = res.data.name
    })
  },
  methods: {
    // 导出excel
    exportExcel() {
      this.exporting = true
      axios({
        url: `api/xcoa-mobile/v1/iam-statistics/exportPlanTrackingList`,
        data: {
          maxResults: -1,
          startPosition: 0,
          expressions: [
            { dataType: 'str', name: 'planYear', op: 'eq', stringValue: '' + this.projectYear },
            { dataType: 'str', name: 'flowState', op: 'eq', stringValue: '结束' },
          ],
        },
        method: 'post',
        responseType: 'blob',
      }).then((res) => {
        const url = URL.createObjectURL(res.data)
        const fname = this.projectYear + '年度' + this.deptName + '计划跟踪表.xls'
        download(url, fname)
        this.exporting = false
      })
    },
    // 切换显示模式
    changeSelectType(selectType) {
      if (this.projectYear === null) {
        Message.info('未获取到已结束审计计划信息', 1)
        return
      }
      // 如果不是显示今天，则重新加载
      if (selectType !== 'curday' && selectType !== this.selectType) {
        this.selectType = selectType
        this.spinning = true
        go(this.source, this.selectType, this.projectYear)
        this.spinning = false
      } else {
        // 跳转至今天
        this.selectType = selectType
        window.$('.nav-now').click()
      }
    },
    // 切换年份下拉框
    changeYear(value) {
      this.projectYear = value
      this.initData()
    },

    // 初始化数据
    initData() {
      this.spinning = true
      // 获取计划跟踪后台数据
      axios({
        url: `api/xcoa-mobile/v1/iam-statistics/getPlanTrackingList`,
        data: {
          maxResults: 9999,
          startPosition: 0,
          expressions: [
            { dataType: 'str', name: 'planYear', op: 'eq', stringValue: '' + this.projectYear },
            { dataType: 'str', name: 'flowState', op: 'eq', stringValue: '结束' },
          ],
        },
        method: 'post',
      }).then((res) => {
        // 如果选择的年份没有数据，则顺延向前一年
        if (res.data.data.length === 0) {
          axios({
            url: `api/xcoa-mobile/v1/iam-statistics/getPlanTrackingList`,
            data: {
              maxResults: 9999,
              startPosition: 0,
              expressions: [
                {
                  dataType: 'str',
                  name: 'planYear',
                  op: 'eq',
                  stringValue: '' + (this.projectYear - 1),
                },
                { dataType: 'str', name: 'flowState', op: 'eq', stringValue: '结束' },
              ],
            },
            method: 'post',
          }).then((res) => {
            if (res.data.data.length === 0) {
              Message.info(this.projectYear + '年或' + (this.projectYear - 1) + '年未发布审计计划')
              this.projectYear = this.curYear
              // 重新加载当前年内容
              // this.initData()
              this.spinning = false
            } else {
              Message.info(
                this.projectYear + '年未发布当年审计计划，自动跳转至' + (this.projectYear - 1)
              )
              this.projectYear--
              this.formatData(res.data)
              this.spinning = false
            }
          })
        } else {
          this.formatData(res.data)
          this.spinning = false
        }
      })
    },

    // 格式化数据
    formatData(data) {
      // 重新拼接数据
      this.source = data.data.map((item) => {
        const newitem = {
          name: item.name,
          url: '#' + item.url,
          desc: item.desc ? item.desc : '未启动',
          values: [],
        }
        item.values.forEach((planitem, index) => {
          if (index === 0) {
            newitem.values.push({
              dataObj: null,
              customClass: 'ganttRed',
              from: planitem.from,
              to: planitem.to,
              label: '',
              desc:
                '<div class="plan-hint-div">' +
                '<div>项目名称：' +
                item.name +
                '</div>' +
                '<div>项目负责人：' +
                planitem.desc.chargeUser.join(',') +
                '</div>' +
                '<div>项目组长：' +
                planitem.desc.projectUser.join(',') +
                '</div>' +
                '<div>计划起止日期：' +
                moment(planitem.desc.startDate).format('YYYY-MM-DD') +
                '至' +
                moment(planitem.desc.endDate).format('YYYY-MM-DD') +
                '</div>' +
                '</div>',
            })
          } else {
            // 有起止时间，才进行拼接
            if (planitem.from !== '') {
              let descText =
                '<div class="true-hint-div">' +
                '<div>项目名称：' +
                item.name +
                '</div>' +
                '<div>项目负责人：' +
                planitem.desc.chargeUser.join(',') +
                '</div>' +
                '<div>项目组长：' +
                planitem.desc.projectUser.join(',') +
                '</div>'

              // 如果有准备起始时间，才拼接
              if (planitem.desc.prepareStartDate && planitem.desc.prepareDndDate) {
                descText +=
                  '<div>实际准备阶段：' +
                  moment(planitem.desc.prepareStartDate).format('YYYY-MM-DD') +
                  '至' +
                  moment(planitem.desc.prepareDndDate).format('YYYY-MM-DD') +
                  '</div>'
              } else {
                descText += '<div>实际准备阶段：</div>'
              }
              // 如果有实施起始时间，才拼接
              if (planitem.desc.effectStartDate && planitem.desc.effectEndDate) {
                descText +=
                  '<div>实际实施阶段：' +
                  moment(planitem.desc.effectStartDate).format('YYYY-MM-DD') +
                  '至' +
                  moment(planitem.desc.effectEndDate).format('YYYY-MM-DD') +
                  '</div>'
              } else {
                descText += '<div>实际实施阶段：</div>'
              }
              // 如果有报告起始时间，才拼接
              if (planitem.desc.reportStartDate && planitem.desc.reportEndDate) {
                descText +=
                  '<div>实际报告阶段：' +
                  moment(planitem.desc.reportStartDate).format('YYYY-MM-DD') +
                  '至' +
                  moment(planitem.desc.reportEndDate).format('YYYY-MM-DD') +
                  '</div>'
              } else {
                descText += '<div>实际报告阶段：</div>'
              }

              // 有提示才显示提示
              let islimit = false // 判断是否逾期
              if (planitem.desc.remind) {
                let remindStr = planitem.desc.remind.replace('提示：', '')
                if (remindStr.includes('逾期')) {
                  islimit = true
                }
                if (remindStr.substring(0, 1) === '；') {
                  remindStr = remindStr.substring(1, remindStr.length)
                }
                descText +=
                  '<div ' +
                  (islimit ? 'style="background:#ff4848 !important;color:white"' : '') +
                  '>提&emsp;&emsp;示：' +
                  remindStr +
                  '</div>' +
                  '</div>'
              } else {
                descText += '<div>提&emsp;&emsp;示：</div></div>'
              }

              newitem.values.push({
                dataObj: null,
                customClass: 'ganttGreen',
                from: planitem.from,
                to: planitem.to,
                label: '',
                desc: descText,
              })
            }
          }
        })
        return newitem
      })
      this.selectType = 'weeks'
      go(this.source, 'weeks', this.projectYear)
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.main-div {
  // height: 100%;
  padding-bottom: 30px;
  background: #fff;
  .header-div {
    height: 90px;
    font-size: 25px;
    font-weight: bold;
    line-height: 90px;
    text-align: center;
    border-bottom: 8px solid #f0f2f5;
    .year-select {
      top: 30px;
      left: 2.5%;
      float: left;
      width: 80px;
    }
    .export-btn {
      top: 30px;
      right: 2.5%;
      float: right;
    }
  }
  .content-div {
    height: calc(100% - 90px);
    .main-gantt {
      height: calc(100% - 100px);
      // overflow: auto;
    }
    .banner-div {
      height: 80px;
      .color-div {
        display: inline-block;
        float: right;
        height: 80px;
        margin-right: 50px;
        .out-div {
          display: inline-block;
          line-height: 80px;
          .plan-div {
            float: left;
            width: 40px;
            height: 26px;
            margin: 26px 10px;
            background: #facd91;
            border-radius: 5px;
          }
          .true-div {
            float: left;
            width: 40px;
            height: 26px;
            margin: 26px 10px;
            background: #6cf37c;
            border-radius: 5px;
          }
          .limit-div {
            float: left;
            width: 40px;
            height: 26px;
            margin: 26px 10px;
            background: #ff4848;
            border-radius: 5px;
          }
        }
      }
    }
  }
}
.change-div {
  display: inline-flex;
  float: right;
  margin-top: 22px;
  margin-right: 2.5%;
  user-select: none;
  user-select: none;
  user-select: none;
  div {
    float: left;
    width: 50px;
    height: 33px;
    line-height: 30px;
    text-align: center;
    cursor: pointer;
    border: 1px solid #e9e9e9;
    border-left: none;
  }
  .current-div {
    width: 65px;
    border-left: 1px solid #e9e9e9;
    border-radius: 5px 0 0 5px;
  }
  .day-div {
  }
  .week-div {
  }
  .month-div {
    border-radius: 0 5px 5px 0;
  }
  .selectd {
    border: 1px solid #1890ff;
  }
}
.load-spin {
  height: 100%;
  :global(.ant-spin-container) {
    height: 100%;
  }
}
</style>
