<template>
  <div class="user-management-container">
    <el-row :gutter="20" type="flex">
      <el-col :span="6">
        <span class="type">操作类型</span>
        <div style="margin-top: 25px; cursor: pointer" @click="search('1')">
          <i class="el-icon-message-solid" style="margin-right: 10px"></i>
          我的待办（{{ statisticsForm.toDoNumber }}）
        </div>
        <div style="margin-top: 20px; cursor: pointer" @click="search('2')">
          <i class="el-icon-video-play" style="margin-right: 10px"></i>
          我发起的（{{ statisticsForm.createNumber }}）
        </div>
        <div style="margin-top: 20px; cursor: pointer" @click="search('3')">
          <i class="el-icon-folder-checked" style="margin-right: 10px"></i>
          我处理的（{{ statisticsForm.completedNumber }}）
        </div>
        <div class="type" style="margin-top: 50px">督办类型</div>
        <div style="margin-top: 20px; cursor: pointer" @click="searchType('')">全部</div>
        <div
          v-for="item in types"
          :key="item.dictCode"
          style="margin-top: 20px; cursor: pointer"
          @click="searchType(item.dictValue)">
          {{ item.dictLabel }}
        </div>
      </el-col>
      <el-col :span="18">
        <el-row :gutter="10" style="margin-bottom: 10px">
          <el-col :span="4">
            <el-input v-model.trim="queryForm.taskTitle" clearable placeholder="请输入督办标题" />
          </el-col>
          <el-col :span="12">
            <el-button icon="el-icon-search" type="primary" @click="queryData">查询</el-button>
            <el-button icon="el-icon-refresh-right" @click="reset">重置</el-button>
          </el-col>
        </el-row>
        <vab-query-form>
          <vab-query-form-left-panel :span="12">
            <el-button 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 :check-list.sync="checkList" :columns="columns" />
          </vab-query-form-right-panel>
        </vab-query-form>
        <!-- 主页面 -->
        <el-table v-loading="listLoading" border :data="list" height="calc(100vh - 340px)">
          <el-table-column
            v-for="(item, index) in finallyColumns"
            :key="index"
            align="center"
            :label="item.label"
            :prop="item.prop"
            show-overflow-tooltip
            :sortable="item.sortable"
            :width="item.width">
            <template #default="{ row }">
              <span v-if="item.prop === 'taskType'">
                {{ typeMap[row.taskType] }}
              </span>
              <span v-else-if="item.prop === 'taskStatus'">
                {{ row.taskStatus === '10' ? '进行中' : '关闭' }}
              </span>
              <span v-else-if="item.prop === 'isOverdue'">
                {{ row.isOverdue === '10' ? '否' : '是' }}
              </span>
              <span v-else-if="item.prop === 'mainUserId' || item.prop === 'supervisorUserId'">
                {{ userMap[row[item.prop]] }}
              </span>
              <span
                v-else-if="item.prop === 'taskStartDate' || item.prop === 'taskEndDate' || item.prop === 'createdTime'">
                {{ parseTime(row[item.prop]) }}
              </span>
              <span v-else>{{ row[item.prop] }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="85">
            <template #default="{ row }">
              <el-button type="text" @click="showDetail(row)">查看</el-button>
            </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" />
      </el-col>
    </el-row>
    <!-- 新建督办 -->
    <taskAdd :do-refresh="doRefresh" :self-visible.sync="addDialogVisible" :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: 'Task',
    components: { taskAdd, taskDetail, TableTool },
    data() {
      return {
        // 各督办数量统计
        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,
          taskType: undefined,
          taskStatus: undefined,
          mySelf: undefined,
          isMain: undefined,
        },
        // 用户信息
        userMap: {},
        users: [],
        // 类型信息
        typeMap: {},
        types: [],
        // 自定义列表
        checkList: [],
        columns: [
          {
            label: '督办标题',
            width: 'auto',
            prop: 'taskTitle',
            sortable: true,
            disableCheck: true,
          },
          {
            label: '督办类型',
            width: 'auto',
            prop: 'taskType',
            sortable: true,
          },
          {
            label: '状态',
            width: 'auto',
            prop: 'taskStatus',
            sortable: true,
          },
          {
            label: '超期',
            width: 'auto',
            prop: 'isOverdue',
            sortable: true,
          },
          {
            label: '督办说明',
            width: 'auto',
            prop: 'taskDesc',
            sortable: true,
          },
          {
            label: '关联对象',
            width: 'auto',
            prop: 'targetName',
            sortable: true,
          },
          {
            label: '负责人',
            width: 'auto',
            prop: 'mainUserId',
            sortable: true,
          },
          {
            label: '督办人',
            width: 'auto',
            prop: 'supervisorUserId',
            sortable: true,
          },
          {
            label: '开始时间',
            width: 'auto',
            prop: 'taskStartDate',
            sortable: true,
          },
          {
            label: '结束时间',
            width: 'auto',
            prop: 'taskEndDate',
            sortable: true,
          },
          {
            label: '创建时间',
            width: 'auto',
            prop: 'createdTime',
            sortable: true,
          },
        ],
      }
    },
    computed: {
      height() {
        return this.$baseTableHeight(1)
      },
      finallyColumns() {
        return this.columns.filter((item) => this.checkList.includes(item.label))
      },
    },
    async created() {
      this.statistics()
      await this.initData()
      this.fetchData()
    },
    methods: {
      // 刷新表数据和数量统计
      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.finallyColumns.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.taskType = undefined
        this.queryForm.taskStatus = undefined
        this.queryForm.mySelf = undefined
        this.queryForm.isMain = undefined
        this.queryData()
      },
      // 左侧操作栏搜索
      search(type) {
        this.queryForm.taskStatus = undefined
        this.queryForm.mySelf = undefined
        this.queryForm.isMain = undefined
        if (type == '1') {
          this.queryForm.taskStatus = '10'
          this.queryForm.isMain = '1'
        }
        if (type == '2') {
          this.queryForm.mySelf = '1'
        }
        if (type == '3') {
          this.queryForm.taskStatus = '20'
          this.queryForm.isMain = '1'
        }
        this.queryData()
      },
      // 督办类型搜索
      searchType(type) {
        this.queryForm.taskType = type
        this.queryData()
      },
      // 初始化数据
      async initData() {
        await dictApi
          .getDictDataList({ dictType: 'TaskType' })
          .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()
          .then((res) => {
            if (res.data.list) {
              this.users = res.data.list
              for (let user of this.users) {
                this.userMap[user.id] = user.userName
              }
            }
          })
          .catch((err) => {
            console.error(err)
          })
      },
      // 显示详情数据
      showDetail(row) {
        this.theTask = JSON.parse(JSON.stringify(row))
        this.detailDialogVisible = true
      },
      // 处理新增
      handleAdd() {
        this.addDialogVisible = 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
        this.list = []
        taskApi
          .getTaskList(this.queryForm)
          .then((res) => {
            if (res.data.list) {
              this.list = res.data.list
            }
            this.total = res.data.total
            this.listLoading = false
          })
          .catch((err) => {
            this.listLoading = false
            console.error(err)
          })
      },
    },
  }
</script>
<style lang="scss" scoped>
  .type {
    font-weight: bold;
  }
</style>
