<template>
  <div>
    <el-container style="height: calc(100vh - 105px)">
      <el-header style="padding:0px;height: 50%;line-height: 20px" >
        <el-container direction="horizontal"style="height: 100%;">
        <el-main style="height: 100%;width: 50%;padding: 0 5px 0 0;" >
          <div class="page" style="height: calc(100% - 0px);">
            <div class="top bg-white" style="height: calc(100% - 10px);border: 1px solid #c8ced4;padding-top: 15px">
              <div style="height: 18px;">
                <span>我的待办</span>
                <el-badge class="mark" v-if="tablePage.total !== 0" :value="tablePage.total" :max="99"style="line-height: 0"/>
                <div style="float:right;align-items:center;display:flex;height: 18px">
                  <el-button type="text" style="float:right" @click="resetSearch()">刷新</el-button>
                  <el-button type="text" style="float:right" @click="toPendingList()">更多>></el-button>
                </div>
              </div>
              <div style="height: calc(100% - 55px);margin-top: 5px">
                <vxe-table
                  border="inner"
                  auto-resize
                  resizable
                  height="auto"
                  :loading="loading"
                  size="small"
                  ref="todoTable"
                  show-header-overflow
                  show-overflow
                  highlight-hover-row
                  :menu-config="{}"
                  :print-config="{}"
                  :import-config="{}"
                  :export-config="{}"
                  :data="dataList"
                  header-align="center"
                  :checkbox-config="{}">
                  <!--<vxe-column type="seq" width="60" title="序号"></vxe-column>
                  <vxe-column type="checkbox"  width="40px"></vxe-column>-->
                  <vxe-column title="实例标题" field="vars.title">
                    <template slot-scope="scope">
                      <el-link type="primary" :underline="false" v-if="scope.row.status === 'todo'"
                               @click="todo(scope.row)">{{scope.row.vars.title}}
                      </el-link>
                      <span v-else>{{scope.row.vars.title}}</span>
                    </template>
                  </vxe-column>
                  <vxe-column title="流程名称" field="processDefinitionName"></vxe-column>
                  <vxe-column title="当前环节" field="task.name">
                    <template slot-scope="scope">
                      <el-tag>{{scope.row.task.name}}</el-tag>
                    </template>
                  </vxe-column>
                  <vxe-column title="流程发起人" field="vars.userName"></vxe-column>
                  <vxe-column
                    field="task.createTime"
                    title="创建时间">
                  </vxe-column>
                  <vxe-column title="操作" width="100px" fixed="right" align="center">
                    <template slot-scope="scope">
                      <el-button type="text" size="small" @click="todo(scope.row)">办理</el-button>
                      <el-button  type="text" size="small" @click="trace(scope.row)">进度</el-button>
                    </template>
                  </vxe-column>
                </vxe-table>
                <vxe-pager
                  background
                  style="margin-top: 5px"
                  size="small"
                  :current-page="tablePage.currentPage"
                  :page-size="tablePage.pageSize"
                  :total="tablePage.total"
                  :page-sizes="[10, 20, 100, 1000, {label: '全量数据', value: 1000000}]"
                  :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
                  @page-change="currentChangeHandle">
                </vxe-pager>
              </div>
            </div>
            <el-dialog
              title="查看进度"
              :close-on-click-modal="true"
              :visible.sync="visible"
              v-dialogDrag
              width="70%"
              height="600px">
              <flow-chart ref="preview" :processInstanceId="processInstanceId"></flow-chart>
            </el-dialog>
            <user-select ref="userSelect" :limit="1" @doSubmit="selectUsersToTransferTask"></user-select>
          </div>
        </el-main>
        <el-main style="height: 100%;width: 50%;padding: 0 0 0 5px;" >
          <div class="page" style="height: calc(100% - 0px);">
            <div class="top bg-white" style="height: calc(100% - 10px);border: 1px solid #c8ced4;padding-top: 15px">
              <div style="height: 18px;" >
                <span>我的通知</span>
                <el-badge class="mark" v-if="noticePageList.total !== 0" :value="noticePageList.total" :max="99" style="line-height: 0"/>
                <div style="float:right;align-items:center;display:flex;height: 18px">
                  <el-button type="text" style="float:right" @click="toNoticeList()">更多>></el-button>
                </div>
              </div>
              <div style="height: calc(100% - 55px);margin-top: 5px">
                <vxe-table
                  border="inner"
                  auto-resize
                  resizable
                  height="auto"
                  :loading="loading3"
                  size="small"
                  ref="noticetable"
                  show-header-overflow
                  show-overflow
                  highlight-hover-row
                  :menu-config="{}"
                  :print-config="{}"
                  :import-config="{}"
                  :export-config="{}"
                  @sort-change="sortChangeHandle"
                  :sort-config="{remote:true}"
                  :data="dataNoticeList"
                  :checkbox-config="{}">
                  <vxe-column title="实例标题" field="title">
                    <template slot-scope="scope">
                      <el-link type="primary" :underline="false"
                               @click="todoPage(scope.row)">{{scope.row.title}}
                      </el-link>
                    </template>
                  </vxe-column>
                  <vxe-column title="流程名称" field="taskName"></vxe-column>
                  <vxe-column title="流程发起人" field="createUser"></vxe-column>
                  <vxe-column
                    field="createTime"
                    title="创建时间">
                  </vxe-column>
                </vxe-table>
                <vxe-pager
                  background
                  size="small"
                  style="margin-top: 5px"
                  :current-page="noticePageList.currentPage"
                  :page-size="noticePageList.pageSize"
                  :total="noticePageList.total"
                  :page-sizes="[10, 20, 100, 1000, {label: '全量数据', value: 1000000}]"
                  :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
                  @page-change="noticePageListChangeHandle">
                </vxe-pager>
              </div>
              <!-- 弹窗, 新增 / 修改 -->
              <NotifyForm  ref="notifyForm" @refreshDataList="refreshList"></NotifyForm>
            </div>
          </div>
        </el-main>
        </el-container>
      </el-header>
      <el-header style="padding:0px;height: 50%;line-height: 20px">
        <el-container direction="horizontal"style="height: 100%;">
          <el-main style="height: 100%;width: 50%;padding: 0 5px 0 0;" >
            <div class="page" style="calc(100% - 0px);">
          <div class="top bg-white"style="height: calc(100% - 10px);border: 1px solid #c8ced4;padding-top: 15px">
            <div style="height: 18px;" >
              <span>公告</span>
              <el-badge v-if="noticePage.total !== 0" class="mark" :value="noticePage.total" :max="99" style="line-height: 0"/>
              <div style="float:right;align-items:center;display:flex;height: 18px">
                <el-button type="text" style="float:right" @click="resetSearch()">刷新</el-button>
                <el-button type="text" style="float:right" @click="toNotice()">更多>></el-button>
              </div>
            </div>
            <div style="height: calc(100% - 55px);margin-top: 5px">
              <vxe-table
                border="inner"
                auto-resize
                resizable
                height="auto"
                :loading="loading2"
                size="small"
                ref="notifyTable"
                show-header-overflow
                show-overflow
                highlight-hover-row
                :menu-config="{}"
                :print-config="{}"
                :import-config="{}"
                :export-config="{}"
                @sort-change="sortChangeHandle"
                :sort-config="{remote:true}"
                :data="dataLists"
                :checkbox-config="{}">
                <!--<vxe-column type="seq" width="60" title="序号"></vxe-column>
                <vxe-column type="checkbox"  width="40px"></vxe-column>-->
                <vxe-column min-width="150px" title="标题" field="title" align="center">
                  <template slot-scope="scope">
                    <el-link  type="primary" :underline="false" @click="view(scope.row.id)">{{scope.row.title}}</el-link>
                  </template>
                </vxe-column>
                <vxe-column min-width="100px" title="类型" field="type" align="center">
                  <template slot-scope="scope">
                    {{ $dictUtils.getDictLabel("oa_notify_type", scope.row.type, '-') }}
                  </template>
                </vxe-column>

                <vxe-column min-width="100px" title="查阅状态" field="status" align="center">
                  <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.readFlag === '1'"> {{ $dictUtils.getDictLabel("oa_notify_read", scope.row.readFlag, '-') }}</el-tag>
                    <el-tag type="danger" v-if="scope.row.readFlag === '0'"> {{ $dictUtils.getDictLabel("oa_notify_read", scope.row.readFlag, '-') }}</el-tag>
                  </template>
                </vxe-column>
                <vxe-column min-width="100px" title="发布者" field="createBy.name" align="center"></vxe-column>
                <vxe-column title="操作" width="50px" fixed="right" align="center">
                  <template  slot-scope="scope">
                    <el-button  type="text" size="mini" @click="view(scope.row.id)">查看</el-button>
                  </template>
                </vxe-column>
              </vxe-table>
              <vxe-pager
                background
                size="small"
                style="margin-top: 5px"
                :current-page="noticePage.currentPage"
                :page-size="noticePage.pageSize"
                :total="noticePage.total"
                :page-sizes="[10, 20, 100, 1000, {label: '全量数据', value: 1000000}]"
                :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
                @page-change="noticeChangeHandle">
              </vxe-pager>
            </div>
            <!-- 弹窗, 新增 / 修改 -->
            <NotifyForm  ref="notifyForm" @refreshDataList="refreshList"></NotifyForm>
          </div>
        </div>
          </el-main>
          <el-main style="height: 100%;width: 50%;padding: 0 0 0 5px;" >
            <div class="page" style="calc(100% - 0px);">
              <div class="top bg-white"style="height: calc(100% - 10px);border: 1px solid #c8ced4;padding-top: 15px">
                <el-empty></el-empty>
              </div>
            </div>
          </el-main>
        </el-container>
      </el-header>
    </el-container>
    <UpdatePassword ref="updatePassword"></UpdatePassword>
    <WareHouseHistoryPopup ref="wareHouseHistoryPopup"></WareHouseHistoryPopup>
  </div>
</template>

<script>
  import pick from 'lodash.pick'
  import UserSelect from '@/components/userSelect/UserSelectDialog'
  import TaskService from '@/api/flowable/TaskService'
  // import NotifyForm from './NotifyForm'
  import NotifyForm from '@/views/modules/notify/NotifyForm'
  import NotifyService from '@/api/notify/NotifyService'
  import NoticeService from '@/api/flowable/NoticeService'
  import UserService from '@/api/sys/UserService'
  import UpdatePassword from '@/views/layout/UpdatePassword'
  import WareHouseHistoryPopup from '../../../materialManagement/wareHouseSummary/WareHouseHistoryPopup'
  export default {
    data () {
      return {
        searchForm: {
          beginDate: '',
          endDate: ''
        },
        dataList: [],
        dataLists: [],
        dataNoticeList: [],
        tablePage: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          orders: []
        },
        noticePage: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          orders: []
        },
        noticePageList: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          orders: []
        },
        loading: false,
        loading2: false,
        loading3: false,
        visible: false,
        currentTask: null,
        processInstanceId: '',
        timer: null
        // pickerOptions: {
        //   shortcuts: [{
        //     text: '最近一周',
        //     onClick (picker) {
        //       const end = new Date()
        //       const start = new Date()
        //       start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
        //       picker.$emit('pick', [start, end])
        //     }
        //   }, {
        //     text: '最近一个月',
        //     onClick (picker) {
        //       const end = new Date()
        //       const start = new Date()
        //       start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
        //       picker.$emit('pick', [start, end])
        //     }
        //   }, {
        //     text: '最近三个月',
        //     onClick (picker) {
        //       const end = new Date()
        //       const start = new Date()
        //       start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
        //       picker.$emit('pick', [start, end])
        //     }
        //   }]
        // }
      }
    },
    taskService: null,
    notifyService: null,
    noticeService: null,
    userService: null,
    created () {
      this.taskService = new TaskService()
      this.notifyService = new NotifyService()
      this.noticeService = new NoticeService()
      this.userService = new UserService()
    },
    activated () {
      // 判断是否有签章页面带过来
      if (this.commonJS.isNotEmpty(this.$route.query.signatureUrl)) {
        this.$confirm(`确定要前往签章页面吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let _this = this
          const wait = function () {
            return new Promise((resolve, reject) => {
              window.open(_this.$route.query.signatureUrl, '_blank')
              resolve()
            })
          }
          wait().then(() => {
            this.$store.dispatch('tagsView/delView', {fullPath: this.$route.fullPath})
            console.log('前往签章页面，清除本页$router.query')
            this.$router.push({query: {}})
          })
        }).catch(() => {
          this.$store.dispatch('tagsView/delView', {fullPath: this.$route.fullPath})
          this.$router.push({query: {}})
          console.log('取消前往签章页面，清除本页$router.query')
        })
      }
      // 判断当前用户是否为管理员
      this.userService.is().then(({data}) => {
        console.log('是否为管理员', data)
        if (!data) {
          // 如果当前用户不是管理员，则判断是否修改过密码
          this.userService.isUpdatePassword().then(({data}) => {
            console.log('是否修改过密码', data)
            if (!data) {
              // 如果没有修改过密码，则弹出密码修改窗口
              this.$refs.updatePassword.init(true)
            }
          })
        }
      })
      this.refreshList()
    },
    components: {
      WareHouseHistoryPopup,
      UserSelect,
      // FlowChart
      NotifyForm,
      UpdatePassword
    },
    // watch: {
    // },
    mounted () {
      // 页面加载后
      // 1.在执行定时器前先执行一次获取接口数据的操作函数, 否则接口会1秒钟后才调用
      // 2.为了避免退出当前页面后,在其他页面也继续调用接口,退出前需要清除定时器.
      this.queryInfo()
      this.timer = setInterval(() => {
        setTimeout(this.queryInfo, 0)
      }, 60000)
    },
    beforeDestroy () {
      clearInterval(this.timer)
      this.timer = null
    },
    methods: {
      queryInfo () {
        this.refreshList()
      },
      toNotice () {
        this.$router.push('/notify/MyNotifyList')
      },
      toNoticeList () {
        // D:\srq\vue\assess_xg_total_process_master_vue\src\views\modules\flowable\task\NoticePageList.vue
        this.$router.push('/flowable/task/NoticePageList')
      },
      toPendingList () {
        // this.$router.push('./PendingList')
        this.$router.push({
          path: './PendingList',
          query: {
            num: 3
          }
        })
      },
      resetSearch () {
        this.refreshList()
      },
      // 获取数据列表
      refreshList () {
        this.loading = true
        this.loading2 = true
        this.loading3 = true
        this.taskService.todoList({
          'current': this.tablePage.currentPage,
          'size': this.tablePage.pageSize,
          'orders': this.tablePage.orders,
          ...this.searchForm
        }).then(({data}) => {
          this.dataList = data.records
          this.tablePage.total = data.total
          this.loading = false
        })
        this.notifyService.myNotifyList({
          'current': this.noticePage.currentPage,
          'size': this.noticePage.pageSize,
          'orders': this.noticePage.orders,
          isSelf: true,
          isClose: '0',
          ...this.searchForm
        }).then(({data}) => {
          this.dataLists = data.records
          this.noticePage.total = data.total
          this.loading2 = false
        })
        this.noticeService.list({
          'current': this.noticePageList.currentPage,
          'size': this.noticePageList.pageSize,
          'orders': this.noticePageList.orders,
          type: '0',
          ...this.searchForm
        }).then(({data}) => {
          this.dataNoticeList = data.records
          this.noticePageList.total = data.total
          this.loading3 = false
        })
      },
      // 排序
      sortChangeHandle (column) {
        this.noticePage.orders = []
        if (column.order != null) {
          this.noticePage.orders.push({column: this.$utils.toLine(column.property), asc: column.order === 'asc'})
        }
        this.refreshList()
      },
      // 当前页
      currentChangeHandle ({ currentPage, pageSize }) {
        this.tablePage.currentPage = currentPage
        this.tablePage.pageSize = pageSize
        // 刷新
        this.loading = true
        this.taskService.todoList({
          'current': this.tablePage.currentPage,
          'size': this.tablePage.pageSize,
          'orders': this.tablePage.orders,
          ...this.searchForm
        }).then(({data}) => {
          this.dataList = data.records
          this.tablePage.total = data.total
          this.loading = false
        })
        // this.refreshList()
      },
      noticePageListChangeHandle ({ currentPage, pageSize }) {
        this.loading3 = true
        this.noticePageList.currentPage = currentPage
        this.noticePageList.pageSize = pageSize
        this.noticeService.list({
          'current': this.noticePageList.currentPage,
          'size': this.noticePageList.pageSize,
          'orders': this.noticePageList.orders,
          type: '0',
          ...this.searchForm
        }).then(({data}) => {
          this.dataNoticeList = data.records
          this.noticePageList.total = data.total
          this.loading3 = false
        })
        // this.refreshList()
      },
      noticeChangeHandle ({ currentPage, pageSize }) {
        this.loading2 = true
        this.noticePage.currentPage = currentPage
        this.noticePage.pageSize = pageSize
        this.notifyService.list({
          'current': this.noticePage.currentPage,
          'size': this.noticePage.pageSize,
          'orders': this.noticePage.orders,
          isSelf: true,
          isClose: '0',
          ...this.searchForm
        }).then(({data}) => {
          this.dataLists = data.records
          this.noticePage.total = data.total
          this.loading2 = false
        })
        // this.refreshList()
      },
      todo (row) {
        let cUser = false
        if (row.processDefinitionName === '业务提问') {
          cUser = true
        }
        this.taskService.getTaskDef({
          taskId: row.task.id,
          taskName: row.task.name,
          taskDefKey: row.task.taskDefinitionKey,
          procInsId: row.task.processInstanceId,
          procDefId: row.task.processDefinitionId,
          procDefKey: row.task.processDefKey,
          status: row.status
        }).then(({data}) => {
          this.$router.push({
            path: '/flowable/task/TaskForm',
            query: {
              isShow: false,
              formReadOnly: true,
              formTitle: `${row.vars.title}`,
              num: 2,
              cUser: cUser,
              title: `审批【${row.task.name || ''}】`,
              ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title', 'businessId')
            }
          })
        })
      },
      todoPage (row) {
        // console.log('row', row)
        if (row.taskName === '库存提醒') {
          // console.log('测试进来了')
          this.$refs.wareHouseHistoryPopup.init(row.defId)
          this.inputForm = {
            id: row.id
          }
          this.noticeService.stockUpdate(this.inputForm)
          this.resetSearch()
        } else {
          this.inputForm = {
            taskId: '',
            noticeId: ''
          }
          this.taskService.getTaskDef({
            procInsId: row.taskId,
            procDefId: row.defId
          }).then(({data}) => {
            this.inputForm.taskId = row.taskId
            this.inputForm.noticeId = row.noticeName
            this.noticeService.update(this.inputForm)
            this.$router.push({
              path: '/flowable/task/TaskForm',
              query: {
                isShow: false,
                formReadOnly: true,
                formTitle: `${row.title}`,
                num: 2,
                title: `审批【${row.taskName || ''}】`,
                ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title', 'businessId')
              }
            })
          })
        }
      },
      trace (row) {
        this.processInstanceId = row.task.processInstanceId
        this.visible = true
        this.$nextTick(() => {
          this.$refs.preview.init()
        })
      },
      transferTask (row) {
        this.currentTask = row.task
        this.$refs.userSelect.init()
      },
      selectUsersToTransferTask (user) {
        this.taskService.delegate(this.currentTask.id, user[0].id).then(({data}) => {
          this.$message.success(data)
          this.refreshList()
        })
      },
      // 查看
      view (id) {
        this.$refs.notifyForm.init('read', id)
      }
      // resetSearch () {
      //   this.$refs.searchForm.resetFields()
      //   this.$nextTick(() => {
      //     this.refreshList()
      //   })
      // }
    }
  }
</script>

<style scoped>
  /deep/ sup {
    top: -.2em;
  }
</style>
