<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="businessCode">
        <el-input size="small"  v-model="searchForm.businessCode"   placeholder="报销批次"   clearable></el-input>
      </el-form-item>
      <el-form-item prop="reimbursementBatch">
        <el-input size="small"  v-model="searchForm.reimbursementBatch"   placeholder="业务编号"   clearable></el-input>
      </el-form-item>
      <el-form-item prop="invoiceNumber">
        <el-input size="small"  v-model="searchForm.invoiceNumber"   placeholder="发票号码"   clearable></el-input>
      </el-form-item>
      <el-form-item prop="firmName">
        <el-input size="small"  v-model="searchForm.firmName"   placeholder="购方企业名称"   clearable></el-input>
      </el-form-item>
      <el-form-item prop="proposer">
        <el-input size="small"  v-model="searchForm.proposer"   placeholder="项目经理"   clearable></el-input>
      </el-form-item>
      <el-form-item prop="partner">
        <el-input size="small"  v-model="searchForm.partner"   placeholder="部门"   clearable></el-input>
      </el-form-item>

      <el-form-item
        label="收入"
        class="priceFormItem"
        prop="income"
      >
        <el-input
          v-model="searchForm.beginIncome"
          onkeyup="value=value.replace(/[^\d]/g,'')"
          class="priceInput"
          style="width: 130px; margin-right: 10px"
        />-<el-input
        v-model="searchForm.endIncome"
        class="priceInput"
        onkeyup="value=value.replace(/[^\d]/g,'')"
        style="width: 130px; margin-left: 10px"
      />
      </el-form-item>

      <el-form-item label="开票日期" prop="makeTime">
        <el-date-picker
          v-model="searchDates"
          type="daterange"
          size="small"
          align="right"
          value-format="yyyy-MM-dd HH:mm:ss"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions">
        </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 custom>
        <template #buttons>
          <el-row>
            <el-upload style="float: left"
                       class="upload-demo"
                       :on-success="uploadSuccess"
                       :show-file-list="false"
                       :before-upload="beforeUpload"
                       :action="`${$http.BASE_URL}/wuHanReimbursement/uploadFile`"
                       multiple
                       list-type="picture">
              <el-button size="small"
                         icon="el-icon-upload"
                         type="primary">点击上传</el-button>
            </el-upload>


            <el-button style="margin-left: 10px" v-if="hasPermission('wuHanReimbursement:del')" :disabled="$refs.xTree && $refs.xTree.getCheckboxRecords().length === 0" type="danger" size="small" icon="el-icon-delete" @click="del()" plain>删除</el-button>
            <el-button v-if="hasPermission('wuHanReimbursement:import')"  type="default" @click="downloadTpl()" size="small">下载模板</el-button>
            <el-button style="margin-left: 10px" v-if="hasPermission('wuHanReimbursement:edit')" :disabled="$refs.xTree && $refs.xTree.getCheckboxRecords().length === 0" type="primary" size="small" icon="el-icon-edit" @click="editInvoiceGatheringTime()" plain>批量收款</el-button>

            <el-button v-if="hasPermission('wuHanReimbursement:addBatchReimbursement')" type="primary" size="small" icon="el-icon-plus" @click="add()">批量报销</el-button>
          </el-row>

        </template>
      </vxe-toolbar>
      <div style="height: calc(100% - 80px);">
        <vxe-table
          ref="xTree"
          border="inner"
          auto-resize
          resizable
          height="auto"
          row-id="id"
          size="small"
          show-header-overflow
          show-overflow
          highlight-hover-row
          :print-config="{}"
          :export-config="{
                    remote: true,
                    filename: `总所报销数据${moment(new Date()).format('YYYY-MM-DD')}`,
                    sheetName: '总所报销数据',
                    exportMethod: exportMethod,
                    types: ['xlsx'],
                    modes: ['current', 'selected', 'all']
                  }"
          :tree-config="{expandAll: true}"
          :loading="loading"
          :checkbox-config="{labelField: ''}"
          :data="dataList">
          <vxe-column type="checkbox" width="40px"> </vxe-column>
          <vxe-column  width="140px" title="报销批次"  field="businessCode"  align="left" tree-node >
            <template slot-scope="scope">
              <el-link  type="primary" :underline="false" v-if="scope.row.parentId == '0'" @click="view(scope.row.id)">{{scope.row.businessCode}}</el-link>
              <span v-else></span>
            </template>
          </vxe-column>
          <vxe-column  width="100px" title="业务编号" field="reimbursementBatch" align="center" visible></vxe-column>
          <vxe-column  width="100px" title="所属年份" field="year" align="center" visible></vxe-column>
          <vxe-column  width="100px" title="发票代码" field="invoiceCode" align="center" visible></vxe-column>
          <vxe-column  width="100px" title="发票号码" field="invoiceNumber" align="center">
            <template slot-scope="scope">
              <el-link  type="primary" :underline="false" v-if="hasPermission('wuHanReimbursement:view') && scope.row.parentId !== '0'" @click="viewInvoice(scope.row.id)">{{scope.row.invoiceNumber}}</el-link>
              <span v-else></span>
            </template>
          </vxe-column>
          <vxe-column  width="100px" title="金额" field="money" align="center"></vxe-column>
          <vxe-column  width="100px" title="税额" field="tax" align="center"></vxe-column>
          <vxe-column  width="100px" title="收入" field="income" align="center"></vxe-column>
          <vxe-column  width="100px" title="报销比例%" field="reimbursementRatio" align="center"></vxe-column>
          <vxe-column  width="100px"  title="状态" field="reimbursementStatus">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.reimbursementStatus === '1'"> 已完成</el-tag>
            </template>
          </vxe-column>
          <vxe-column  width="100px" title="可报金额" field="canReimbursementAmount" align="center">
            <template slot-scope="scope">
              <span style="font-weight: bold">{{scope.row.canReimbursementAmount}}</span>
            </template>
          </vxe-column>
          <vxe-column  width="100px" title="已报金额" field="allAlreadyReimbursementQuota" align="center">
            <template slot-scope="scope">
              <span style="font-weight: bold">{{scope.row.allAlreadyReimbursementQuota}}</span>
            </template>
          </vxe-column>
          <vxe-column  width="200px" title="购方企业名称" field="firmName" align="center"></vxe-column>
          <vxe-column  width="100px" title="开票日期" field="makeTime" align="center"></vxe-column>
          <vxe-column  width="150px" title="商品名称" field="name" align="center"></vxe-column>
          <vxe-column  width="100px" title="项目经理" field="proposer" align="center"></vxe-column>
          <vxe-column  width="100px" title="部门" field="partner" align="center"></vxe-column>
          <vxe-column  width="100px" title="业务类型" field="businessType" align="center"></vxe-column>
          <vxe-column  width="100px" title="收款日期" field="gatheringTime" align="center"></vxe-column>


          <vxe-column title="操作" width="300px" fixed="right" align="center">
            <template slot-scope="scope">
              <el-button v-if="hasPermission('wuHanReimbursement:edit')  && scope.row.businessFlag === '1'" type="text" icon="el-icon-edit" size="small" @click="editInvoiceBusiness(scope.row.id)">新增报销批次</el-button>
              <el-button v-if="hasPermission('wuHanReimbursement:edit') && scope.row.businessCode!=='' && scope.row.parentId === '0' && scope.row.randomType === '1' " type="text" icon="el-icon-edit" size="small" @click="editBusiness(scope.row.id)">编辑报销批次</el-button>
              <el-button v-if="hasPermission('wuHanReimbursement:edit') && (scope.row.businessCode==='' && scope.row.parentId === '0' && scope.row.businessFlag === '0')" type="text" icon="el-icon-edit" size="small" @click="editBusiness(scope.row.id)">新增报销批次</el-button>
              <el-button v-if="hasPermission('wuHanReimbursement:edit') && scope.row.businessCode !== '' && !scope.row.reimbursementRatio && scope.row.parentId === '0'" type="text" icon="el-icon-edit" size="small" @click="editBusinessRatio(scope.row.id)">报销比例</el-button>
              <el-button v-if="hasPermission('wuHanReimbursementBusiness:add') && scope.row.businessCode !== '' && scope.row.reimbursementRatio && scope.row.parentId === '0' && scope.row.reimbursementStatus === '0'" type="text" icon="el-icon-plus" size="small" @click="addBusinessInfo(scope.row.id, scope.row.businessCode)">业务报销</el-button>
              <el-button v-if="hasPermission('wuHanReimbursementBusiness:view') && scope.row.businessCode !== '' && scope.row.reimbursementRatio && scope.row.parentId === '0'" type="text" icon="el-icon-view" size="small" @click="viewBusinessInfo(scope.row.id)">业务报销详情</el-button>

              <el-button v-if="hasPermission('wuHanReimbursement:edit') && scope.row.parentId !== '0' && !scope.row.gatheringTime" type="text" icon="el-icon-edit" size="small" @click="editInvoice(scope.row.id)">收款</el-button>
              <el-button v-if="hasPermission('wuHanReimbursement:edit') && scope.row.parentId !== '0'" type="text" icon="el-icon-edit" size="small" @click="modifyInvoice(scope.row.id)">修改</el-button>
              <el-button v-if="hasPermission('wuHanReimbursement:del') && scope.row.parentId === '0'" type="text" icon="el-icon-delete" size="small" @click="delBusiness(scope.row.id)">删除</el-button>
              <el-button v-if="hasPermission('wuHanReimbursement: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>
        <reimbursement-select ref="reimbursementSelect" @doSubmit="selectBatchReimbursement"></reimbursement-select>
      </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>
    <reimbursementBusinessList ref="reimbursementBusinessList" @refreshDataList="refreshList"></reimbursementBusinessList>
    <reimbursementInvoiceForm ref="reimbursementInvoiceForm" @refreshDataList="refreshList"></reimbursementInvoiceForm>
    <reimbursementInvoiceModify ref="reimbursementInvoiceModify" @refreshDataList="refreshList"></reimbursementInvoiceModify>
  </div>


</template>
<script>
import ReimbursementSys from '@/api/reimbursementSys/wuHanReimbursementSysService'
import XEUtils from 'xe-utils'
import reimbursementForm from './wuHanReimbursementForm'
import reimbursementGatheringTimeForm from './wuHanReimbursementGatheringTimeForm'
import reimbursementRatioForm from './wuHanReimbursementRatioForm'
import reimbursementInvoiceForm from './wuHanReimbursementInvoiceForm'
import reimbursementInvoiceModify from './wuHanReimbursementInvoiceModify'
import reimbursementBusinessForm from './wuHanReimbursementBusinessForm'
import reimbursementSelect from './wuHanReimbursementSelectDialog'
export default {
  data () {
    return {
      dataList: [],
      searchDates: '',
      searchForm: {
        reimbursementBatch: '',
        businessFlag: '',
        businessCode: '',
        invoiceNumber: '',
        proposer: '',
        partner: '',
        firmName: '',
        reimbursementRatio: '',
        randomType: '',
        beginDate: '',
        endDate: '',
        beginIncome: '',
        endIncome: ''
      },
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        orders: [{column: 'a.create_date', asc: false}]
      },
      loading: false,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  watch: {
    searchDates () {
      if (this.searchDates) {
        this.searchForm.beginDate = this.searchDates[0]
        this.searchForm.endDate = this.searchDates[1]
      } else {
        this.searchForm.beginDate = ''
        this.searchForm.endDate = ''
      }
    }
  },
  components: {
    reimbursementForm,
    reimbursementGatheringTimeForm,
    reimbursementRatioForm,
    reimbursementInvoiceForm,
    reimbursementInvoiceModify,
    reimbursementBusinessForm,
    reimbursementSelect
  },
  ReimbursementSys: null,
  created () {
    this.reimbursementSys = new ReimbursementSys()
  },
  activated () {
    this.refreshList()
  },
  methods: {
    // 获取数据列表
    refreshList () {
      this.loading = true
      this.reimbursementSys.treeData({
        'current': this.tablePage.currentPage,
        'size': this.tablePage.pageSize,
        'orders': this.tablePage.orders,
        ...this.searchForm
      }).then(({data}) => {
        this.dataList = data
        this.tablePage.total = data.total
        this.handleSearch()
        this.loading = false
      })
    },
    beforeUpload (file) {
      const isExcel = file.name.indexOf('.xls') >= 0 || file.name.indexOf('.xlsx') >= 0
      const isLt2M = file.size / 1024 / 1024 < 1
      if (!isExcel) {
        this.$message.error('只能上传xls、xlsx文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 10MB!')
        return false
      }
      this.loading = true
      return true
    },
    handleSearch () {
      let name = XEUtils.toValueString(this.searchForm.businessCode).trim()
      let options = { children: 'children' }
      let searchProps = ['name']
      this.dataList = XEUtils.searchTree(
        this.dataList.records, item => searchProps.some(key => XEUtils.toValueString(item[key]).indexOf(name) >= -1), options)
      this.$nextTick(() => {
        this.$refs.xTree.setAllTreeExpand(true)
      })
    },
    resetSearch () {
      this.$refs.searchForm.resetFields()
      this.searchForm.beginIncome = ''
      this.searchForm.endIncome = ''
      this.searchForm.beginDate = ''
      this.searchForm.endDate = ''
      this.searchDates = ''
      this.refreshList()
    },
    uploadSuccess (res, file) {
      if (res.success) {
        this.$message.success({dangerouslyUseHTMLString: true,
          message: res.message})
        this.refreshList()
      } else {
        this.$message.error(res.message)
        this.refreshList()
      }
    },
    // 当前页
    currentChangeHandle ({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.refreshList()
    },
    // 新增
    add () {
      this.$refs.reimbursementSelect.init()
    },
    // 修改
    editBusiness (id) {
      this.$refs.reimbursementForm.init('editBusiness', {id: id, parent: {id: '', name: ''}})
    },
    editInvoiceBusiness (id) {
      this.$refs.reimbursementForm.init('editInvoiceBusiness', {id: id, parent: {id: '', name: ''}})
    },
    // 修改
    editBusinessRatio (id) {
      this.$refs.reimbursementRatioForm.init('editBusinessRatio', {id: id, parent: {id: '', name: ''}})
    },
    // 修改
    addBusinessInfo (id, businessCode) {
      this.$refs.reimbursementBusinessForm.init('addBusinessInfo', {id: '', businessCodeId: id, businessCode: businessCode, parent: {id: '', name: ''}})
    },
    // 查看业务报销详情/reimbursementSys/reimbursementBusinessList
    viewBusinessInfo (id) {
      this.$router.push({path: `/reimbursementSys/wuHanReimbursementBusinessList`, query: {id: id, title: '业务报销详情'}})
    },
    // 修改发票收款日期
    editInvoiceGatheringTime (id) {
      let ids = id || this.$refs.xTree.getCheckboxRecords().map(item => {
        return item.id
      }).join(',')
      this.$refs.reimbursementGatheringTimeForm.init('edit', {id: ids, parent: {id: '', name: ''}})
    },
    // 修改发票信息
    editInvoice (id) {
      this.$refs.reimbursementInvoiceForm.init('editInvoice', {id: id, parent: {id: '', name: ''}})
    },
    // 修改发票信息
    modifyInvoice (id) {
      this.$refs.reimbursementInvoiceModify.init('modifyInvoice', {id: id, parent: {id: '', name: ''}})
    },
    // 查看
    view (id) {
      this.$refs.reimbursementForm.init('view', {id: id, parent: {id: '', name: ''}})
    },
    // 查看发票信息
    viewInvoice (id) {
      this.$refs.reimbursementInvoiceForm.init('viewInvoice', {id: id, parent: {id: '', name: ''}})
    },
    // 下载模板
    downloadTpl () {
      this.reimbursementSys.exportTemplate().then((res) => {
        // 将二进制流文件写入excel表，以下为重要步骤
        this.$utils.downloadExcel(res.data, '报销发票导入模板')
      }).catch(function (err) {
        if (err.response) {
          console.log(err.response)
        }
      })
    },
    // 删除
    delBusiness (id) {
      let ids = id || this.$refs.xTree.getCheckboxRecords().map(item => {
        return item.id
      }).join(',')
      this.$confirm(`确定删除该记录吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        this.reimbursementSys.deleteBusiness(ids).then(({data}) => {
          this.loading = false
          this.$message({
            message: data,
            type: 'success',
            duration: 1500
          })
          this.refreshList()
        })
      })
    },
    // 删除
    delInvoice (id) {
      let ids = id || this.$refs.xTree.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()
        })
      })
    },
    // 删除
    del (id) {
      let ids = id || this.$refs.xTree.getCheckboxRecords().map(item => {
        return item.id
      }).join(',')
      this.$confirm(`确定删除该记录吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        this.reimbursementSys.delete(ids).then(({data}) => {
          this.loading = false
          this.$message({
            message: data,
            type: 'success',
            duration: 1500
          })
          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.reimbursementSys.exportExcel(params).then((res) => {
        // 将二进制流文件写入excel表，以下为重要步骤
        this.$utils.downloadExcel(res.data, options.filename)
      }).catch(function (err) {
        if (err.response) {
          console.log(err.response)
        }
      })
    },
    selectBatchReimbursement (invoices) {
      let invoiceNumbers = invoices.map(invoice => { return invoice.id }).join(',')
      this.loading = true
      this.reimbursementSys.addBatchReimbursement(invoiceNumbers).then(({data}) => {
        this.loading = false
        this.$message.success({dangerouslyUseHTMLString: true,
          message: data})
        this.refreshList()
      })
    }
  }

}
</script>
