<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 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>
        <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('accountant:reimbursementBusinessTwo:add')" type="primary" size="small" icon="el-icon-plus"
                       @click="addBusinessInfo()">新增
            </el-button>
            <el-button v-if="hasPermission('accountant:reimbursementBusinessTwo:binding')" type="warning" size="small" icon="el-icon-edit"
                       @click="openDialog($refs.reimbursementUserTable.getCheckboxRecords())"
                       :disabled="$refs.reimbursementUserTable && $refs.reimbursementUserTable.getCheckboxRecords().length === 0"
                       plain>批量绑定
            </el-button>
            <el-button v-if="hasPermission('accountant:reimbursementBusinessTwo:del')" type="danger" size="small" icon="el-icon-delete"
                       @click="delInvoice()"
                       :disabled="$refs.reimbursementUserTable && $refs.reimbursementUserTable.getCheckboxRecords().length === 0"
                       plain>删除
            </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="{}"
          :sort-config="{remote:true}"
          :data="dataList"
          :checkbox-config="{}">
          <vxe-column type="checkbox" width="40px"></vxe-column>
          <vxe-column width="172px" title="报销人" field="userName" align="center" visible></vxe-column>
          <vxe-column width="172px" title="报销年份" field="year" align="center"></vxe-column>
          <vxe-column width="172px" title="报销类型" field="reimbursementType" align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.reimbursementType === '1'"> 正常报销</el-tag>
              <el-tag v-if="scope.row.reimbursementType === '2'"> 补差</el-tag>
            </template>
          </vxe-column>
          <vxe-column width="172px" title="报销天数" field="reimbursementDay" align="center"></vxe-column>
          <vxe-column width="172px" title="报销额度" field="reimbursementAmount" align="center"></vxe-column>
          <vxe-column title="操作" width="300px" fixed="right" align="center">
            <template slot-scope="scope">
              <el-button v-if="hasPermission('accountant:reimbursementBusinessTwo:binding') && scope.row.parentId !== '0'" type="text"
                         icon="el-icon-plus" size="small" @click="openDialog(scope.row)">绑定业务编号
              </el-button>
              <el-button v-if="hasPermission('accountant:reimbursementBusinessTwo:del') && scope.row.parentId !== '0'" type="text"
                         icon="el-icon-delete" size="small" @click="delInvoice(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>
    <!-- 弹窗, 新增 / 修改 -->
    <reimbursementForm ref="reimbursementForm" @refreshDataList="refreshList"></reimbursementForm>
    <reimbursementGatheringTimeForm ref="reimbursementGatheringTimeForm"
                                    @refreshDataList="refreshList"></reimbursementGatheringTimeForm>
    <reimbursementRatioForm ref="reimbursementRatioForm" @refreshDataList="refreshList"></reimbursementRatioForm>
    <reimbursementBusinessForm ref="reimbursementBusinessForm"
                               @refreshDataList="refreshList"></reimbursementBusinessForm>
    <reimbursementInvoiceForm ref="reimbursementInvoiceForm" @refreshDataList="refreshList"></reimbursementInvoiceForm>


    <el-dialog
      title="选择绑定业务编号"
      :visible.sync="dialogVisible"
      width="60%">
      <el-col :span="12">
        <label-wrap>请选择年份：</label-wrap>
        <el-select v-model="selectedYear" filterable placeholder="请选择年份" @change="findSelectCodeListByYear">
          <el-option
            v-for="item in selectYear"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-col>

      <el-col :span="12">
        <label-wrap>请选择业务编号：</label-wrap>
        <el-select v-model="selectedCode" filterable clearable placeholder="请选择业务编号" @change="determination($event)">
          <el-option
            v-for="item in selectCode"
            :key="item.id"
            :label="item.businessCode"
            :value="item.id">
          </el-option>
        </el-select>
      </el-col>

      <span slot="footer" class="dialog-footer">
    <el-button @click="closeDialog">取 消</el-button>
    <el-button type="primary" @click="bindBusinessCode">确 定</el-button>
  </span>
    </el-dialog>

  </div>


</template>
<script>
  import ReimbursementSys from '@/api/reimbursementSys/project/reimbursementIsNoTicketService'
  import SelectUserTree from '@/views/modules/reimbursementSys/utils/treeReimbursementBuinessUserSelect.vue'
  import reimbursementForm from './reimbursementForm'
  import reimbursementGatheringTimeForm from './reimbursementGatheringTimeForm'
  import reimbursementRatioForm from './reimbursementRatioForm'
  import reimbursementInvoiceForm from './reimbursementInvoiceForm'
  import reimbursementBusinessForm from './reimbursementIsNoTicketForm'
  import reimbursementSelect from './reimbursementSelectDialog'

  export default {
    data () {
      return {
        dataList: [],
        searchForm: {
          year: '',
          userId: ''
        },
        tablePage: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          orders: [{column: 'a.create_date', asc: false}]
        },
        loading: false,
        dialogVisible: false,
        bindObj: [],
        selectCode: [],
        selectedCode: '',
        selectYear: [],
        selectedYear: '',
        reimbursementAmount: 0,
        canReimbursementAmount: 0
      }
    },
    components: {
      reimbursementForm,
      reimbursementGatheringTimeForm,
      reimbursementRatioForm,
      reimbursementInvoiceForm,
      reimbursementBusinessForm,
      reimbursementSelect,
      SelectUserTree
    },
    ReimbursementSys: null,
    created () {
      this.reimbursementSys = new ReimbursementSys()
    },
    activated () {
      this.refreshList()
    },
    methods: {
      // 获取数据列表
      refreshList () {
        this.loading = true
        this.reimbursementSys.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()
        })
      },
      // 修改发票信息
      modifyInvoice (id) {
        this.$refs.reimbursementInvoiceModify.init('modifyInvoice', {id: id, parent: {id: '', name: ''}})
      },
      // 删除
      delInvoice (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.reimbursementSys.deleteInvoice(ids).then(({data}) => {
            this.loading = false
            this.$message({
              message: data,
              type: 'success',
              duration: 1500
            })
            this.refreshList()
          })
        })
      },
      addBusinessInfo (id, businessCode) {
        this.$refs.reimbursementBusinessForm.init('addBusinessInfo', {
          id: '',
          businessCodeId: '',
          businessCode: '',
          parent: {id: '', name: ''}
        })
      },
      bindBusinessCode () {
        if (this.selectedCode === '') {
          this.$message.error('请选择业务编号')
          return
        }
        this.reimbursementSys.modifyBindCode({
          'ids': this.bindObj,
          'businessCode': this.selectedCode,
          'money': this.reimbursementAmount
        }).then(({data}) => {
          if (!data) {
            this.$message.error('可报销额度不足')
          } else {
            this.closeDialog()
          }
        })
      },
      openDialog (obj) {
        // eslint-disable-next-line eqeqeq
        this.bindObj = obj.id || obj.map(item => {
          return item.id
        }).join(',')
        this.dialogVisible = true
        if (obj.length > 1) {
          obj.map(item => {
            this.reimbursementAmount += parseInt(item.reimbursementAmount)
          })
        } else {
          this.reimbursementAmount = obj.reimbursementAmount
        }
        this.reimbursementSys.findSelectYearList().then(({data}) => {
          this.selectYear = data
          this.selectedYear = this.selectYear[0]
          this.findSelectCodeListByYear()
        })
      },
      closeDialog () {
        this.dialogVisible = false
        this.selectedCode = ''
        this.refreshList()
        this.bindObj = []
        this.reimbursementAmount = 0
      },
      findSelectCodeListByYear () {
        this.selectedCode = ''
        this.reimbursementSys.findSelectCodeListByYear(this.selectedYear).then(({data}) => {
          this.selectCode = data
          this.selectedCode = ''
        })
      },
      determination (e) {
        for (let i = 0; i < this.selectCode.length; i++) {
          if (this.selectCode[i].id === e) {
            if (parseInt(this.selectCode[i].canReimbursementAmount) < parseInt(this.reimbursementAmount)) {
              this.$message.error('可报销额度不足,可报销额度为' + this.selectCode[i].canReimbursementAmount)
            }
          }
        }
      }
    }

  }
</script>
