<template>
  <el-container class="list_main_content">
    <el-aside width="200px">
      <b class="top-title el-icon-menu">待办信息分类</b>
      <FlowTree
        ref="FlowTree"
        v-if="isRefresh"
        @currentTree="getCurrent"
        :loadCount="loadCount"
        :data="data"
      ></FlowTree>
    </el-aside>
    <el-container style="border-left:1px solid #E7EAEC">
      <el-main>
        <div class="query-box">
          <div>
                        <el-button size="small" @click="divertClick" type="primary"  icon="icon-zhuanyi">转移</el-button>
          </div>
      <div class="query-box_right">
           <div>
            <el-input
              size="small"
              clearable
              placeholder="标题/编号/流程名称/任务名称/扩展字段"
              prefix-icon="el-icon-search"
              v-model="tableData"
              style="width:300px;"
              @keyup.enter.native="searchEnterFun"
            ></el-input>
          </div>
          <div style="margin:0 15px">
            <el-date-picker
              v-model="date"
              type="datetimerange"
              align="right"
              size="small"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
            ></el-date-picker>
          </div>
          <div>
            <el-button size="small" type="primary" @click="search('find')"  icon="el-icon-search"
              >搜索</el-button
            >
            <el-button size="small" @click="reset" icon="icon-my-todo-reset">重置</el-button>

          </div>
       </div>
        </div>
        <!-- default-sort 默认不排序（排序时查询待办很慢，用户可以点击某列进行排序） -->
        <el-table
          ref="todoTable"
          :data="rows"
          border
          style="width: 100%"
          header-cell-class-name="header-row-bg"
          row-class-name="flow-table-row"
          size="medium"
          :max-height="500"
          v-loading="fullscreenLoading"
          v-if="defaultFiledShowConf"
        >
          <el-table-column
            type="selection"
            width="50"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="procInstId"
            :label="defaultFiledShowConf.procInstId.desc"
            v-if="defaultFiledShowConf.procInstId.frontShow"
            show-overflow-tooltip
            align="center"
            width="200"
          ></el-table-column>
          <el-table-column
            :label="defaultFiledShowConf.subject.desc"
            v-if="defaultFiledShowConf.subject.frontShow"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span>{{ scope.row.subject }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="defaultFiledShowConf.procDefName.desc"
            v-if="defaultFiledShowConf.procDefName.frontShow"
            show-overflow-tooltip
            align="center"
            width="200"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.procDefName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="defaultFiledShowConf.name.desc"
            v-if="defaultFiledShowConf.name.frontShow"
            show-overflow-tooltip
            align="center"
            width="200"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            :label="defaultFiledShowConf.createTime.desc"
            v-if="defaultFiledShowConf.createTime.frontShow"
            align="center"
            width="150"
          ></el-table-column>
          <el-table-column
            prop="creator"
            :label="defaultFiledShowConf.creator.desc"
            v-if="defaultFiledShowConf.creator.frontShow"
            align="center"
            width="90"
          ></el-table-column>
          <el-table-column
            prop="ownerName"
            :label="defaultFiledShowConf.ownerName.desc"
            v-if="defaultFiledShowConf.ownerName.frontShow"
            align="center"
            width="90"
          ></el-table-column>
          <el-table-column
            prop="assigneeName"
            :label="defaultFiledShowConf.assigneeName.desc"
            v-if="defaultFiledShowConf.assigneeName.frontShow"
            align="center"
            width="90"
          ></el-table-column>
          <el-table-column
            width="100"
            :label="defaultFiledShowConf.status.desc"
            v-if="defaultFiledShowConf.status.frontShow"
            align="center"
          >
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status == 'NORMAL'" size="small"
                >待办</el-tag
              >
              <el-tag v-if="scope.row.status == 'TRANSFORMED'" size="small"
                >流转</el-tag
              >
              <el-tag v-if="scope.row.status == 'TRANSFORMEDINQU'" size="small"
                >征询</el-tag
              >
              <el-tag v-if="scope.row.status == 'DELIVERTO'" size="small"
                >转办</el-tag
              >
              <el-tag v-if="scope.row.status == 'FOLLOW'" size="small"
                >跟踪</el-tag
              >
              <el-tag v-if="scope.row.status == 'COMMU'" size="small"
                >沟通</el-tag
              >
              <el-tag v-if="scope.row.status == 'BACK'" size="small"
                >驳回</el-tag
              >
              <el-tag v-if="scope.row.status == 'ADDSIGN'" size="small"
                >加签</el-tag
              >
              <el-tag v-if="scope.row.status == 'AGENT'" size="small"
                >委托</el-tag
              >
              <el-tag v-if="scope.row.status == 'SHARE'" size="small"
                >共享</el-tag
              >
              <el-tag v-if="scope.row.status == 'BACKSHARE'" size="small"
                >驳回共享</el-tag
              >
              <el-tag v-if="scope.row.status == 'APPROVELINEED'" size="small"
                >并行审批</el-tag
              >
              <el-tag v-if="scope.row.status == 'SIGNSEQUENCEED'" size="small"
                >顺序签署</el-tag
              >
              <el-tag v-if="scope.row.status == 'SIGNLINEED'" size="small"
                >并行签署</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="prop1"
            :label="defaultFiledShowConf.prop1&&defaultFiledShowConf.prop1.desc"
            v-if="defaultFiledShowConf.prop1&&defaultFiledShowConf.prop1.frontShow"
            align="center"
            width="100"
          ></el-table-column>
          <el-table-column
            prop="prop2"
            :label="defaultFiledShowConf.prop2.desc"
            v-if="defaultFiledShowConf.prop2.frontShow"
            align="center"
            width="100"
          ></el-table-column>
          <el-table-column
            prop="prop3"
            :label="defaultFiledShowConf.prop3.desc"
            v-if="defaultFiledShowConf.prop3.frontShow"
            align="center"
            width="100"
          ></el-table-column>
          <el-table-column
            prop="prop4"
            :label="defaultFiledShowConf.prop4.desc"
            v-if="defaultFiledShowConf.prop4.frontShow"
            align="center"
            width="100"
          ></el-table-column>
          <el-table-column
            prop="prop5"
            :label="defaultFiledShowConf.prop5.desc"
            v-if="defaultFiledShowConf.prop5.frontShow"
            align="center"
            width="100"
          ></el-table-column>
          <el-table-column
            prop="prop6"
            :label="defaultFiledShowConf.prop6.desc"
            v-if="defaultFiledShowConf.prop6.frontShow"
            align="center"
            width="100"
          ></el-table-column>
          <el-table-column label="到期时间" width="100">
            <template slot-scope="scope">
              <span :style="computeColor(scope.row.deadline)">{{
                computeTime(scope.row.deadline)
              }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer height="50px" style="padding:10px 0">
        <el-row type="flex" justify="end" >
          <el-pagination
           background
            :disabled="fullscreenLoading"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.page"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
          ></el-pagination>
        </el-row>
      </el-footer>
    </el-container>
    <!--用户选择对话框  -->
    <ht-user-dialog
      ref="eipUserDialog"
      @on-confirm="eipUserDialogOk"
      single
      append-to-body
    />
    <!-- 组织选择对话框  -->
    <ht-org-post-dialog
      ref="eipOrgDialog"
      @on-confirm="eipOrgDialogOk"
      single
      append-to-body
    />
    <!-- 岗位选择对话框  -->
    <ht-post-dialog
      ref="eipPostDialog"
      @on-confirm="eipPostDialogOk"
      single
      append-to-body
    />
    <!-- 角色选择对话框  -->
    <ht-role-dialog
      ref="eipRoleDialog"
      @on-confirm="eipRoleDialogOk"
      single
      append-to-body
    />
  </el-container>
</template>

<script>
import req from '@/request.js'
import FlowTree from '@/views/flow/permissionAdjustment/FlowTree.vue'
import utils from '@/hotent-ui-util.js'
import flow from '@/api/flow.js'
import {Message} from 'element-ui'
const eipUserDialog = () => import('@/components/dialog/EipUserDialog.vue')
const eipOrgDialog = () => import('@/components/dialog/EipOrgDialog.vue')
const eipPostDialog = () => import('@/components/dialog/EipPostDialog.vue')
const eipRoleDialog = () => import('@/components/dialog/EipRoleDialog.vue')
let Base64 = require('js-base64').Base64
export default {
  name: 'todo',
  components: {
    FlowTree,
    eipUserDialog,
    eipOrgDialog,
    eipPostDialog,
    eipRoleDialog
  },
  props: ['data'],
  data() {
    return {
      isRefresh: true,
      maxHeight: '500', //列表高度
      tableData: '',
      date: '',
      currentTree: '',
      fullscreenLoading: true,
      sorter: [],
      urgentStateConf: {},
      urgentStateConfList: [],
      urgentStateVal: '',
      ids: '', //待办任务id集合
      defaultFiledShowConf: '',
      defaultFiledShowConfList: [
        {name: 'subject', desc: '标题', frontShow: true},
        {name: 'procInstId', desc: '流程编号', frontShow: true},
        {name: 'procDefName', desc: '流程名称', frontShow: true},
        {name: 'name', desc: '任务名称', frontShow: true},
        {name: 'status', desc: '类型', frontShow: true},
        {name: 'createTime', desc: '创建时间', frontShow: true},
        {name: 'creator', desc: '创建人', frontShow: true},
        {name: 'urgentStateValue', desc: '紧急状态', frontShow: true},
        {name: 'dueExpDate', desc: '到期时间', frontShow: false},
        {name: 'ownerName', desc: '所属人', frontShow: false},
        {name: 'assigneeName', desc: '待审批人', frontShow: false},
        {name: 'prop1', desc: '扩展1', frontShow: false},
        {name: 'prop2', desc: '扩展2', frontShow: false},
        {name: 'prop3', desc: '扩展3', frontShow: false},
        {name: 'prop4', desc: '扩展4', frontShow: false},
        {name: 'prop5', desc: '扩展5', frontShow: false},
        {name: 'prop6', desc: '扩展6', frontShow: false}
      ],
      rows: [],
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      selectTaskIds: [] //选择要转移的taskId
    }
  },
  watch: {
    data: {
      handler(newValue, oldValue) {
        this.$nextTick(() => {
          this.createdSearch()
        })
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    //转移
    divertClick() {
      this.selectTaskIds = []
      let selectSelection = this.$refs.todoTable.selection
      if (selectSelection && selectSelection.length == 0) {
        this.$message.error('请选择要转移的任务')
        return
      }
      for (let k = 0; k < selectSelection.length; k++) {
        this.selectTaskIds.push(selectSelection[k].id)
      }
      if (this.data.type == 'user') {
        this.$refs['eipUserDialog'].showDialog()
      }
      if (this.data.type == 'org') {
        this.$refs['eipOrgDialog'].showDialog()
      }
      if (this.data.type == 'post') {
        this.$refs['eipPostDialog'].showDialog()
      }
      if (this.data.type == 'role') {
        this.$refs['eipRoleDialog'].showDialog()
      }
    },
    //选择用户确认事件
    eipUserDialogOk(data) {
      if (data[0]) {
        if (this.data.typeValue.id == data[0].id) {
          this.$message.error('所选任务不能转移给自己')
          return
        }
        let map = {
          type: this.data.type,
          oldUserId: this.data.typeValue.id,
          oldUserName: this.data.typeValue.fullname,
          userId: data[0].id,
          userName: data[0].fullname,
          taskIds: this.selectTaskIds
        }
        this.isRefresh = false
        req
          .post(
            window.context.bpmRunTime + '/runtime/task/v1/divertBpmTask',
            map
          )
          .then(res => {
            this.isRefresh = true
            if (res.data.state) {
              this.$message.success(res.data.message)
              this.$nextTick(() => {
                this.createdSearch()
              })
            }
          })
          .catch(() => {
            this.isRefresh = true
          })
      }
    },
    //选择所属组织确认事件
    eipOrgDialogOk(data) {
      if (data[0]) {
        if (this.data.typeValue.id == data[0].id) {
          this.$message.error('所选任务不能转移给自己')
          return
        }
        let map = {
          type: this.data.type,
          oldOrgId: this.data.typeValue.id,
          oldOrgName: this.data.typeValue.name,
          orgId: data[0].id,
          orgName: data[0].name,
          taskIds: this.selectTaskIds
        }
        this.isRefresh = false
        req
          .post(
            window.context.bpmRunTime + '/runtime/task/v1/divertBpmTask',
            map
          )
          .then(res => {
            this.isRefresh = true
            if (res.data.state) {
              this.$message.success(res.data.message)
              this.$nextTick(() => {
                this.createdSearch()
              })
            }
          })
          .catch(() => {
            this.isRefresh = true
          })
      }
    },
    //选择所属岗位确认事件
    eipPostDialogOk(data) {
      if (data[0]) {
        if (this.data.typeValue.id == data[0].id) {
          this.$message.error('所选任务不能转移给自己')
          return
        }
        let map = {
          type: this.data.type,
          oldPostId: this.data.typeValue.id,
          oldPostName: this.data.typeValue.name,
          postId: data[0].id,
          postName: data[0].name,
          taskIds: this.selectTaskIds
        }
        this.isRefresh = false
        req
          .post(
            window.context.bpmRunTime + '/runtime/task/v1/divertBpmTask',
            map
          )
          .then(res => {
            this.isRefresh = true
            if (res.data.state) {
              this.$message.success(res.data.message)
              this.$nextTick(() => {
                this.createdSearch()
              })
            }
          })
          .catch(() => {
            this.isRefresh = true
          })
      }
    },
    //选择所属角色确认事件
    eipRoleDialogOk(data) {
      if (data[0]) {
        if (this.data.typeValue.id == data[0].id) {
          this.$message.error('所选任务不能转移给自己')
          return
        }
        let map = {
          type: this.data.type,
          oldRoleId: this.data.typeValue.id,
          oldRoleName: this.data.typeValue.name,
          roleId: data[0].id,
          roleName: data[0].name,
          taskIds: this.selectTaskIds
        }
        this.isRefresh = false
        req
          .post(
            window.context.bpmRunTime + '/runtime/task/v1/divertBpmTask',
            map
          )
          .then(res => {
            this.isRefresh = true
            if (res.data.state) {
              this.$message.success(res.data.message)
              this.$nextTick(() => {
                this.createdSearch()
              })
            }
          })
          .catch(() => {
            this.isRefresh = true
          })
      }
    },
    //动态计算列表高度
    setMaxHeight(item) {
      const this_ = this
      setTimeout(() => {
        if (window.innerHeight) {
          this_.maxHeight = window.innerHeight
        } else if (document.body && document.body.clientHeight) {
          this_.maxHeight = document.body.clientHeight
        }
        this_.maxHeight = this_.maxHeight - item
      }, 10)
    },
    //Loading 加载中
    openFullScreen() {
      this.fullscreenLoading = true
    },
    handleSizeChange: function(size) {
      //每页下拉显示数据
      this.pagination.pageSize = size
      this.search()
    },
    handleCurrentChange: function(currentPage) {
      //点击第几页
      this.pagination.page = currentPage
      this.search()
    },
    //回车查询
    searchEnterFun: function(e) {
      var keyCode = window.event ? e.keyCode : e.which
      if (keyCode == 13) {
        this.search('find')
      }
    },
    // 查询
    search(str) {
      const this_ = this
      if (str == 'find') {
        this_.pagination.page = 1
      }
      let querys = [] //查询条件
      let queryFilter = {}
      let pageBean = {pageBean: this_.pagination}
      let beginDate = '' //开始时间
      let endDate = '' //结束时间
      let group = 'main' //判断条件
      if (this_.tableData) {
        querys = [
          {
            property: 'bt.subject_',
            value: this_.tableData,
            group: 'main',
            operation: 'LIKE',
            relation: 'OR'
          },
          {
            property: 'bt.proc_inst_id_',
            value: this_.tableData,
            group: 'main',
            operation: 'LIKE',
            relation: 'OR'
          },
          {
            property: 'bt.proc_def_name_',
            value: this_.tableData,
            group: 'main',
            operation: 'LIKE',
            relation: 'OR'
          },
          {
            property: 'bt.name_',
            value: this_.tableData,
            group: 'main',
            operation: 'LIKE',
            relation: 'OR'
          }
        ]
        let temp = querys[0]
        for (let index = 1; index < 7; index++) {
          let query = JSON.parse(JSON.stringify(temp))
          query.property = 'prop' + index
          querys.push(query)
        }
      }
      if (this_.currentTree) {
        querys.push({
          property: 'bt.type_id_',
          value: this.currentTree,
          group: 'typeId',
          operation: 'IN',
          relation: 'AND'
        })
      }
      if (this_.date) {
        beginDate = utils.formatDate(this_.date[0].getTime())
        endDate = utils.formatDate(this_.date[1].getTime())
        querys.push({
          property: 'bt.create_time_',
          value: [beginDate, endDate],
          group: 'time',
          operation: 'BETWEEN',
          relation: 'AND'
        })
      }
      queryFilter = {pageBean: this_.pagination, querys, sorter: this_.sorter}
      this_.openFullScreen()
      let team = {}
      team.key = this_.data.type
      if (this_.data.type == 'user') {
        team.val = this_.data.typeValue.id
      }
      if (this_.data.type == 'org') {
        team.val = this_.data.typeValue.id
      }
      if (this_.data.type == 'post') {
        team.val = this_.data.typeValue.id
      }
      if (this_.data.type == 'role') {
        team.val = this_.data.typeValue.id
      }
      req
        .post(
          window.context.bpmRunTime +
            '/runtime/task/v1/getTodoListByTeam?team=' +
            Base64.encode(JSON.stringify(team)),
          queryFilter
        )
        .then(response => {
          if (response.data) {
            this_.rows = response.data.rows
            this_.pagination = {
              page: response.data.page,
              pageSize: response.data.pageSize,
              total: response.data.total
            }
          }
          //页面加载调用tudo.js里面的分页方法
          this_.fullscreenLoading = false
        })
        .catch(() => {
          this_.fullscreenLoading = false
        })
    },
    //重置
    reset() {
      this.tableData = ''
      this.date = ''
      this.search('find')
    },
    //子组件传值父组件(待办分类查询)
    getCurrent(data) {
      const this_ = this
      if (data.id == 6) {
        this_.currentTree = ''
        this_.openFullScreen()
        let pageBean = {pageBean: this_.pagination}
        let team = {}
        team.key = this_.data.type
        if (this_.data.type == 'user') {
          team.val = this_.data.typeValue.id
        }
        if (this_.data.type == 'org') {
          team.val = this_.data.typeValue.id
        }
        if (this_.data.type == 'post') {
          team.val = this_.data.typeValue.id
        }
        if (this_.data.type == 'role') {
          team.val = this_.data.typeValue.id
        }
        req
          .post(
            window.context.bpmRunTime +
              '/runtime/task/v1/getTodoListByTeam?team=' +
              Base64.encode(JSON.stringify(team)),
            pageBean
          )
          .then(response => {
            if (response.data) {
              this_.rows = response.data.rows
              this_.pagination = {
                page: response.data.page,
                pageSize: response.data.pageSize,
                total: response.data.total
              }
            }
            //页面加载调用tudo.js里面的分页方法
            this_.fullscreenLoading = false
          })
          .catch(() => {
            this_.fullscreenLoading = false
          })
      } else {
        let ids = []
        this_.getFlowTrees(data, ids)
        this_.currentTree = ids.join(',')
        this_.search('find')
      }
    },
    getFlowTrees(data, ids) {
      ids.push(data.id)
      let arr = data.children
      for (var i = 0; i < arr.length; i++) {
        this.getFlowTrees(arr[i], ids)
      }
    },
    formatConfListToObj(tempList) {
      let editConfObj = {}
      tempList.forEach(c => {
        let key = c.name
        editConfObj[key] = c
      })
      this.$set(this, 'defaultFiledShowConf', editConfObj)
    },
    loadCount() {
      const this_ = this
      let team = {}
      team.key = this_.data.type
      if (this_.data.type == 'user') {
        team.val = this_.data.typeValue.id
      }
      if (this_.data.type == 'org') {
        team.val = this_.data.typeValue.id
      }
      if (this_.data.type == 'post') {
        team.val = this_.data.typeValue.id
      }
      if (this_.data.type == 'role') {
        team.val = this_.data.typeValue.id
      }
      return flow.getTodoCountByTeam(Base64.encode(JSON.stringify(team)))
    },
    computeTime(deadline) {
      if (deadline) {
        let time = new Date(deadline).getTime()
        let nowTime = new Date().getTime()
        let day = (time - nowTime) / 86400000
        if (day > 0) return Math.ceil(day) + '天'
        else return '延期' + Math.ceil(Math.abs(day)) + '天'
      }
      return ''
    },
    computeColor(deadline) {
      if (deadline) {
        let time = new Date(deadline).getTime()
        let nowTime = new Date().getTime()
        let day = (time - nowTime) / 86400000
        if (day > 0) return {color: 'green'}
        else {
          if (Math.ceil(Math.abs(day)) >= 3) return {color: 'red'}
          else return {color: 'yellow'}
        }
      }
      return {}
    },
    createdSearch() {
      const this_ = this
      let querys = []
      let pageBean = {
        pageBean: {page: '1', pageSize: '10', showTotal: 'true'},
        querys: querys
      }
      let team = {}
      team.key = this_.data.type
      if (this_.data.type == 'user') {
        team.val = this_.data.typeValue.id
      }
      if (this_.data.type == 'org') {
        team.val = this_.data.typeValue.id
      }
      if (this_.data.type == 'post') {
        team.val = this_.data.typeValue.id
      }
      if (this_.data.type == 'role') {
        team.val = this_.data.typeValue.id
      }
      //初次加载默认pageBean
      req
        .post(
          window.context.bpmRunTime +
            '/runtime/task/v1/getTodoListByTeam?team=' +
            Base64.encode(JSON.stringify(team)),
          pageBean
        )
        .then(response => {
          if (response.data) {
            this_.rows = response.data.rows
            this_.pagination = {
              page: response.data.page,
              pageSize: response.data.pageSize,
              total: response.data.total
            }
          }
          //页面加载调用tudo.js里面的分页方法
          this_.fullscreenLoading = false
        })
        .catch(() => {
          this_.fullscreenLoading = false
        })
    }
  },
  created() {
    const this_ = this
    if (JSON.stringify(this_.data) == '{}') {
      return '请选择查询对象'
    }
    //this_.setMaxHeight(300);//动态计算列表高度
    this_.$http
      .get(
        window.context.portal +
          '/sys/sysProperties/v1/getDecryptByAlias?alias=taskListFiledConf'
      )
      .then(function(resp) {
        let tempConf = {}
        if (resp.data) {
          tempConf = JSON.parse(resp.data.value)
        } else {
          tempConf = this_.defaultFiledShowConfList
        }
        this_.formatConfListToObj(tempConf)
      })
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/element-variables.scss';
.el-container {
  background-color: #fff;
}
.el-row {
  margin-bottom: 20px;
}
.el-header {
  border-bottom: 1.5px solid #ededed;
}
.top-title {
  line-height: 58px;
  margin-left: 20px;
  font-size: 16px;
  color: #a2a2a2;
}
/deep/.el-tree {
  position: relative;
  cursor: default;
  background: #fff;
  color: #303133;
  font-size: 13px;
}
.query-box {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-bottom: 20px;
    &_right{
    display: flex;
  }
}
</style>
