<template>
  <div class="table-page">
    <!--  四级路由切换  -->
    <page-route-tab />
    <div class="table-page-content">
      <div class="right-table">
        <div class="full-page bg">
          <div class="search-box">
            <el-row :gutter="24">
              <el-col :span="5">
                <el-select
                  v-model="orgId"
                  filterable
                  placeholder="请选择队伍"
                  style="width: 100%"
                  @change="changeOrg"
                >
                  <el-option
                    v-for="item in orgOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-select
                  v-model="rankId"
                  clearable
                  filterable
                  placeholder="请选择班种"
                  style="width: 100%"
                  @change="changeRank"
                >
                  <el-option
                    v-for="item in rankData"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="4">
                <!-- <el-button
                  class="btn btn-plus"
                  icon="el-icon-download"
                  type="primary"
                  @click="download"
                  >模板下载
                </el-button>
                <el-button
                  class="btn btn-plus"
                  icon="el-icon-upload"
                  type="warning"
                  @click="handleImport"
                  >导入
                </el-button> -->
                <el-popover
                  v-model="isShowPopover"
                  :width="popoverWidth"
                  placement="bottom-start"
                  popper-class="import-popover"
                  trigger="click"
                >
                  <div class="popover-container">
                    <div class="popover-container-title">
                      <div class="popover-container-title-left">
                        <i class="el-icon-warning" /> 提示：
                      </div>
                      <div
                        class="popover-container-title-right"
                        @click="isShowPopover = false"
                      >
                        <i class="el-icon-close" />
                      </div>
                    </div>
                    <div class="popover-container-content">
                      请下载排班模板并完成模板文件的录入后，导入已录入信息的模板文件。
                    </div>
                    <div class="popover-container-btn">
                      <el-button
                        :loading="downloadLoading"
                        class="btn btn-plus"
                        icon="el-icon-download"
                        plain
                        size="mini"
                        type="primary"
                        @click="downloadTemplate"
                      >
                        下载模版
                      </el-button>

                      <el-upload
                        ref="upload"
                        :action="action"
                        :before-upload="beforeUpload"
                        :data="importParams"
                        :headers="headers"
                        :multiple="false"
                        :on-error="handleError"
                        :on-success="handleSuccess"
                        :show-file-list="false"
                      >
                        <el-button
                          :loading="uploadLoading"
                          class="btn btn-plus"
                          icon="el-icon-upload2"
                          plain
                          size="mini"
                          type="warning"
                        >
                          导入模版
                        </el-button>
                      </el-upload>
                    </div>
                  </div>
                  <template v-slot:reference>
                    <el-button
                      class="btn btn-plus"
                      icon="el-icon-upload"
                      style="margin: 0 10px"
                      type="warning"
                    >
                      导入
                    </el-button>
                  </template>
                </el-popover>
              </el-col>
            </el-row>
          </div>
          <div class="main-table-container">
            <div class="table-container" style="padding: 20px">
              <div class="calendar">
                <el-calendar
                  v-model="calendarValue"
                  v-loading="loadingCalendar"
                >
                  <template slot="dateCell" slot-scope="{date, data}">
                    <div class="day-content">
                      <div class="header-class">
                        <div class="day-class">
                          {{ data.day.split('-').slice(1).join('-') }}
                        </div>
                      </div>
                      <template
                        v-if="
                          viewDate[data.day] &&
                          viewDate[data.day].length &&
                          data.day.slice(5, 7) == showMonth.slice(5, 7)
                        "
                      >
                        <div
                          v-for="(item, index) in viewDate[data.day]"
                          :key="index"
                          :style="`background-color: ${item.markColor}`"
                          class="paiban-class"
                          @click.stop.prevent="handleEdit(item, data)"
                        >
                          <div class="banzhong flex-between">
                            <span>
                              {{
                                item.rankName +
                                '（' +
                                item.workStartTime +
                                '-' +
                                item.workEndTime +
                                '）'
                              }}
                            </span>
                            <i
                              class="delect-paiban el-icon-close"
                              @click.stop.prevent="handleDelete(item.id)"
                            >
                            </i>
                          </div>

                          <span class="worker">{{ item.userName }} </span>
                        </div>
                        <div
                          class="addPaiban-class"
                          @click.stop.prevent="handleAdd(data)"
                        >
                          <i class="el-icon-plus"></i>
                        </div>
                      </template>
                      <template
                        v-else-if="
                          data.day.slice(5, 7) == showMonth.slice(5, 7)
                        "
                      >
                        <div
                          class="no-work-class flex-start"
                          @click.stop.prevent="handleAdd(data)"
                        >
                          <i class="el-icon-date"></i>
                          <span class="nowork-title"
                          >未排班 <i class="el-icon-plus"></i
                          ></span>
                        </div>
                      </template>
                    </div>
                  </template>
                </el-calendar>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {mapState} from 'vuex'
import moment from 'moment'
import PageRouteTab from '@/components/PageRouteTab/index.vue'
import PubSub from 'pubsub-js'
import {getTableData, orgTree} from '@/api/patrolAndRescue/roadWatch/inspectScheduling/inspectWorkGroupContent'

import {
  deleteArrangeInfo,
  getMonthArrangeInfo
} from '@/api/patrolAndRescue/roadWatch/inspectScheduling/inspectWorkUserContent'

import {calcFontSize} from '@/utils/responsiveUtils'

export default {
  name: 'CalenderPage',
  components: {
    PageRouteTab
  },
  props: {
    componentName: {
      default: 'CalenderPage',
      type: String
    }
  },
  data() {
    return {
      orgId: '',
      rankId: '',
      rankName: '',
      orgOptions: [],
      rankData: [],
      viewDate: {},
      showMonth: moment().format('YYYY-MM-DD'),
      calendarValue: '',
      loadingCalendar: false,
      firstDay: moment().startOf('month').format('YYYY-MM-DD'),
      isShowPopover: false, // 是否展示Popover
      uploadLoading: false, // 上传loading
      downloadLoading: false, // 下载模版loading
      popoverWidth: calcFontSize(360),
      importParams: {
        orgId: ''
      }
    }
  },
  created() {
    this.getOrgData()
  },
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.openPage()
        }
      }
    }
  },
  computed: {
    actionUrl: (_) => window.context.portal,
    action() {
      return `${this.actionUrl}/bizInspectRankUser/v1/import`
    },
    ...mapState({
      headers: (state) => ({
        Authorization: `Bearer ${state.login.currentUser.token}`
      })
    })
  },
  mounted() {
    this.pubSub = PubSub.subscribe('CalendarPage', (_, data) => {
      switch (data.type) {
        case 'add':
          break
        case 'edit':
          break
      }
    })
    this.$nextTick(() => {
      // 点击前一个月
      const prevBtn = document.querySelector(
        '.el-calendar__button-group .el-button-group>button:nth-child(1)'
      )
      prevBtn.addEventListener('click', (e) => {
        this.showMonth = moment(this.calendarValue).format('YYYY-MM-DD')
        this.loadMonthData()
      })

      // 点击下一个月
      const nextBtn = document.querySelector(
        '.el-calendar__button-group .el-button-group>button:nth-child(3)'
      )
      nextBtn.addEventListener('click', (e) => {
        this.showMonth = moment(this.calendarValue).format('YYYY-MM-DD')
        this.loadMonthData()
      })
    })
  },
  methods: {
    openPage() {
      this.showMonth = moment().format('YYYY-MM-DD')
      this.loadMonthData()
    },
    // 获取所在监控中心列表数据
    async getOrgData() {
      try {
        this.treeLoading = true
        let {value} = await orgTree() // 调用 API 获取树形数据
        // this.orgOptions = value
        this.orgOptions = value.children.reduce((accumulator, item) => {
          return accumulator.concat(item.teamList)
        }, [])
        // console.log(this.orgOptions, 'this.orgOptions')
        this.orgId = this.orgOptions?.[0]?.id || '' // 默认选择第一个监控中心
        this.loadRankData() // 加载班种数据
        this.loadMonthData() // 获取排班数据
      } finally {
        this.treeLoading = false // 无论成功或失败，都关闭加载状态
      }
    },
    // 加载班种数据
    loadRankData() {
      let query = {
        pageBean: {pageSize: -1, page: 1},
        querys: [
          {
            operation: 'EQUAL',
            property: 'orgId',
            value: this.orgId
          }
        ]
      }
      getTableData(query).then((res) => {
        this.rankData = res.rows
      })
    },
    changeOrg() {
      this.rankId = ''
      this.loadRankData()
      this.loadMonthData()
    },
    changeRank() {
      this.rankName =
        this.rankData.find((item) => item.id === this.rankId)?.name || ''
      this.loadMonthData()
    },
    //获取排班数据
    loadMonthData() {
      this.loadingCalendar = true
      this.viewDate = {}

      this.firstDay = moment(this.showMonth)
        .startOf('month')
        .format('YYYY-MM-DD')

      getMonthArrangeInfo({
        queryDate: this.firstDay,
        orgId: this.orgId || '',
        rankGroupId: this.rankId || ''
      }).then((res) => {
        let workData = res || []
        this.viewDate = {}
        workData.forEach((item) => {
          if (this.viewDate[item.rankDate]) {
            this.viewDate[item.rankDate].push(item)
          } else {
            this.viewDate[item.rankDate] = [item]
          }
          this.$set(this.viewDate, item.rankData, this.viewDate[item.rankDate])
        })
        this.loadingCalendar = false
      })
    },
    //添加
    handleAdd(day) {
      this.changePage('EditAddPage', {
        orgId: this.orgId,
        rankId: this.rankId,
        rankName: this.rankName,
        rankData: this.rankData,
        day
      })
    },
    handleEdit(item, day) {
      this.changePage('EditAddPage', {
        orgId: this.orgId,
        rankId: this.rankId,
        rankName: this.rankName,
        rankData: this.rankData,
        day,
        id: item.id
      })
    },
    handleDelete(id) {
      this.$confirm('确定删除选中排班吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteArrangeInfo(id).then((res) => {
          this.loadMonthData()
          if (!res.errorMsg) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
          }
        })
      })
    },
    // 下载导入模版
    downloadTemplate() {
      const fileType = '路巡任务排班信息导入模板.xls'
      var a = document.createElement('a')
      a.href = window.context.download + fileType
      a.download = fileType
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },

    // 文件上传前
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        this.uploadLoading = true
        const {size, name} = file
        this.$confirm(`请确认是否导入 “${name}” ？`, '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then((_) => {
            let passedOrNot = true // 是否通过验证
            const maxSize = 500 * 1024 * 1024 // 20MB
            const typeRegular = /\.(xls|xlsx)$/i
            const verification = [
              {
                condition: !typeRegular.test(name),
                result: () => this.$message.error('只能上传xls或xlsx文件类型')
              }
              // {
              //   condition: size > maxSize,
              //   result: () => this.$message.error('附件大小不能超过500MB')
              // }
            ]
            verification.forEach((item) => {
              if (item.condition) {
                item.result()
                passedOrNot = false
                this.uploadLoading = false
              }
            })
            this.importParams.orgId = this.orgId
            passedOrNot ? resolve() : reject()
            this.isShowPopover = passedOrNot
          })
          .catch((_) => {
            reject()
            this.isShowPopover = true
            this.uploadLoading = false
            this.$message.warning('已取消排班上传')
          })
      })
    },

    // 文化上传成功
    handleSuccess() {
      this.topicDialog = false
      this.$message.success('排班导入成功')
      this.uploadLoading = false
      this.loadMonthData()
      this.isShowPopover = false
    },

    // 文件上传失败
    handleError() {
      this.$message.error('排班导入失败，请重试')
      this.uploadLoading = false
      this.isShowPopover = false
    },

    // 改变页面
    changePage(pageName = '', row = {}) {
      if (!pageName) return
      this.$emit(
        'changePage',
        pageName,
        (_) => {
          PubSub.publish(pageName, row)
        },
        row.id ? '编辑' : '添加'
      )
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>


<style lang="scss" scoped>
.workUser-container {
  height: calc(100% - 80px - 30px);
  width: 100%;
  padding: 20px 20px;
  margin: 10px 0 20px 15px;
  border-radius: 8px 8px 8px 8px;
  background-color: #103c60;
  box-sizing: border-box;
  transition: height 0.3s linear;

  .calendar {
    height: 100%;
    width: 100%;
    overflow: hidden;

    .el-calendar {
      margin-right: 15px;
    }
  }
}

.day-content {
  width: 100%;
  height: calc(100% - 22px);
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  align-content: space-between;
}

.header-class {
  flex: 1;
  height: 22px;
  width: 100%;
  text-align: left;
}

.day-class {
  flex: 4;
  color: #144871;
}

.no-work-class {
  margin-top: 5px;
  width: 85px;
  height: 25px;
  box-sizing: border-box;
  padding: 5px 5px;
  color: #ffffff;
  font-size: 12px;
  display: flex;
  background-color: #e13030;
  border-radius: 4px 4px 4px 4px;
  transition: background-color 0.1s linear;
  -webkit-transition: background-color 0.1s linear;
  -moz-transition: background-color 0.1s linear;
  -ms-transition: background-color 0.1s linear;
  -o-transition: background-color 0.1s linear;

  .el-icon-date {
    vertical-align: middle;
    margin-top: 2px;
  }

  .nowork-title {
    display: inline-block;
    margin-left: 5px;
    font-size: 12px;
    vertical-align: middle;
  }
}

.no-work-class:hover {
  background-color: #d22a2a;
}

.paiban-class {
  width: 100%;
  height: calc(100% - 44px);
  margin-top: 5px;
  // height: 50%;
  box-sizing: border-box;
  padding: 5px 10px;
  border-radius: 4px 4px 4px 4px;
  background-color: #b914b6;

  span {
    font-size: 13px;
    color: #ffffffd1;
  }

  .banzhong {
    text-align: left;
    height: 20px;
    width: 100%;
    border-bottom: 1px solid #ffffffd1;
  }

  .worker {
    margin-top: 5px;
    display: block;
    text-align: left;
    height: calc(100% - 20px);
    width: 100%;
  }

  .delect-paiban {
    font-size: 14px;
    vertical-align: middle;
    color: #fff;
  }

  .delect-paiban:hover {
    color: #e13030;
  }
}

::v-deep .el-calendar {
  .el-calendar-table {
    min-height: 60px !important;
    height: auto;
  }

  .el-calendar-table .el-calendar-day {
    min-height: 100px !important;
    height: auto;
    text-align: center;
    border: none;
  }
}

.collapse-title {
  margin-left: 20px;
  color: #66b1fc;
}

.addPaiban-class {
  width: 100%;
  height: 22px;
  line-height: 22px;
  border-radius: 4px 4px 4px 4px;
  background-color: #fef0f0;
  border: 1px solid #fde4e4;
  margin-top: 5px;
  color: #f6928c;
  transition: background-color 0.1s linear;
  -webkit-transition: background-color 0.1s linear;
  -moz-transition: background-color 0.1s linear;
  -ms-transition: background-color 0.1s linear;
  -o-transition: background-color 0.1s linear;
}

.addPaiban-class:hover {
  background-color: #fde4e4;
}

::v-deep .el-button--plain {
  &:nth-child(2) {
    display: none;
  }
}

::v-deep .el-select__tags {
  .el-tag:nth-of-type(1) {
    .el-tag__close {
      display: none;
    }
  }
}

.calendar {
  height: 100%;
  width: 100%;
  overflow: auto;
}

.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.flex-start {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
</style>