<template>
  <div class="user-management-container">
    <div class="side-layout">
      <div class="tree-side">
        <span class="type">操作类型</span>
        <div
          :style="{
            color: queryForm.operateType != '1' ? '#999999' : '#1D66DC',
            'margin-top': '20px',
            cursor: 'pointer',
          }"
          @click="search('1')">
          <i class="el-icon-message-solid" style="margin-right: 10px"></i>
          我的待办（{{ statisticsForm.toDoNumber }}）
        </div>
        <div
          :style="{
            color: queryForm.operateType != '2' ? '#999999' : '#1D66DC',
            'margin-top': '20px',
            cursor: 'pointer',
          }"
          @click="search('2')">
          <i class="el-icon-video-play" style="margin-right: 10px"></i>
          我发起的
        </div>
        <div
          :style="{
            color: queryForm.operateType != '3' ? '#999999' : '#1D66DC',
            'margin-top': '20px',
            cursor: 'pointer',
          }"
          @click="search('3')">
          <i class="el-icon-folder-checked" style="margin-right: 10px"></i>
          我处理的
        </div>
        <div class="type" style="margin-top: 50px">督办类型</div>
        <div
          :style="{ color: queryForm.taskType != '' ? '#999999' : '#1D66DC', 'margin-top': '20px', cursor: 'pointer' }"
          @click="searchType('')">
          全部
        </div>
        <div
          v-for="item in types"
          :key="item.dictCode"
          :style="{
            color: queryForm.taskType != item.dictValue ? '#999999' : '#1D66DC',
            'margin-top': '20px',
            cursor: 'pointer',
          }"
          @click="searchType(item.dictValue)">
          {{ item.dictLabel }}
        </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>
                <el-input v-model.trim="queryForm.taskTitle" clearable placeholder="请输入督办标题" />
              </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 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="height" width="100%">
          <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 }">
              <el-button v-if="item.prop === 'taskTitle'" class="link-button" type="text" @click="showDetail(row)">
                {{ row.taskTitle }}
              </el-button>
              <span v-if="item.prop === 'taskType'">
                {{ typeMap[row.taskType] }}
              </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>
              <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 === '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: 'Task',
    components: { taskAdd, taskDetail, TableTool },
    data() {
      return {
        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,
          taskType: '',
          operateType: '1',
        },
        // 用户信息
        userMap: {},
        users: [],
        // 类型信息
        typeMap: {},
        types: [],
        // 自定义列表
        checkList: [],
        columns: [
          {
            label: '督办标题',
            width: '280px',
            prop: 'taskTitle',
            sortable: false,
            disableCheck: true,
          },
          {
            label: '督办类型',
            width: '120px',
            prop: 'taskType',
            sortable: false,
          },
          {
            label: '状态',
            width: '120px',
            prop: 'taskStatus',
            sortable: false,
          },
          {
            label: '超期',
            width: '120px',
            prop: 'isOverdue',
            sortable: false,
          },
          {
            label: '督办说明',
            width: '120px',
            prop: 'taskDesc',
            sortable: false,
          },
          {
            label: '关联对象',
            width: '120px',
            prop: 'targetName',
            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: '160px',
            prop: 'taskStartDate',
            sortable: false,
          },
          {
            label: '结束时间',
            width: '160px',
            prop: 'taskEndDate',
            sortable: false,
          },
          {
            label: '创建时间',
            width: '160px',
            prop: 'createdTime',
            sortable: false,
          },
        ],
      }
    },
    computed: {
      finallyColumns() {
        return this.columns.filter((item) => this.checkList.includes(item.label))
      },
    },
    async created() {
      this.queryForm.operateType = '1'
      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.operateType = '1'
        this.queryForm.taskType = ''
        this.queryData()
      },
      // 左侧操作栏搜索
      search(type) {
        this.queryForm.operateType = type
        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.nickName
              }
            }
          })
          .catch((err) => {
            console.error(err)
          })
      },
      // 显示详情数据
      showDetail(row) {
        // this.theTask = JSON.parse(JSON.stringify(row))
        // this.detailDialogVisible = true
        this.$store.state.task.theTask = { ...row }
        this.$router.push({
          path: '/customer/plat/task/detail',
          query: {
            type: this.queryForm.operateType,
          },
        })
      },
      // 处理新增
      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
        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)
          })
      },
      // 团队成员
      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;
  }
</style>
