<template>
  <div class="user-management-container">
    <div class="side-layout">
      <div class="tree-side">
        <span class="type">操作类型</span>
        <div
          :style="{
            color: queryForm.overdueDays != '' ? '#999999' : '#1D66DC',
            'margin-top': '20px',
            cursor: 'pointer',
          }"
          @click="search('')">
          <i class="el-icon-message-solid" style="margin-right: 10px"></i>
          全部督办
        </div>
        <div
          :style="{
            color: queryForm.overdueDays != '1' ? '#999999' : '#1D66DC',
            'margin-top': '20px',
            cursor: 'pointer',
          }"
          @click="search('1')">
          <i class="el-icon-video-play" style="margin-right: 10px"></i>
          超期1天
        </div>
        <div
          :style="{
            color: queryForm.overdueDays != '3' ? '#999999' : '#1D66DC',
            'margin-top': '20px',
            cursor: 'pointer',
          }"
          @click="search('3')">
          <i class="el-icon-folder-checked" style="margin-right: 10px"></i>
          超期3天
        </div>
        <div
          :style="{
            color: queryForm.overdueDays != '5' ? '#999999' : '#1D66DC',
            'margin-top': '20px',
            cursor: 'pointer',
          }"
          @click="search('5')">
          <i class="el-icon-warning-outline" style="margin-right: 10px"></i>
          超期5天
        </div>
        <div
          :style="{
            color: queryForm.overdueDays != '>5' ? '#999999' : '#1D66DC',
            'margin-top': '20px',
            cursor: 'pointer',
          }"
          @click="search('>5')">
          <i class="el-icon-remove-outline" style="margin-right: 10px"></i>
          超期5天以上
        </div>
      </div>
      <div class="tree-table">
        <vab-query-form>
          <vab-query-form-top-panel>
            <el-form :inline="true" :model="queryForm" @submit.native.prevent>
              <el-form-item label="负责人">
                <el-select
                  v-model="queryForm.mainUserId"
                  clearable
                  filterable
                  placeholder="请选择负责人"
                  @keyup.enter.native="queryData">
                  <el-option v-for="user in users" :key="user.id" :label="user.nickName" :value="user.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="督办人">
                <el-select
                  v-model="queryForm.supervisorUserId"
                  clearable
                  filterable
                  placeholder="请选择督办人"
                  @keyup.enter.native="queryData">
                  <el-option v-for="user in users" :key="user.id" :label="user.nickName" :value="user.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="发起人">
                <el-select
                  v-model="queryForm.createdById"
                  clearable
                  filterable
                  placeholder="请选择发起人"
                  @keyup.enter.native="queryData">
                  <el-option v-for="user in users" :key="user.id" :label="user.nickName" :value="user.id" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button icon="el-icon-search" type="primary" @click="queryData">查询</el-button>
                <el-button icon="el-icon-refresh-right" @click="reset">重置</el-button>
              </el-form-item>
            </el-form>
          </vab-query-form-top-panel>
          <vab-query-form-left-panel :span="12">
            <el-button v-permissions="['plat:task:add']" icon="el-icon-plus" type="primary" @click="handleAdd">
              添加
            </el-button>
          </vab-query-form-left-panel>
          <vab-query-form-right-panel :span="12">
            <!-- <el-button icon="el-icon-download" @click="exportData" /> -->
            <table-tool :columns="columns" :show-columns.sync="showColumns" table-type="taskTable" />
          </vab-query-form-right-panel>
        </vab-query-form>
        <!-- 主页面 -->
        <el-table
          ref="table"
          v-loading="listLoading"
          border
          :data="list"
          :height="height"
          :row-class-name="tableRowClassName"
          width="100%">
          <el-table-column
            v-for="(item, index) in showColumns"
            :key="index"
            align="center"
            :label="item.label"
            :prop="item.prop"
            show-overflow-tooltip
            :sortable="item.sortable"
            :width="item.width">
            <template #default="{ row }">
              <el-button v-if="item.prop === 'taskTitle'" class="link-button" type="text" @click="showDetail(row)">
                {{ row.taskTitle }}
              </el-button>
              <span v-else-if="item.prop === 'taskType'">
                {{ typeMap[row.taskType] }}
              </span>
              <span v-else-if="item.prop === 'source'">
                {{ selectDictLabel(sourceOptions, row.source) }}
              </span>
              <span v-else-if="item.prop === 'taskStatus'">
                <span v-if="row.taskStatus === '10'">发起</span>
                <span v-if="row.taskStatus === '20'">进行中</span>
                <span v-if="row.taskStatus === '30'">流程完成</span>
                <span v-if="row.taskStatus === '40'">审批拒绝</span>
                <span v-if="row.taskStatus === '50'">撤销</span>
              </span>
              <span v-else-if="item.prop === 'isOverdue'">
                {{ isNotOverdue(parseTime(row['taskEndDate'], '{y}-{m}-{d} 23:59:59'), row) ? '否' : '是' }}
              </span>
              <span
                v-else-if="
                  item.prop === 'mainUserId' || item.prop === 'supervisorUserId' || item.prop === 'watchUserId'
                ">
                {{ userMap[row[item.prop]] }}
              </span>
              <span v-else-if="item.prop === 'ownerUserId'">
                {{ generateTeamMembers(row[item.prop]) }}
              </span>
              <span
                v-else-if="item.prop === 'taskStartDate' || item.prop === 'taskEndDate' || item.prop === 'createdTime'">
                {{ parseTime(row[item.prop], '{y}-{m}-{d}') }}
              </span>
              <span v-else>{{ row[item.prop] }}</span>
            </template>
          </el-table-column>
          <template #empty>
            <el-image class="vab-data-empty" :src="require('@/assets/empty_images/data_empty.png')" />
          </template>
        </el-table>
        <el-pagination
          background
          :current-page="queryForm.pageNum"
          :layout="layout"
          :page-size="queryForm.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange" />
      </div>
    </div>
    <!-- 新建督办 -->
    <taskAdd ref="taskAdd" :do-refresh="doRefresh" :types="types" :users="users" />
    <!-- 查看详情 -->
    <taskDetail
      :do-refresh="doRefresh"
      :self-visible.sync="detailDialogVisible"
      :the-task="theTask"
      :type-map="typeMap"
      :user-map="userMap" />
  </div>
</template>

<script>
  import taskApi from '@/api/plat/task'
  import userApi from '@/api/system/user'
  import dictApi from '@/api/system/dict'
  import taskAdd from './components/TaskAdd.vue'
  import taskDetail from './components/TaskDetail.vue'
  import TableTool from '@/components/table/TableTool'
  import downloadFileByByte from '@/utils/base64ToFile'

  export default {
    name: 'AllTask',
    components: { taskAdd, taskDetail, TableTool },
    data() {
      return {
        // 判断当前督办是否可以进行操作
        taskMap: {},
        height: this.$baseTableHeight(2),
        // 各督办数量统计
        statisticsForm: {
          toDoNumber: 0,
          createNumber: 0,
          completedNumber: 0,
        },
        // 督办详情查看
        detailDialogVisible: false,
        // 新建弹窗控制
        addDialogVisible: false,
        // 展示的督办数据
        theTask: {},
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        queryForm: {
          pageNum: 1,
          pageSize: 10,
          taskTitle: undefined,
          source: '',
          operateType: '5',
          overdueDays: '',
          isOverdue: '',
          mainUserId: '',
          supervisorUserId: '',
          createdById: '',
        },
        // 用户信息
        userMap: {},
        users: [],
        // 类型信息
        typeMap: {},
        types: [],
        sourceOptions: [],
        // 自定义列表
        showColumns: [],
        columns: [
          {
            label: '督办标题',
            width: '280px',
            prop: 'taskTitle',
            sortable: false,
            disableCheck: true,
          },
          {
            label: '督办内容',
            width: '320px',
            prop: 'taskDesc',
            sortable: false,
          },
          // {
          //   label: '督办类型',
          //   width: '120px',
          //   prop: 'taskType',
          //   sortable: false,
          // },
          {
            label: '状态',
            width: '120px',
            prop: 'taskStatus',
            sortable: false,
          },
          // {
          //   label: '事项来源',
          //   width: '120px',
          //   prop: 'source',
          //   sortable: false,
          // },
          {
            label: '负责人',
            width: '120px',
            prop: 'mainUserId',
            sortable: false,
          },
          {
            label: '协办人',
            width: '180px',
            prop: 'ownerUserId',
            sortable: false,
          },
          {
            label: '督办人',
            width: '120px',
            prop: 'supervisorUserId',
            sortable: false,
          },
          {
            label: '监办人',
            width: '120px',
            prop: 'watchUserId',
            sortable: false,
          },
          {
            label: '发布时间',
            width: '120px',
            prop: 'taskStartDate',
            sortable: false,
          },
          {
            label: '要求完成时间',
            width: '120px',
            prop: 'taskEndDate',
            sortable: false,
          },
          {
            label: '提醒规则',
            width: '200px',
            prop: 'reminderRuleInfo',
            sortable: false,
          },
          // {
          //   label: '创建时间',
          //   width: '160px',
          //   prop: 'createdTime',
          //   sortable: false,
          // },
          {
            label: '是否超期',
            width: '120px',
            prop: 'isOverdue',
            sortable: false,
          },
        ],
      }
    },
    watch: {
      showColumns: function () {
        this.$nextTick(() => this.$refs.table.doLayout())
      },
    },
    async created() {
      if (this.$route.params.isOverdue) {
        this.queryForm.isOverdue = this.$route.params.isOverdue
      }
      this.queryForm.operateType = '5'
      this.statistics()
      await this.initData()
      this.fetchData()
    },
    activated() {
      if (this.$route.params.isOverdue) {
        this.queryForm.isOverdue = this.$route.params.isOverdue
        this.queryForm.operateType = '5'
      }
      this.statistics()
      this.fetchData()
    },
    methods: {
      // 获取我的待办
      async getMyTasks() {
        await taskApi
          .getTaskList({ pageNum: 1, pageSize: 9999, operateType: '1' })
          .then((res) => {
            if (res.data.list) {
              for (let item of res.data.list) {
                this.taskMap[item.id] = item
              }
            }
          })
          .catch((err) => {
            console.error(err)
          })
      },
      // 单元格样式控制
      tableRowClassName({ row, rowIndex }) {
        if (this.taskMap[row.id]) {
          return 'warning-row'
        }
        return ''
      },
      // 接收任务
      receiveTask(task) {
        this.$confirm('确定接收该督办？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(async () => {
          let data = {
            taskId: task.id,
            step: 10,
            handleStatus: '10',
          }
          const { msg } = await taskApi.handleTask(data)
          this.$baseMessage(msg, 'success', 'vab-hey-message-success')
          this.doRefresh()
        })
      },
      // 判断是否没有超期
      isNotOverdue(date, row) {
        return new Date() <= new Date(date) || (row.taskStatus != '10' && row.taskStatus != '20')
      },
      // 刷新表数据和数量统计
      doRefresh() {
        this.fetchData()
        this.statistics()
      },
      // 统计各类型督办数量
      statistics() {
        taskApi
          .statisticsTaskNumber()
          .then((res) => {
            if (res.data.list) {
              this.statisticsForm = res.data.list
            }
          })
          .catch((err) => {
            console.error(err)
          })
      },
      // 数据导出
      exportData() {
        let exportFrom = JSON.parse(JSON.stringify(this.queryForm))
        exportFrom.columns = this.showColumns.map((item) => item.label)
        taskApi
          .exportTasks(exportFrom)
          .then((res) => {
            if (res.data.list.content) {
              downloadFileByByte(res.data.list.content, '督办数据.xlsx')
            }
          })
          .catch((err) => {
            console.error(err)
          })
      },
      // 重置查询数据
      reset() {
        this.queryForm.pageNum = 1
        this.queryForm.pageSize = 10
        this.queryForm.taskTitle = undefined
        this.queryForm.isOverdue = ''
        this.queryForm.operateType = '5'
        this.queryForm.overdueDays = ''
        this.queryForm.source = ''
        this.queryForm.mainUserId = ''
        this.queryForm.supervisorUserId = ''
        this.queryForm.createdById = ''
        this.queryData()
      },
      // 左侧操作栏搜索
      search(type) {
        this.queryForm.overdueDays = type
        this.queryData()
      },
      // 事项来源搜索
      searchSource(source) {
        this.queryForm.source = source
        this.queryData()
      },
      // 初始化数据
      async initData() {
        await dictApi
          .getDictDataList({ dictType: 'task_type', pageNum: 1, pageSize: 9999 })
          .then((res) => {
            if (res.data.list) {
              this.types = res.data.list
              for (let type of this.types) {
                this.typeMap[type.dictValue] = type.dictLabel
              }
            }
          })
          .catch((err) => {
            console.error(err)
          })
        await userApi
          .getList({ pageNum: 1, pageSize: 9999 })
          .then((res) => {
            if (res.data.list) {
              this.users = res.data.list
              for (let user of this.users) {
                this.userMap[user.id] = user.nickName
              }
            }
          })
          .catch((err) => {
            console.error(err)
          })
        this.getDicts('plat_task_source').then((response) => {
          this.sourceOptions = response.data.values || []
        })
        await this.getMyTasks()
      },
      // 显示详情数据
      showDetail(row) {
        if (this.taskMap[row.id]) {
          this.$store.state.task.theTask = { ...this.taskMap[row.id] }
        } else {
          this.$store.state.task.theTask = { ...row }
        }
        this.$router.push({
          path: '/plat/task/detail',
          query: {
            type: this.taskMap[row.id] ? '1' : '5',
            pageType: '5',
          },
        })
      },
      // 处理新增
      handleAdd() {
        // this.addDialogVisible = true
        this.$refs.taskAdd.selfVisible = true
      },
      // 更换页数据大小
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      // 更换当前页
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.fetchData()
      },
      // 查询
      queryData() {
        this.queryForm.pageNum = 1
        this.fetchData()
      },
      // 获取数据
      fetchData() {
        this.listLoading = true
        let params = JSON.parse(JSON.stringify(this.queryForm))
        params.mainUserId += ''
        params.supervisorUserId += ''
        params.createdById += ''
        this.list = []
        taskApi
          .getTaskList(params)
          .then((res) => {
            if (res.data.list) {
              for (let item of res.data.list) {
                if (item.reminderRule == '') {
                  item.reminderRuleInfo = '不提醒'
                } else {
                  let rules = item.reminderRule.split(' ')
                  if (rules[3] == '*') {
                    item.reminderRuleInfo = '每天在' + rules[2] + ':' + rules[1] + ':' + rules[0] + '提醒'
                  } else if (rules[3] == '?') {
                    item.reminderRuleInfo =
                      '每周周' + rules[4] + '在' + rules[2] + ':' + rules[1] + ':' + rules[0] + '提醒'
                  } else {
                    item.reminderRuleInfo =
                      '每月' + rules[3] + '日在' + rules[2] + ':' + rules[1] + ':' + rules[0] + '提醒'
                  }
                }
              }
              this.list = res.data.list
            }
            this.total = res.data.total
            this.listLoading = false
            this.$nextTick(() => this.$refs.table.doLayout())
          })
          .catch((err) => {
            this.listLoading = false
            console.error(err)
          })
      },
      // 协办人
      generateTeamMembers(ids) {
        if (!ids) {
          return ''
        } else {
          let names = ''
          let idArray = ids.split(',')
          for (let id of idArray) {
            if (names == '') {
              names = this.userMap[parseInt(id)]
            } else {
              names += ',' + this.userMap[parseInt(id)]
            }
          }

          return names
        }
      },
    },
  }
</script>
<style lang="scss" scoped>
  .type {
    font-weight: bold;
  }

  $base: '.list';
  .link-button {
    font-size: 14px;
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  ::v-deep .el-table .warning-row {
    background: oldlace;
  }
  ::v-deep .el-table .danger-row {
    background: #f56c6c;
  }
</style>
