<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 prop="userId" :rules=" [{trigger: 'blur'}]" label="人员">
        <SelectUserTree
          ref="companyTree"
          :props="{
                  value: 'id',             // ID字段名
                  label: 'name',         // 显示名称
                  children: 'children'    // 子级字段名
                }"
          :url="`/sys/user/treeUserDataByOfficeName?type=2&officeName=中审众环`"
          :value="searchForm.userId"
          :clearable="true"
          :accordion="true"
          @getValue="(value) => {searchForm.userId=value}"/>
      </el-form-item>

      <el-form-item prop="officeId" :rules=" [{trigger: 'blur'}]" label="部门">
        <SelectUserTree
          ref="companyTree"
          :props="{
                  value: 'id',             // ID字段名
                  label: 'name',         // 显示名称
                  children: 'children'    // 子级字段名
                }"
          :url="`/sys/user/treeUserDataByOfficeList?type=2&officeName=中审众环`"
          :value="searchForm.officeId"
          :clearable="true"
          :accordion="true"
          @getValue="(value) => {searchForm.officeId=value}"/>
      </el-form-item>

      <el-form-item label="年份" prop="year":rules="[{trigger:'blur'}]">
        <el-date-picker
          v-model="searchForm.year"
          type="year"
          value-format="yyyy"
          placeholder="选择年份">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="报销来源" prop="reimbursementAddress">
        <el-select v-model="searchForm.reimbursementAddress" clearable placeholder="请选择">
          <el-option
            v-for="item in reimbursementAddressList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </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}" export  print resizable custom>
        <template #buttons>
          <el-row>
            <el-button v-if="hasPermission('reimbursementUser:add')" type="primary" icon="el-icon-plus" size="small" @click="add()">新增</el-button>
            <el-button v-if="hasPermission('reimbursementUser:del')" type="danger"   size="small" icon="el-icon-delete" @click="del()" :disabled="$refs.reimbursementUserTable && $refs.reimbursementUserTable.getCheckboxRecords().length === 0" plain>删除</el-button>
            <!--<el-button v-if="hasPermission('reimbursementUser:import')"  type="default" @click="downloadTpl()" size="small">下载模板</el-button>-->
            <el-button v-if="hasPermission('reimbursementUser:add')" type="success" icon="el-icon-success" size="small" @click="initialize()">初始化</el-button>
          </el-row>
        </template>
      </vxe-toolbar>
      <div style="height: calc(100% - 80px);">
        <vxe-table
          border="inner"
          auto-resize
          resizable
          height="auto"
          :loading="loading"
          size="small"
          ref="reimbursementUserTable"
          show-header-overflow
          show-overflow
          highlight-hover-row
          :menu-config="{}"
          :print-config="{}"
          :export-config="{
                    remote: true,
                    filename: `中审众环报销人员信息数据${moment(new Date()).format('YYYY-MM-DD')}`,
                    sheetName: '中审众环报销人员信息数据',
                    exportMethod: exportMethod,
                    types: ['xlsx'],
                    modes: ['current', 'selected', 'all']
                  }"
          @sort-change="sortChangeHandle"
          :sort-config="{remote:true}"
          :data="dataList"
          :checkbox-config="{}">
          <vxe-column type="checkbox" width="40px"> </vxe-column>
          <vxe-column  title="人员" field="user.name">
            <template slot-scope="scope">
              <el-link  type="primary" :underline="false" v-if="hasPermission('reimbursementUser:edit')" @click="view(scope.row.id)">{{scope.row.user.name}}</el-link>
              <el-link  type="primary" :underline="false" v-else-if="hasPermission('reimbursementUser:view')"  @click="view(scope.row.id,)">{{scope.row.user.name}}</el-link>
              <span v-else>{{scope.row.user.name}}</span>
            </template>
          </vxe-column>

          <vxe-column  title="部门" field="officeName"></vxe-column>
          <vxe-column  title="报销年份" field="year"></vxe-column>
          <vxe-column  title="日报销额度" field="reimbursementQuotaDay"></vxe-column>
          <vxe-column  title="年报销额度" field="reimbursementQuota"></vxe-column>

          <vxe-column  title="分所已报额度" field="substationAlreadyReimbursementAmount"></vxe-column>
          <vxe-column  title="总所已报额度" field="headquarterAlreadyReimbursementAmount"></vxe-column>
          <vxe-column  title="总报销额度" field="alreadyReimbursementAmount"></vxe-column>
          <vxe-column  title="剩余额度" field="remainReimbursementAmount"></vxe-column>
          <vxe-column  title="已报天数" field="alreadyReimbursementDay"></vxe-column>
          <vxe-column  title="剩余天数" field="surplusReimbursementDay"></vxe-column>
          <vxe-column title="操作" width="300px" fixed="right" align="center">
            <template  slot-scope="scope">
              <el-button v-if="hasPermission('reimbursementUser:view')" type="text" icon="el-icon-view" size="small" @click="viewBusinessInfo(scope.row.id)">报销详情</el-button>
              <el-button v-if="hasPermission('reimbursementUser:edit')" type="text" icon="el-icon-edit" size="small" @click="edit(scope.row.id)">修改</el-button>
              <el-button v-if="hasPermission('reimbursementUser:del')" 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>
      </div>
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <reimbursementUserForm ref="reimbursementUserForm" @refreshDataList="refreshList"></reimbursementUserForm>
  </div>


</template>
<script>
import SelectUserTree from '@/views/modules/reimbursementSys/utils/treeReimbursementBuinessUserSelect.vue'
import ReimbursementUser from '@/api/reimbursementSys/user/reimbursementUserService'
import reimbursementUserForm from './reimbursementUserForm'
export default {
  data () {
    return {
      dataList: [],
      searchForm: {
        year: '',
        officeType: '1',
        userId: '',
        officeId: '',
        reimbursementAddress: ''
      },
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        orders: [{column: 'a.create_date', asc: false}]
      },
      reimbursementAddressList: [{
        value: '0',
        label: '分所报销'
      }, {
        value: '1',
        label: '总所报销'
      }],
      loading: false
    }
  },
  components: {
    SelectUserTree,
    reimbursementUserForm
  },
  ReimbursementUser: null,
  created () {
    this.reimbursementUser = new ReimbursementUser()
  },
  activated () {
    this.refreshList()
  },
  methods: {
    // 获取数据列表
    refreshList () {
      this.loading = true
      this.reimbursementUser.findList({
        '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
      })
    },
    // 当前页
    currentChangeHandle ({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.refreshList()
    },
    resetSearch () {
      this.$refs.searchForm.resetFields()
      this.$nextTick(() => {
        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()
    },
    // 自定义服务端导入
    importMethod ({ file }) {
      // 处理表单
      const formBody = new FormData()
      formBody.append('file', file)
      this.reimbursementUser.importExcel(formBody).then(result => {
        this.$message.success(result.data)
        this.refreshList()
      })
    },
    // 下载模板
    downloadTpl () {
      this.reimbursementUser.exportTemplate().then((res) => {
        // 将二进制流文件写入excel表，以下为重要步骤
        this.$utils.downloadExcel(res.data, '报销人员导入模板')
      }).catch(function (err) {
        if (err.response) {
          console.log(err.response)
        }
      })
    },
    // 新增
    add () {
      this.$refs.reimbursementUserForm.init('add', {id: '', parent: {id: '', name: ''}})
    },
    // 修改
    edit (id) {
      this.$refs.reimbursementUserForm.init('edit', id)
    },
    // 查看
    view (id) {
      this.$refs.reimbursementUserForm.init('view', id)
    },
    // 查看业务报销详情
    viewBusinessInfo (id) {
      this.$router.push({path: `/reimbursementSys/user/reimbursementUserBusinessList`, query: {userId: id, title: '报销详情'}})
    },
    // 删除
    del (id) {
      let ids = id || this.$refs.reimbursementUserTable.getCheckboxRecords().map(item => {
        return item.id
      }).join(',')
      this.$confirm(`确定删除该记录吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        this.reimbursementUser.delete(ids).then(({data}) => {
          this.loading = false
          this.$message({
            message: data,
            type: 'success',
            duration: 1500
          })
          this.refreshList()
        })
        this.refreshList()
      })
    },
    // 初始化按钮
    initialize () {
      this.$confirm(`确定初始化人员信息吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        this.reimbursementUser.initialize({
          'officeType': this.searchForm.officeType
        }).then(({data}) => {
          this.loading = false
          this.$message({
            message: data,
            type: 'success',
            duration: 1500
          })
          this.refreshList()
        })
        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.data.map(item => item.id) : [],
        exportFields: options.columns.map(column => column.property)
      }
      return this.reimbursementUser.exportExcel(params).then((res) => {
        // 将二进制流文件写入excel表，以下为重要步骤
        this.$utils.downloadExcel(res.data, options.filename)
      }).catch(function (err) {
        if (err.response) {
          console.log(err.response)
        }
      })
    }
  }

}
</script>
