<template>
  <div class="page">
    <el-form  :inline="true" class="query-form m-b-10" v-if="searchVisible" ref="searchForm" :model="searchForm" @keyup.enter.native="refreshList()" @submit.native.prevent>
      <!-- 搜索框-->
      <el-form-item label="项目名称" prop="projectName">
        <el-input  v-model="searchForm.projectName" placeholder="请输入项目名称" clearable></el-input>
      </el-form-item>
      <!--<el-form-item label="项目编号" prop="projectNumber">
        <el-input size="small" v-model="searchForm.projectNumber" placeholder="请输入项目编号" clearable></el-input>
      </el-form-item>
      <el-form-item label="项目经理" prop="projectMasterName">
        <UserSelect :limit='1' :userName="searchForm.projectMasterName" @getValue='(value, label) => {searchForm.projectMasterName = 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 label="结束时间" prop="endDates">
        <el-date-picker
          placement="bottom-start"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          v-model="searchForm.endDates"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>-->

      <el-form-item>
        <el-button type="primary" @click="refreshList()" icon="el-icon-search">查询</el-button>
        <el-button @click="resetSearch()" icon="el-icon-refresh-right">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="jp-table top" style="">
      <vxe-toolbar :refresh="{query: refreshList}" ref="toolbarRef" export custom>
        <template #buttons>
          <el-button type="primary" icon="el-icon-plus" @click="add()">新建</el-button>
        </template>
		  <template #tools>
			  <vxe-button
				  text
				  type="primary"
				  :title="searchVisible ? '收起检索' : '展开检索'"
				  icon="vxe-icon-search"
				  class="tool-btn"
				  @click="searchVisible = !searchVisible"
			  ></vxe-button>
		  </template>
      </vxe-toolbar>
      <div style="height: calc(100% - 90px)">
        <vxe-table
          :key="tableKey"
          border="inner"
          auto-resize
          resizable
          height="auto"
          :loading="loading"
          size="small"
          ref="projectTable"
          show-header-overflow
          show-overflow
          highlight-hover-row
          :menu-config="{}"
          @sort-change="sortChangeHandle"
          :sort-config="{remote:true}"
          :export-config="{
                    remote: true,
                    filename: `项目数据${moment(new Date()).format('YYYY-MM-DD')}`,
                    sheetName: `项目数据${moment(new Date()).format('YYYY-MM-DD')}`,
                    exportMethod: exportMethod,
                    types: ['xlsx'],
                    modes: ['current', 'selected', 'all']
                  }"
          :data="dataList"
          :checkbox-config="{}">
          <vxe-column type="seq" width="60" title="序号"></vxe-column>
          <vxe-column type="checkbox" width="40" ></vxe-column>
          <vxe-column min-width="230" align="center" title="项目名称" field="projectName">
            <template #default="scope">
              <el-link  type="primary" :underline="false" v-if="hasPermission('manHourManagement:view')" @click="view(scope.row.id)">{{scope.row.projectName}}</el-link>
              <el-link  type="primary" :underline="false" v-else-if="hasPermission('manHourManagement:view')"  @click="view(scope.row.id,)">{{scope.row.projectName}}</el-link>
              <span v-else>{{scope.row.projectName}}</span>
            </template>
          </vxe-column>
          <vxe-column min-width="160" align="center" title="项目编号" field="projectNumber"></vxe-column>
          <vxe-column min-width="160" align="center" title="项目经理" field="projectMasterName"></vxe-column>
          <vxe-column min-width="160" align="center" title="计划开始时间" field="planStartDate"></vxe-column>
          <vxe-column min-width="160" align="center" title="计划结束时间" field="planEndDate"></vxe-column>
          <vxe-column min-width="160" align="center" title="创建人" field="createBy.name"></vxe-column>
          <vxe-column min-width="160" align="center" title="创建时间" field="createTime"></vxe-column>
          <vxe-column min-width="100" align="center" title="确认状态" field="statusStr"></vxe-column>
          <vxe-column title="操作" width="200px" fixed="right" align="center">
            <template  #default="scope">
              <el-button v-if="hasPermission('manHourManagement:edit')&&scope.row.createBy.id === $store.state.user.id&&scope.row.status === '0'" type="text"  @click="edit(scope.row.id)">编辑</el-button>
              <el-button v-if="hasPermission('manHourManagement:edit')&&scope.row.status === '0'" type="text"   @click="isReceivables(scope.row)">确认工时</el-button>
              <el-button v-if="hasPermission('manHourManagement:del')&&scope.row.status === '0'" type="text"    @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>
    </div>
    <ManHourManagementForm ref="manHourManagementForm" @refreshDataList="refreshList"></ManHourManagementForm>
  </div>
</template>

<script>
  import ManHourManagementService from '@/api/cw/projectRecords/ManHourManagementService'
  import processService from '@/api/flowable/ProcessService'
  import ManHourManagementForm from './ManHourManagementForm'
  import userService from '@/api/sys/UserService'
  // import UserSelect from '@/components/userSelect'
  export default {
    data () {
      return {
		searchVisible: true,
        searchForm: {
          projectMasterName: '',
          projectNumber: '',
          projectName: '',
          createDates: [],
          endDates: []
        },
        dataList: [],
        tablePage: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          orders: []
        },
        tableKey: '',
        loading: false,
        processDefinitionAuditId: '',
        procDefAuditKey: '',
        isAdmin: false
      }
    },
    manHourManagementService: null,
    created () {
      this.manHourManagementService = new ManHourManagementService()
    },
    components: {
      ManHourManagementForm,
      // UserSelect
    },
    computed: {
      userName () {
        return JSON.parse(localStorage.getItem('user')).name
      },
      user () {
        this.createName = JSON.parse(localStorage.getItem('user')).name
        return JSON.parse(localStorage.getItem('user'))
      }
    },
    mounted () {
		this.$nextTick(() => {
			//将表格和工具栏进行关联
			const $table = this.$refs.projectTable;
			const $toolbar = this.$refs.toolbarRef;
			$table.connect($toolbar);
		})
      this.refreshList()
    },
    activated () {
      this.refreshList()
    },
    methods: {
      // 新增
      add () {
        this.$refs.manHourManagementForm.init('add', '')
      },
      // 修改
      edit (id) {
        this.$refs.manHourManagementForm.init('edit', id)
      },
      // 查看
      view (id) {
        this.$refs.manHourManagementForm.init('view', id)
      },
      // 查询当前用户是否是管理员用户
      checkIsAdmin () {
        userService.is().then((data) => {
          this.isAdmin = data
        })
      },
      // 获取数据列表
      refreshList () {
        this.loading = true
        this.manHourManagementService.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.tableKey = Math.random()
          this.loading = false
        })
        this.checkIsAdmin()
        processService.getByName('财务-项目登记').then((data) => {
          if (!this.commonJS.isEmpty(data.id)) {
            this.processDefinitionAuditId = data.id
            this.procDefAuditKey = data.key
          }
        })
      },
      // 当前页
      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()
      },
      isReceivables (row) {
        this.$confirm(`是否确认工时?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.manHourManagementService.updateStatus(row.id).then((data) => {
            this.$message.success(data)
            this.refreshList()
          })
        })
      },
      // 删除
      del (id) {
        let ids = id || this.$refs.projectTable.getCheckboxRecords().map(item => {
          return item.id
        }).join(',')
        this.$confirm(`确定删除所选项吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          this.manHourManagementService.delete(ids).then((data) => {
            this.$message.success(data)
            this.refreshList()
            this.loading = false
          })
        })
      },
      resetSearch () {
        this.$refs.searchForm.resetFields()
        this.refreshList()
      },
      // 自定义服务端导出
      exportMethod ({ options }) {
        // 传给服务端的参数
        const params = {
          'current': this.tablePage.currentPage,
          'size': this.tablePage.pageSize,
          'orders': this.tablePage.orders,
          ...this.searchForm,
          filename: options.filename,
          sheetName: options.sheetName,
          isHeader: options.isHeader,
          original: options.original,
          mode: options.mode,
          selectIds: options.mode === 'selected' ? options.map(item => item.id) : [],
          exportFields: options.columns.map(column => column.property)
        }
        return this.projectRecordsService.exportFile(params).then((res) => {
          // 将二进制流文件写入excel表，以下为重要步骤
          this.$utils.downloadExcel(res, options.filename)
        }).catch(function (err) {
          if (err.response) {
            console.log(err.response)
          }
        })
      }
    }
  }
</script>
