<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="project">
        <el-input size="small" v-model="searchForm.project" placeholder="请输入报销项目" clearable>
          <el-button icon="el-icon-search" slot="append" @click="openProgramPageForm"></el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="报销时间" prop="dates">
        <el-date-picker
          style=""
          placement="bottom-start"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          v-model="searchForm.dates"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="经办人" prop="handled">
        <UserSelect :limit='1' :userName="searchForm.handled" @getValue='(value, label) => {searchForm.handled = label}'></UserSelect>
      </el-form-item>
      <el-form-item label="报销人" prop="remiBy">
        <UserSelect :limit='1' :userName="searchForm.remiBy" @getValue='(value, label) => {searchForm.remiBy = label}'></UserSelect>
      </el-form-item>
      <el-form-item label="报销状态" prop="type">
        <el-select v-model="searchForm.type" placeholder="请选择" style="width:100%;">
          <el-option
            v-for="item in $dictUtils.getDictList('status')"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="报销部门" prop="department">
        <SelectTree
          ref="officeTree"
          :props="{
                value: 'id',             // ID字段名
                label: 'name',         // 显示名称
                children: 'children'    // 子级字段名
              }"
          :url="`/sys/office/treeData?type=2`"
          :value="searchForm.department"
          :clearable="true"
          :accordion="true"
          @getValue="(value,label) => {searchForm.department=label}"/>
      </el-form-item>
      <el-form-item label="报销类别" prop="remiType">
        <SelectTree
          ref="areaTree"
          :props="{
                  value: 'id',             // ID字段名
                  label: 'name',         // 显示名称
                  children: 'children'    // 子级字段名
                }"
          url="/reimbursement/type/treeData?type=12"
          :value="searchForm.remiType"
          :clearable="true"
          :accordion="true"
          @getValue="(value, label) => {searchForm.remiType=label}"/>
      </el-form-item>
      <el-form-item label="报销金额" prop="amounts">
        <InputNumber :disabled="false" :precision="num" v-model="searchForm.amounts"></InputNumber>
      </el-form-item>
      <el-form-item label="报告号" prop="reportNumber">
        <el-input size="small" v-model="searchForm.reportNumber" placeholder="请输入报告号" clearable></el-input>
      </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" style="">
      <vxe-toolbar :refresh="{query: refreshList}" custom>
        <template #buttons>
          <el-button v-if="hasPermission('reimbursement:info:add')" type="primary" size="small" icon="el-icon-plus" @click="add()">新建</el-button>
          <el-button v-if="hasPermission('reimbursement:info:del')" type="danger" size="small" icon="el-icon-delete" @click="del()" :disabled="$refs.infoTable && $refs.infoTable.getCheckboxRecords().length === 0" plain>删除</el-button>
          <el-button v-if="hasPermission('sys:project:exportFile')"  type="warning" plain @click="exportFile()" size="small">导出</el-button>
        </template>
      </vxe-toolbar>
      <div style="height: calc(100% - 50px)">
        <vxe-table
          border="inner"
          auto-resize
          resizable
          height="auto"
          :loading="loading"
          size="small"
          ref="infoTable"
          show-header-overflow
          show-overflow
          highlight-hover-row
          :menu-config="{}"
          :sort-config="{remote:true}"
          :data="dataList"
          :checkbox-config="{}">
          <vxe-column type="seq" width="60" title="序号"></vxe-column>
          <vxe-column type="checkbox" width="40" ></vxe-column>
          <vxe-column width="200" title="报销编号" field="no" align="left">
            <template slot-scope="scope">
              <el-link  type="primary" :underline="false" v-if="hasPermission('reimbursement:info:view')" @click="view(scope.row.id)">{{scope.row.no}}</el-link>
              <el-link  type="primary" :underline="false" v-else-if="hasPermission('reimbursement:info:view')" @click="view(scope.row.id)">{{scope.row.no}}</el-link>
              <span v-else>{{scope.row.no}}</span>
            </template>
          </vxe-column>
          <vxe-column width="200" title="报销类别" field="typeName"></vxe-column>
          <vxe-column width="200" title="报销项目" field="projectName">
            <template slot-scope="scope">
              <el-link  type="primary" :underline="false" v-if="hasPermission('reimbursement:info:view') && scope.row.projectId != undefined" @click="viewProject(scope.row.projectId)">{{scope.row.projectName}}</el-link>
              <el-link  type="primary" :underline="false" v-else-if="hasPermission('reimbursement:info:view') && scope.row.projectId != undefined" @click="viewProject(scope.row.projectId)">{{scope.row.projectName}}</el-link>
              <span v-else>{{scope.row.projectName}}</span>
            </template>
          </vxe-column>
          <vxe-column width="200" title="报告号" field="reportNumber"></vxe-column>
          <vxe-column width="100" title="经办人" field="userName"></vxe-column>
          <vxe-column width="100" title="报销人" field="name"></vxe-column>
          <vxe-column width="200" title="报销部门" field="deptName"></vxe-column>
          <vxe-column width="100" title="报销日期" field="reimDate"></vxe-column>
          <vxe-column width="100" title="报销金额" field="number"></vxe-column>
          <vxe-column width="100" title="状态" field="type">
            <template slot-scope="scope">
              <el-button type="text" @click="detail(scope.row)" :type="$dictUtils.getDictLabel('status_info', scope.row.type, '-')" effect="dark" size="mini">{{$dictUtils.getDictLabel("status", scope.row.type, '未开始')}} </el-button>
            </template>
          </vxe-column>

          <vxe-column title="操作" width="230px" fixed="right" align="center">
            <template  slot-scope="scope">
              <el-button v-if="hasPermission('reimbursement:info:edit') && (scope.row.type === '1' || scope.row.type === '3' || scope.row.type === '4')" type="text" icon="el-icon-edit" size="small" @click="edit(scope.row)">修改</el-button>
              <el-button v-if="hasPermission('reimbursement:info:edit') && (scope.row.type === '2')" type="text" icon="el-icon-back" size="small" @click="reback(scope.row)">撤回</el-button>
              <el-button v-if="hasPermission('reimbursement:info:del') && (scope.row.type === '1')" type="text" icon="el-icon-delete" 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>

        <ProgramPageForm ref="programPageForm" @getProgram="getProgram"></ProgramPageForm>
        <InfoForm ref="infoForm" @refreshDataList="refreshList"></InfoForm>
        <ProjectForm ref="projectForm" @refreshDataList="refreshList"></ProjectForm>
      </div>
    </div>
  </div>
</template>

<script>
  import ReimbursementService from '@/api/sys/ReimbursementService'
  import InputNumber from '@/views/modules/sys/workContract/InputNumber.vue'
  import SelectUserTree from '@/views/modules/utils/treeUserSelect'
  import UserSelect from '@/components/userSelect'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import ProgramPageForm from '@/views/modules/finance/invoice/ProgramPageForm'
  import InfoForm from './InfoForm'
  import TaskService from '@/api/flowable/TaskService'
  import ProcessService from '@/api/flowable/ProcessService'
  import pick from 'lodash.pick'
  import ProjectForm from '@/views/modules/program/registered/ProjectForm'
  export default {
    data () {
      return {
        num: 0,
        visable: false,
        gridData: [],
        searchForm: {
          project: '',
          dates: [],
          handled: '',
          remiBy: '',
          type: [],
          department: '',
          remiType: '',
          amounts: [],
          reportNumber: ''
        },
        dataList: [],
        tablePage: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          orders: []
        },
        loading: false
      }
    },
    reimbursementService: null,
    taskService: null,
    processService: null,
    created () {
      this.reimbursementService = new ReimbursementService()
      this.taskService = new TaskService()
      this.processService = new ProcessService()
    },
    components: {
      InputNumber,
      SelectUserTree,
      SelectTree,
      ProgramPageForm,
      InfoForm,
      ProjectForm,
      UserSelect
    },
    mounted () {
      this.refreshList()
    },
    activated () {
      this.refreshList()
    },
    computed: {
      userName () {
        return JSON.parse(localStorage.getItem('user')).name
      },
      user () {
        this.create = JSON.parse(localStorage.getItem('user')).id
        console.log('createId', this.create)
        return JSON.parse(localStorage.getItem('user'))
      }
    },
    methods: {
      // 新增
      add () {
        // 读取流程表单
        let tabTitle = `发起流程【报销审批】`
        let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [报销审批]`
        this.taskService.getTaskDef({ procDefId: this.processDefinitionId,
          status: 'startAndHold'}).then((data) => {
            this.$router.push({
              path: '/flowable/task/TaskForm',
              query: {
                procDefId: this.processDefinitionId,
                procDefKey: this.procDefKey,
                status: 'startAndHold',
                title: tabTitle,
                formType: data.data.formType,
                formUrl: data.data.formUrl,
                formTitle: processTitle,
                businessId: 'false',
                isShow: false,
                routePath: '/reimbursement/info/InfoList'
              }
            })
          })
      },
      // 修改
      edit (row) {
        // 暂存修改
        let status = ''
        if (row.type === '1') {
          status = 'startAndHold'
        }
        // 撤回或者驳回修改
        if (row.type === '3' || row.type === '4') {
          status = 'startAndClose'
        }
        // 读取流程表单
        let tabTitle = `发起流程【报销申请】`
        let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [报销申请]`
        this.taskService.getTaskDef({ procDefId: this.processDefinitionId,
          businessId: row.id,
          businessTable: 'reimbursement_info',
          status: status
        }).then((data) => {
          this.$router.push({
            path: '/flowable/task/TaskForm',
            query: {
              procDefId: this.processDefinitionId,
              procDefKey: this.procDefKey,
              status: status,
              title: tabTitle,
              formType: data.data.formType,
              formUrl: data.data.formUrl,
              formTitle: processTitle,
              businessTable: 'reimbursement_info',
              businessId: row.id,
              isShow: false,
              routePath: '/reimbursement/info/InfoList'
            }
          })
        })
      },
      // 撤回
      reback (row) {
        this.$confirm(`确定撤回流程吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          taskId: row.procInsId,
          type: 'warning'
        }).then(() => {
          this.taskService.backNodes(row.taskId).then(({data}) => {
            let backNodes = data
            if (backNodes.length > 0) {
              let backTaskDefKey = backNodes[0].taskDefKey
              this.taskService.back({
                taskId: row.taskId,
                backTaskDefKey: backTaskDefKey,
                isShow: false,
                ...this.auditForm
              }).then(({data}) => {
                row.type = '3'
                console.log('type', row)
                this.reimbursementService.updateStatusById(row)
                this.$message.success('回退成功')
                this.refreshList()
              })
            }
          })
        })
      },
      // 查看
      view (id) {
        this.$refs.infoForm.init('view', id)
      },
      // 查看报销项目
      viewProject (id) {
        this.$refs.projectForm.init('view', id)
      },
      // 获取数据列表
      refreshList () {
        this.loading = true
        this.reimbursementService.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.processService.getByName('报销申请').then(({data}) => {
          if (!this.commonJS.isEmpty(data.id)) {
            this.processDefinitionId = data.id
            this.procDefKey = data.key
          }
        })
      },
      // 删除
      del (id) {
        let ids = id || this.$refs.infoTable.getCheckboxRecords().map(item => {
          return item.id
        }).join(',')
        this.$confirm(`确定删除所选项吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          this.reimbursementService.remove(ids).then(({data}) => {
            this.$message.success(data)
            this.refreshList()
            this.loading = false
          })
        })
      },
      resetSearch () {
        this.$refs.searchForm.resetFields()
        this.refreshList()
      },
      // 流程详情
      detail (row) {
        if (!this.commonJS.isEmpty(row.type) && row.type !== '1') {
          this.taskService.getTaskDef({
            procInsId: row.procInsId,
            procDefId: row.processDefinitionId
          }).then(({data}) => {
            this.$router.push({
              path: '/flowable/task/TaskFormDetail',
              query: {
                isShow: 'false',
                readOnly: true,
                title: '流程详情',
                formTitle: '流程详情',
                businessId: row.id,
                status: 'reback',
                ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title', 'businessId')}
            })
          })
        }
      },
      openProgramPageForm (rowIndex) {
        // 打开单选组件
        this.$refs.programPageForm.init(null, false)
      },
      getProgram (rows) {
        // rows[0].name // 项目名称、开票详情
        // rows[0].contractName // 合同名称
        // rows[0].no // 项目编号
        // rows[0].clientName // 客户名称
        // rows[0].client // 客户id
        // rows[0].id // 项目id
        // rows[0].location // 项目所在地
        this.searchForm.project = rows[0].name
      },
      // 下载文档
      exportFile () {
        this.loading = true
        this.reimbursementService.exportFile({
          'itemType': '1',
          ...this.searchForm
        }).then((res) => {
          // 将二进制流文件写入excel表，以下为重要步骤
          this.$utils.downloadExcel(res.data, '报销申请列表信息')
          this.loading = false
        }).catch(function (err) {
          this.loading = false
          if (err.response) {
            console.log(err.response)
          }
        })
      },
      // 当前页
      currentChangeHandle ({ currentPage, pageSize }) {
        this.tablePage.currentPage = currentPage
        this.tablePage.pageSize = pageSize
        this.refreshList()
      }
    }
  }
</script>
