<template>
  <div class="page">
      <el-form size="small" :inline="true" class="query-form" ref="searchForm" :model="searchForm" @keyup.enter.native="refreshList()" @submit.native.prevent>
            <!-- 搜索框-->
		     <el-form-item label="标题" prop="title">
                <el-input size="small" v-model="searchForm.title" placeholder="标题" clearable></el-input>
		     </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select size="small" v-model="searchForm.type" placeholder="类型" clearable>
            <el-option
              v-for="item in $dictUtils.getDictList('oa_notify_type')"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布者" prop="createName">
          <UserSelect :limit='1' :userName="searchForm.createName" @getValue='(value, label) => {searchForm.createName = label}'></UserSelect>
        </el-form-item>
        <el-form-item label="创建时间" prop="createDates">
          <el-date-picker
            placement="bottom-start"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="searchForm.createDates"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
          <el-form-item>
            <el-button  type="primary" @click="refreshList()" size="small" icon="el-icon-search">查询</el-button>
            <el-button @click="resetSearch()" size="small" icon="el-icon-refresh-right">重置</el-button>
          </el-form-item>
      </el-form>
     <div class="bg-white top">
      <vxe-toolbar :refresh="{query: refreshList}" custom>
        <template #buttons>
          <el-button v-if="hasPermission('notify:add')" type="primary" size="small" icon="el-icon-plus" @click="start()">新建</el-button>
<!--          <el-button v-if="hasPermission('notify:del')" type="danger"   size="small" icon="el-icon-delete" @click="del()" :disabled="$refs.notifyTable && $refs.notifyTable.getCheckboxRecords().length === 0" plain>删除</el-button>-->
        </template>
      </vxe-toolbar>
     <div style="height: calc(100% - 80px);">
        <vxe-table
            border="inner"
            auto-resize
            resizable
            height="auto"
            :loading="loading"
            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="dataList"
            :checkbox-config="{}">
            <vxe-column type="seq" width="60" title="序号"></vxe-column>
<!--            <vxe-column type="checkbox"  width="40px"></vxe-column>-->
            <vxe-column min-width="180px" title="标题" field="title" align="center" >
              <template slot-scope="scope">
                <el-link  type="primary" :underline="false" v-if="hasPermission('notify:view')"  @click="view(scope.row.id)">{{scope.row.title}}</el-link>
                <span v-else>{{scope.row.title}}</span>
<!--                <span >{{scope.row.title}}</span>-->
              </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="readNum" align="center" >
               <template slot-scope="scope">
                 <span v-if="scope.row.status === '5'">
                   {{commonJS.isNotEmpty(scope.row.readNum) && commonJS.isNotEmpty(scope.row.unReadNum) ? scope.row.readNum + " / " + (parseInt(scope.row.readNum) + parseInt(scope.row.unReadNum)) : '0 / 0'}}
                 </span>
                 <span v-else>
                   通告未发起
                 </span>
              </template>
            </vxe-column>
             <vxe-column  min-width="100px"title="发布者" field="createBy.name" align="center" ></vxe-column>
            <vxe-column min-width="180px" title="通告时间" field="beginDate" align="center" >
              <template slot-scope="scope">
                 <span v-if="scope.row.notifyType === '0'">
                   {{commonJS.isNotEmpty(scope.row.beginDate) && commonJS.isNotEmpty(scope.row.endDate)
                   ?
                   moment(scope.row.beginDate).format('YYYY-MM-DD') + " 至 " + moment(scope.row.endDate).format('YYYY-MM-DD')
                   :
                   ''}}
                 </span>
                <span v-else-if="scope.row.notifyType === '1'">
                   长期通告
                 </span>
              </template>
            </vxe-column>
          <vxe-column  min-width="180px"title="创建时间" field="createDate" align="center" ></vxe-column>
          <vxe-column  width="100px"align="center" fixed="right" title="关闭状态" field="isClose" >
            <template slot-scope="scope">
              <span v-if="scope.row.isClose === '0'" style="color: #67C23A"> 未关闭 </span>
              <span v-else-if="scope.row.isClose === '1'" style="color: #F56C6C"> 已关闭 </span>
            </template>
          </vxe-column>
            <vxe-column  width="100px"align="center" fixed="right" title="状态" field="status" >
              <template slot-scope="scope">
                <el-button  type="text" @click="detail(scope.row)" effect="dark" size="mini"
                            :type="$dictUtils.getDictLabel('cw_status_flag', scope.row.status, '-')">
                  {{$dictUtils.getDictLabel("cw_status", scope.row.status, '-')}}
                </el-button>
              </template>
            </vxe-column>

            <vxe-column title="操作" width="120px" fixed="right" align="center">
                <template  slot-scope="scope">

                  <el-button v-if="hasPermission('notify:edit')&&(scope.row.status === '1' || scope.row.status === '3')&&scope.row.createBy.id === $store.state.user.id" type="text" size="small" @click="push(scope.row)">修改</el-button>
                  <el-button v-else-if="(scope.row.status === '1' || scope.row.status === '3' || scope.row.status === '5')&&isAdmin" type="text" size="small" @click="edit(scope.row.id)">修改</el-button>
                  <el-button v-if="scope.row.status === '5' && scope.row.isClose === '0' && (scope.row.createBy.id === $store.state.user.id || isAdmin)" type="text" size="small" @click="close(scope.row.id)">关闭</el-button>

                  <el-button v-if="hasPermission('notify:edit')&&(scope.row.status === '2')&&scope.row.createBy.id === $store.state.user.id" type="text" size="small" @click="reback(scope.row)">撤回</el-button>
                  <el-button v-if="hasPermission('notify:del')&&(scope.row.status === '1' || scope.row.status === '3')&&(scope.row.createBy.id === $store.state.user.id || isAdmin)"  type="text" size="small" @click="del(scope.row.id)">删除</el-button>
                </template>
            </vxe-column>
        </vxe-table>
        <vxe-pager
          background
          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>
        <!-- 弹窗, 新增 / 修改 -->
    <NotifyForm  ref="notifyForm" @refreshDataList="refreshList"></NotifyForm>
  </div>
  </div>
</template>

<script>
  import NotifyForm from './NotifyForm'
  import NotifyService from '@/api/notify/NotifyService'
  import pick from 'lodash.pick'
  import TaskService from '@/api/flowable/TaskService'
  import ProcessService from '@/api/flowable/ProcessService'
  import UserService from '@/api/sys/UserService'
  import UserSelect from '@/components/userSelect'
  export default {
    data () {
      return {
        searchForm: {
          title: '',
          type: '',
          createName: '',
          createDates: []
        },
        dataList: [],
        tablePage: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          orders: []
        },
        loading: false,
        processDefinitionAuditId: '',
        procDefAuditKey: '',
        isAdmin: false
      }
    },
    components: {
      NotifyForm,
      UserSelect
    },
    notifyService: null,
    taskService: null,
    processService: null,
    userService: null,
    created () {
      this.notifyService = new NotifyService()
      this.taskService = new TaskService()
      this.processService = new ProcessService()
      this.userService = new UserService()
    },
    activated () {
      this.refreshList()
    },
    computed: {
      userName () {
        return JSON.parse(localStorage.getItem('user')).name
      },
      user () {
        this.createName = JSON.parse(localStorage.getItem('user')).name
        return JSON.parse(localStorage.getItem('user'))
      }
    },
    methods: {
      // 获取数据列表
      refreshList () {
        this.loading = true
        this.notifyService.list({
          '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.checkIsAdmin()
          this.processService.getByName('发起通知').then(({data}) => {
            if (!this.commonJS.isEmpty(data.id)) {
              this.processDefinitionAuditId = data.id
              this.procDefAuditKey = data.key
            }
          })
        })
      },
      // 查询当前用户是否是管理员用户
      checkIsAdmin () {
        this.userService.is().then(({data}) => {
          this.isAdmin = data
        })
      },
  // 当前页
      currentChangeHandle ({ currentPage, pageSize }) {
        this.tablePage.currentPage = currentPage
        this.tablePage.pageSize = pageSize
        this.refreshList()
      },
      // 排序
      sortChangeHandle (column) {
        this.tablePage.orders = []
        if (column.order != null) {
          this.tablePage.orders.push({column: this.$utils.toLine(column.property), asc: column.order === 'asc'})
        }
        this.refreshList()
      },
      close (id) {
        this.$confirm(`关闭通告后，接收人将无法查阅，确定关闭吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          this.notifyService.close(id).then(({data}) => {
            this.$message.success(data)
            this.refreshList()
            this.loading = false
          })
        })
      },
      // 新增
      add () {
        this.$refs.notifyForm.init('add', '')
      },
            // 修改
      edit (id) {
        id = id || this.$refs.notifyTable.getCheckboxRecords().map(item => {
          return item.id
        })[0]
        this.$refs.notifyForm.init('edit', id)
      },
      // 查看
      view (id) {
        this.$refs.notifyForm.init('view', id)
      },
      // 删除
      del (id) {
        let ids = id || this.$refs.notifyTable.getCheckboxRecords().map(item => {
          return item.id
        }).join(',')
        this.$confirm(`确定删除所选项吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          this.notifyService.delete(ids).then(({data}) => {
            this.$message.success(data)
            this.refreshList()
            this.loading = false
          })
        })
      },
      resetSearch () {
        this.$refs.searchForm.resetFields()
        this.refreshList()
      },
      start () {
        // 读取流程表单
        let tabTitle = `发起流程【发起通知】`
        let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [发起通知]`
        this.taskService.getTaskDef({ procDefId: this.processDefinitionAuditId,
          status: 'startAndHold'}).then((data) => {
            this.$router.push({
              path: '/flowable/task/TaskForm',
              query: {
                ...pick(data.data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
                procDefId: this.processDefinitionAuditId,
                procDefKey: this.procDefAuditKey,
                status: 'startAndHold',
                title: tabTitle,
                formType: data.data.formType,
                formUrl: data.data.formUrl,
                formTitle: processTitle,
                businessId: 'false',
                isShow: false,
                routePath: '/notify/NotifyList'
              }
            })
          })
      },
      // 发起项目登记
      push (row) {
        // 读取流程表单
        let title = `发起流程【发起通知】`
        let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了[发起通知]`
        let status = 'startAndHold'
        if (row.status === '3') {
          status = 'startAndClose'
        } else if (row.status === '4') {
          status = 'reapplyFlag'
        }
        this.taskService.getTaskDef({ procDefId: this.processDefinitionAuditId,
          businessId: row.id,
          businessTable: 'plugin_notify'}).then((data) => {
            this.$router.push({
              path: '/flowable/task/TaskForm',
              query: {
                ...pick(data.data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
                procDefId: this.processDefinitionAuditId,
                procDefKey: this.procDefAuditKey,
                title: title,
                formType: data.data.formType,
                formUrl: data.data.formUrl,
                formTitle: processTitle,
                businessTable: 'plugin_notify',
                businessId: row.id,
                isShow: 'false',
                status: status,
                routePath: '/notify/NotifyList'
              }
            })
          })
      },
      // 查看项目登记流程结果
      detail (row) {
        if (row.status !== '0' && row.status !== '1') {
          // eslint-disable-next-line eqeqeq
          this.taskService.getTaskDef({
            procInsId: row.procInsId,
            procDefId: this.processDefinitionAuditId
          }).then(({data}) => {
            this.$router.push({
              path: '/flowable/task/TaskFormDetail',
              query: {
                ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
                isShow: 'false',
                readOnly: true,
                title: '发起通知' + '流程详情',
                formTitle: '发起通知' + '流程详情',
                businessId: row.id,
                status: 'reback'
              }
            })
          })
        }
      },
      // 撤回项目登记
      reback (row) {
        this.$confirm(`确定要撤回该申请吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await this.notifyService.queryById(row.id).then(({data}) => {
            if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
              this.$message.error('数据已发生改变或不存在，请刷新数据')
              this.refreshList()
            } else {
              this.processService.revokeProcIns(row.procInsId).then(({data}) => {
                let form = {status: '3', id: row.id}
                this.notifyService.updateStatusById(form)
                this.$message.success(data)
                this.refreshList()
              })
            }
          })
        })
      }
    }
  }
</script>
<style>
  .box {
    width: 400px
  }
  .box .top {
    text-align: center;
  }
  .box .item {
    margin: 4px;
  }
</style>
