<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-row :gutter="0">
        <el-form-item prop="no" label="发票申请编号">
          <el-input size="small" v-model="searchForm.no" placeholder="请输入发票申请编号" clearable></el-input>
        </el-form-item>
        <el-form-item prop="number" label="发票号">
          <el-input size="small" v-model="searchForm.number" placeholder="请输入发票号" clearable></el-input>
        </el-form-item>
<!--        <el-form-item prop="programName" label="项目名称">-->
<!--          <el-input size="small" v-model="searchForm.programName" placeholder="请输入项目名称" clearable @clear="clearProgram">-->
<!--            <el-button slot="append" @click="openProgramPageForm()" icon="el-icon-search"></el-button>-->
<!--          </el-input>-->
<!--        </el-form-item>-->
        <el-form-item v-if="showHideItem" prop="accountBegin" label="开票总金额">
          <el-input-number
            size="small"
            v-model="searchForm.accountBegin"
            controls-position="right"
            :controls="false"
            style="width:100%;"
            :precision="2"
            placeholder="请填写开票总金额"
            :step="0.01"
            :min="0"
            clearable>
          </el-input-number>
        </el-form-item>
        <el-form-item v-if="showHideItem" prop="accountEnd" label="-">
          <el-input-number
            size="small"
            v-model="searchForm.accountEnd"
            controls-position="right"
            :controls="false"
            style="width:100%;"
            :precision="2"
            placeholder="请填写开票总金额"
            :step="0.01"
            :min="0"
            clearable>
          </el-input-number>
        </el-form-item>
        <el-form-item v-if="showHideItem" prop="reconciliationPeopleName" label="对账人">
          <UserSelect :limit='1' :userName="searchForm.reconciliationPeopleName" @getValue='(value, label) => {searchForm.reconciliationPeopleName = label}'></UserSelect>
        </el-form-item>
        <el-form-item v-if="showHideItem" label="经办人" prop="operator">
          <UserSelect :limit='1' :userName="searchForm.operator" @getValue='(value, label) => {searchForm.operator = label}'></UserSelect>
        </el-form-item>
        <el-form-item v-if="showHideItem" prop="operatorOffice" label="经办人部门">
          <SelectTree
            ref="officeTree"
            :props="{
                  value: 'id',             // ID字段名
                  label: 'name',         // 显示名称
                  children: 'children'    // 子级字段名
                }"

            :url="`/sys/office/treeData?type=2`"
            :value="searchForm.operatorOffice"
            :clearable="true"
            :accordion="true"
            @getValue="(value) => {searchForm.operatorOffice=value}"/>
        </el-form-item>
        <el-form-item v-if="showHideItem" prop="billingWorkplaceReal" label="开票单位">
          <el-input size="small" v-model="searchForm.billingWorkplaceReal" placeholder="请输入开票单位" clearable></el-input>
        </el-form-item>
        <el-form-item v-if="showHideItem" prop="receivablesStatus" label="是否收款">
          <el-select v-model="searchForm.receivablesStatus" placeholder="请选择是否收款" clearable>
            <el-option
              v-for="item in this.$dictUtils.getDictList('collect_not')"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="showHideItem" prop="type" label="发票类型">
          <el-select v-model="searchForm.type" placeholder="请选择发票类型" clearable>
            <el-option
              v-for="item in this.$dictUtils.getDictList('invoice_type')"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="showHideItem" prop="receivablesType" label="收款类型">
          <el-select v-model="searchForm.receivablesType" placeholder="请选择收款类型"clearable>
            <el-option
              v-for="item in $dictUtils.getDictList('invoice_receivables_type')"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="showHideItem" prop="billingContent" label="开票内容">
          <el-select v-model="searchForm.billingContent" placeholder="请选择开票内容"clearable>
            <el-option
              v-for="item in $dictUtils.getDictList('invoice_billing_content')"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="showHideItem" prop="reconciliationArea" label="对账地区">
          <SelectTree
            ref="areaTree"
            :props="{
                    value: 'id',             // ID字段名
                    label: 'name',         // 显示名称
                    children: 'children'    // 子级字段名
                  }"
            url="/sys/area/treeData"
            :value="searchForm.reconciliationArea"
            :clearable="true"
            :accordion="true"
            @getValue="(value) => {searchForm.reconciliationArea=value}"/>
        </el-form-item>

        <el-form-item v-if="showHideItem" prop="billingDateList" label="开票日期">
          <el-date-picker
            size="small"
            @change="changeBillingDateList"
            v-model="searchForm.billingDateList"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            style="width: 100%  "
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            placement="bottom-start"
            clearabl>
          </el-date-picker>
        </el-form-item>
        <el-form-item v-if="showHideItem" prop="remittanceDateList" label="收款日期">
          <el-date-picker
            size="small"
            v-model="searchForm.remittanceDateList"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            style="width: 100%  "
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            placement="bottom-start"
            clearable>
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="default" @click="showHide" size="small" :icon="showHideIcon">{{showHideName}}</el-button>
          <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-row>
    </el-form>
    <div class="bg-white top" style="">
      <vxe-toolbar :refresh="{query: refreshList}" export custom>
        <template #buttons>
          <el-button v-if="hasPermission('cw_finance:invoice:add')" type="primary" size="small" icon="el-icon-plus" @click="start()">新建</el-button>
<!--          <el-button v-if="hasPermission('cw_finance:invoice:del')" type="danger"   size="small" icon="el-icon-delete" @click="del()" :disabled="$refs.invoiceTable && $refs.invoiceTable.getCheckboxRecords().length === 0" plain>删除</el-button>-->
        </template>
      </vxe-toolbar>
      <div style="height: calc(100% - 80px)">
        <vxe-table
          border="inner"
          auto-resize
          resizable
          height="auto"
          :loading="loading"
          size="small"
          ref="invoiceTable"
          show-header-overflow
          show-overflow
          highlight-hover-row
          :menu-config="{}"
          @sort-change="sortChangeHandle"
          :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']
                  }"
          :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 min-width="150" title="项目名称"align="center" field="programName">
            <template slot-scope="scope">
              <el-link  type="primary" :underline="false" @click="viewProject(scope.row.id)">{{scope.row.programName}}</el-link>
            </template>
          </vxe-column>
          <vxe-column min-width="150" title="发票申请编号"align="center" field="no">
            <template slot-scope="scope">
              <el-link  type="primary" :underline="false" @click="view(false, scope.row.id)">{{scope.row.no}}</el-link>
            </template>
          </vxe-column>
          <vxe-column min-width="150" title="发票号"align="center" field="number"></vxe-column>
          <vxe-column min-width="150" title="实际开票单位"align="center" field="billingWorkplaceReal"></vxe-column>
          <vxe-column min-width="150" title="经办人"align="center" field="operator"></vxe-column>
          <vxe-column min-width="150" title="经办人部门"align="center" field="operatorOffice"></vxe-column>
          <vxe-column min-width="150" title="开票总金额（元）"align="center" field="account"></vxe-column>
          <vxe-column min-width="150" title="发票金额（元）"align="center" field="accountDetail"></vxe-column>
          <vxe-column min-width="120" title="开票内容"align="center" field="billingContent">
            <template slot-scope="scope">
              {{$dictUtils.getDictLabel('invoice_billing_content', scope.row.billingContent, '-')}}
            </template>
          </vxe-column>
          <vxe-column min-width="100" title="收款类型"align="center" field="receivablesType">
            <template slot-scope="scope">
              {{$dictUtils.getDictLabel('invoice_receivables_type', scope.row.receivablesType, '-')}}
            </template>
          </vxe-column>
          <vxe-column min-width="100" title="发票类型"align="center" field="type">
            <template slot-scope="scope">
              {{$dictUtils.getDictLabel('invoice_type', scope.row.type, '-')}}
            </template>
          </vxe-column>
          <vxe-column min-width="120" title="开票日期"align="center" field="billingDate"></vxe-column>
          <vxe-column min-width="120" title="收款日期"align="center" field="receivablesDate"></vxe-column>
          <vxe-column min-width="110" fixed="right"align="center" title="是否收款" field="receivablesStatus">
            <template slot-scope="scope">
              {{$dictUtils.getDictLabel('collect_not', scope.row.receivablesStatus, '-')}}
            </template>
          </vxe-column>
          <vxe-column min-width="110" fixed="right"align="center" title="是否作废" field="invalidStatus">
            <template slot-scope="scope">
              {{scope.row.invalidStatus === '1'?'已作废':'未作废'}}
            </template>
          </vxe-column>
          <vxe-column  min-width="110px" fixed="right"align="center" title="状态" field="status" >
            <template slot-scope="scope">
              <el-button  type="text" @click="invoiceDetail(scope.row)" :type="$dictUtils.getDictLabel('invoice_status_info', scope.row.status, '-')" effect="dark" size="mini">{{$dictUtils.getDictLabel("invoice_status", scope.row.status, '-')}} </el-button>
            </template>
          </vxe-column>
          <vxe-column min-width="300" title="操作"  fixed="right" align="center">
            <template  slot-scope="scope">
              <div v-if="isAdmin">
                <el-button v-if="(scope.row.status === '5')" type="text"  size="small" @click="editForm(scope.row.id)">修改</el-button>
                <el-button v-if="(scope.row.status === '5')" type="text"   size="small" @click="del(scope.row.id)">删除</el-button>
              </div>
              <div v-else>
              <el-button v-if="hasPermission('cw_finance:invoice:edit')&&scope.row.createBy.id === $store.state.user.id&&(scope.row.status === '1'||scope.row.status === '3')" type="text"  size="small" @click="invoicePush(scope.row)">修改</el-button>
              <el-button v-if="hasPermission('cw_finance:invoice:edit')&&scope.row.createBy.id === $store.state.user.id&&scope.row.status === '2'" type="text"  size="small" @click="invoiceReback(scope.row)">撤回</el-button>
              <el-button v-if="hasPermission('cw_finance:invoice:edit:detail')&&scope.row.status === '5'&&scope.row.receivablesStatus !== '1'" type="text"  size="small" @click="editDetail(scope.row.id)">修改发票明细</el-button>
              <el-button v-if="hasPermission('cw_finance:invoice:edit:receivables')&&scope.row.status === '5'&&scope.row.receivablesStatus !== '1'" type="text"   size="small" @click="view(true, scope.row.id)">收款</el-button>
              <el-button v-if="hasPermission('cw_finance:invoice:edit:is_receivables')&&scope.row.status === '5'&&scope.row.receivablesStatus !== '1'" type="text"   size="small" @click="isReceivables(scope.row)">确认收款</el-button>
              <el-button v-if="hasPermission('cw_finance:invoice:edit:is_receivables')&&scope.row.status === '5'&&scope.row.receivablesStatus === '1'" type="text"   size="small" @click="recallReceivables(scope.row)">撤回收款</el-button>
              <el-button v-if="hasPermission('cw_finance:invoice:edit')&&scope.row.createBy.id === $store.state.user.id&&(scope.row.status === '5'||scope.row.status === '7')" type="text"  size="small" @click="invoiceInvalidPush(scope.row)">作废</el-button>
              <el-button v-if="hasPermission('cw_finance:invoice:edit')&&scope.row.createBy.id === $store.state.user.id&&scope.row.status === '6'" type="text"  size="small" @click="invoiceInvalidReBack(scope.row)">作废撤回</el-button>
              <el-button v-if="hasPermission('cw_finance:invoice:edit')&&scope.row.createBy.id === $store.state.user.id&&(scope.row.status === '1'||scope.row.status === '3')" type="text"   size="small" @click="del(scope.row.id)">删除</el-button>
<!--              审核  发票申请-->
              <el-button v-if="scope.row.status==='2' && checkIsAudit(scope.row)" type="text"  size="small" @click="examine(scope.row)">审核</el-button>
<!--              被驳回后当前申请人重新调整  发票申请-->
              <el-button v-if="scope.row.createBy.id === $store.state.user.id&&scope.row.status === '4'" type="text"  size="small" @click="adjust(scope.row)">驳回调整</el-button>
<!--              审核  发票作废-->
              <el-button v-if="scope.row.status==='6' && checkIsAuditInvalid(scope.row)" type="text"  size="small" @click="examineInvalid(scope.row)">作废审核</el-button>
<!--              被驳回后当前申请人重新调整  发票作废-->
              <el-button v-if="scope.row.createBy.id === $store.state.user.id&&scope.row.status === '8'" type="text"  size="small" @click="adjustInvalid(scope.row)">驳回调整</el-button>
              </div>
            </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>
    <InvoiceForm  ref="invoiceForm" @refreshDataList="refreshList"></InvoiceForm>
    <ProgramPageForm ref="programPageForm" @getProgram="getProgram"></ProgramPageForm>
    <ProgramForm ref="programForm"></ProgramForm>
    <InvoiceUpdateForm ref="invoiceUpdateForm" @refreshDataList="refreshList"></InvoiceUpdateForm>
  </div>
</template>

<script>
  import FinanceInvoiceService from '@/api/cw/invoice/CwFinanceInvoiceService'
  import ProgramForm from './ProgramForm'
  import InvoiceForm from './InvoiceForm'
  import pick from 'lodash.pick'
  import TaskService from '@/api/flowable/TaskService'
  import ProcessService from '@/api/flowable/ProcessService'
  import UserService from '@/api/sys/UserService'
  import UserSelect from '@/components/userSelect'
  import SelectUserTree from '@/views/modules/utils/treeUserSelect'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import ProgramPageForm from '@/views/modules/finance/invoice/ProgramPageForm'
  import InvoiceUpdateForm from './InvoiceUpdateForm'
  export default {
    data () {
      return {
        showHideItem: false,
        showHideIcon: 'el-icon-arrow-down',
        showHideName: '展示',
        searchForm: {
          number: '',
          accountBegin: undefined,
          accountEnd: undefined,
          billingDateList: [],
          billingDateBegin: '',
          billingDateEnd: '',
          remittanceDateList: [],
          remittanceDateBegin: '',
          remittanceDateEnd: '',
          programName: '',
          programId: '',
          reconciliationPeopleName: '',
          operator: '',
          operatorOffice: ''
        },
        dataList: [],
        tablePage: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          orders: []
        },
        loading: false,
        processDefinitionId: '',
        procDefKey: '',
        processDefinitionInvalidId: '',
        procDefInvalidKey: '',
        isAdmin: false
      }
    },
    financeInvoiceService: null,
    taskService: null,
    processService: null,
    userService: null,
    computed: {
      userName () {
        return JSON.parse(localStorage.getItem('user')).name
      }
    },
    created () {
      this.financeInvoiceService = new FinanceInvoiceService()
      this.taskService = new TaskService()
      this.processService = new ProcessService()
      this.userService = new UserService()
    },
    components: {
      InvoiceForm,
      UserSelect,
      SelectUserTree,
      SelectTree,
      ProgramPageForm,
      ProgramForm,
      InvoiceUpdateForm
    },
    mounted () {
      this.refreshList()
    },
    activated () {
      this.refreshList()
    },
    methods: {
      showHide () {
        if (this.showHideItem === false) {
          this.showHideItem = true
          this.showHideIcon = 'el-icon-arrow-up'
          this.showHideName = '隐藏'
        } else {
          this.showHideItem = false
          this.showHideIcon = 'el-icon-arrow-down'
          this.showHideName = '展示'
        }
      },
      // 查询当前用户是否是管理员用户
      checkIsAdmin () {
        this.userService.is().then(({data}) => {
          this.isAdmin = data
        })
      },
      // 新增
      add () {
        this.$refs.invoiceForm.init('add', '')
      },
      editForm (id) {
        this.$refs.invoiceUpdateForm.init('edit', id)
      },
      // 修改发票明细
      editDetail (id) {
        id = id || this.$refs.invoiceTable.getCheckboxRecords().map(item => {
          return item.id
        })[0]
        this.$refs.invoiceForm.init(false, id, true)
      },
      // 查看 flag为true时，弹窗为收款，其他值为查看发票详情
      view (flag, id) {
        this.$refs.invoiceForm.init(flag, id)
      },
      // 查看项目数据
      viewProject (id) {
        this.$refs.programForm.init(id)
      },
      // 获取数据列表
      refreshList () {
        this.loading = true
        if (!this.commonJS.isEmpty(this.searchForm.billingDateList)) {
          if (!this.commonJS.isEmpty(this.searchForm.billingDateList[0]) && !this.commonJS.isEmpty(this.searchForm.billingDateList[1])) {
            this.searchForm.billingDateBegin = this.searchForm.billingDateList[0]
            this.searchForm.billingDateEnd = this.searchForm.billingDateList[1]
          }
        } else {
          this.searchForm.billingDateBegin = ''
          this.searchForm.billingDateEnd = ''
        }
        if (!this.commonJS.isEmpty(this.searchForm.remittanceDateList)) {
          if (!this.commonJS.isEmpty(this.searchForm.remittanceDateList[0]) && !this.commonJS.isEmpty(this.searchForm.remittanceDateList[1])) {
            this.searchForm.remittanceDateBegin = this.searchForm.remittanceDateList[0]
            this.searchForm.remittanceDateEnd = this.searchForm.remittanceDateList[1]
          }
        } else {
          this.searchForm.remittanceDateBegin = ''
          this.searchForm.remittanceDateEnd = ''
        }
        this.financeInvoiceService.list({
          'current': this.tablePage.currentPage,
          'size': this.tablePage.pageSize,
          'orders': this.tablePage.orders,
          ...this.searchForm
        }).then(({data}) => {
          this.dataList = data.records
          this.dataList.forEach(item => {
            item.account = parseFloat(item.account).toFixed(2)
            if (!this.commonJS.isEmpty(item.financeInvoiceBaseDTOList)) {
              let pName = ''
              if (this.commonJS.isNotEmpty(item.financeInvoiceBaseDTOList)) {
                if (item.financeInvoiceBaseDTOList.length === 1) {
                  if (this.commonJS.isEmpty(item.financeInvoiceBaseDTOList[0].programId)) {
                    pName = '其他： '
                  }
                }
              }
              item.financeInvoiceBaseDTOList.forEach((program, index) => {
                if ((index + 1) !== item.financeInvoiceBaseDTOList.length) {
                  pName = pName + program.programName + ','
                } else {
                  pName = pName + program.programName
                }
              })
              item.programName = pName
            } else {
              item.programName = ''
            }
            // if (!this.commonJS.isEmpty(item.financeInvoiceDetailDTOList)) {
            //   item.accountDetail = 0
            //   let num = ''
            //   item.financeInvoiceDetailDTOList.forEach((detail, index) => {
            //     if (!this.commonJS.isEmpty(detail.account)) {
            //       item.accountDetail = parseFloat(parseFloat(item.accountDetail) + parseFloat(detail.account)).toFixed(2)
            //     }
            //     if ((index + 1) !== item.financeInvoiceDetailDTOList.length) {
            //       num = num + detail.number + ','
            //     } else {
            //       num = num + detail.number
            //     }
            //   })
            //   item.number = num
            // } else {
            //   item.number = ''
            //   item.accountDetail = ''
            // }
          })
          this.tablePage.total = data.total
          this.loading = false
        })
        this.checkIsAdmin()
        this.processService.getByName('会计-发票申请').then(({data}) => {
          if (!this.commonJS.isEmpty(data.id)) {
            this.processDefinitionId = data.id
            this.procDefKey = data.key
          }
        })
        this.processService.getByName('会计-发票作废').then(({data}) => {
          if (!this.commonJS.isEmpty(data.id)) {
            this.processDefinitionInvalidId = data.id
            this.procDefInvalidKey = 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()
      },
      // 删除
      del (id) {
        let ids = id || this.$refs.invoiceTable.getCheckboxRecords().map(item => {
          return item.id
        }).join(',')
        this.$confirm(`确定删除所选项吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          this.financeInvoiceService.delete(ids).then(({data}) => {
            this.$message.success(data)
            this.refreshList()
            this.loading = false
          })
        })
      },
      resetSearch () {
        this.searchForm = {
          number: '',
          accountBegin: undefined,
          accountEnd: undefined,
          billingDateList: [],
          billingDateBegin: '',
          billingDateEnd: '',
          remittanceDateList: [],
          remittanceDateBegin: '',
          remittanceDateEnd: '',
          programName: '',
          programId: '',
          reconciliationPeopleName: '',
          operator: '',
          operatorOffice: ''
        }
        this.$refs.searchForm.resetFields()
        this.refreshList()
      },
      start () {
        // 读取流程表单
        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: {
                ...pick(data.data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
                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: '/cw/invoice/InvoiceList'
              }
            })
          })
      },
      // 发起发票申请审批
      invoicePush (row) {
        // 读取流程表单
        let title = `发起流程【会计-发票申请】`
        let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了[会计-发票申请]`
        let status = 'startAndHold'
        if (row.status === '3') {
          status = 'startAndClose'
        } else if (row.status === '4') {
          status = 'reapplyFlag'
        }
        this.taskService.getTaskDef({ procDefId: this.processDefinitionId,
          businessId: row.id,
          businessTable: 'cw_finance_invoice'}).then((data) => {
            this.$router.push({
              path: '/flowable/task/TaskForm',
              query: {
                ...pick(data.data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
                procDefId: this.processDefinitionId,
                procDefKey: this.procDefKey,
                title: title,
                formType: data.data.formType,
                formUrl: data.data.formUrl,
                formTitle: processTitle,
                businessTable: 'finance_invoice',
                businessId: row.id,
                isShow: 'false',
                status: status,
                routePath: '/cw/invoice/InvoiceList'
              }
            })
          })
      },
      // 发起发票作废审批
      invoiceInvalidPush (row) {
        // 读取流程表单
        let title = `发起流程【发票作废】`
        let processTitle = `${this.userName} 发起了 ${row.no} [发票作废]`
        let status = 'startAndHold'
        if (row.status === '7') {
          status = 'startAndClose'
        } else if (row.status === '8') {
          status = 'reapplyFlag'
        }
        this.taskService.getTaskDef({ procDefId: this.processDefinitionInvalidId,
          businessId: row.financeInvoiceInvalidDTO.id,
          businessTable: 'cw_finance_invoice_invalid'}).then((data) => {
            this.$router.push({
              path: '/flowable/task/TaskForm',
              query: {
                ...pick(data.data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
                procDefId: this.processDefinitionInvalidId,
                procDefKey: this.procDefInvalidKey,
                title: title,
                formType: data.data.formType,
                formUrl: data.data.formUrl,
                formTitle: processTitle,
                businessTable: 'cw_finance_invoice_invalid',
                businessId: row.financeInvoiceInvalidDTO.id,
                isShow: 'false',
                status: status,
                routePath: '/cw/invoice/InvoiceList'
              }
            })
          })
      },
      // 查看发票申请审批流程结果
      invoiceDetail (row) {
        if (row.status !== '0' && row.status !== '1') {
          if (row.status === '6' || row.status === '7' || row.status === '8' || row.status === '9') {
            this.invoiceInvalidDetail(row)
          } else {
            this.taskService.getTaskDef({
              procInsId: row.procInsId,
              procDefId: this.processDefinitionId
            }).then(({data}) => {
              this.$router.push({
                path: '/flowable/task/TaskFormDetail',
                query: {
                  ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
                  isShow: 'false',
                  readOnly: true,
                  title: '会计-发票申请' + '流程详情',
                  formTitle: '会计-发票申请' + '流程详情',
                  businessId: row.id,
                  status: 'reback'
                }
              })
            })
          }
        }
      },
      // 查看发票作废审批流程结果
      invoiceInvalidDetail (row) {
        this.taskService.getTaskDef({
          procInsId: row.financeInvoiceInvalidDTO.procInsId,
          procDefId: this.processDefinitionInvalidId
        }).then(({data}) => {
          this.$router.push({
            path: '/flowable/task/TaskFormDetail',
            query: {
              ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
              isShow: 'false',
              readOnly: true,
              title: '发票作废' + '流程详情',
              formTitle: '发票作废' + '流程详情',
              businessId: row.financeInvoiceInvalidDTO.id,
              status: 'reback'
            }
          })
        })
      },
      // 撤回发票申请审批
      invoiceReback (row) {
        this.$confirm(`确定要撤回该申请吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await this.financeInvoiceService.queryById(row.id).then(({data}) => {
            if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
              this.$message.error('数据已发生改变或不存在，请刷新数据')
              this.refreshList()
            } else {
              this.processService.revokeProcIns(row.procInsId).then(async ({data}) => {
                let form = {status: '3', id: row.id}
                await this.financeInvoiceService.updateStatusById(form)
                this.$message.success(data)
                this.refreshList()
              })
            }
          })
        })
      },
      invoiceInvalidReBack (row) {
        this.$confirm(`确定要撤回该申请吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await this.financeInvoiceService.queryById(row.id).then(({data}) => {
            if (data.status !== '6') { // status的值不等于“审核中”，就弹出提示
              this.$message.error('数据已发生改变或不存在，请刷新数据')
              this.refreshList()
            } else {
              this.processService.revokeProcIns(row.financeInvoiceInvalidDTO.procInsId).then(async ({data}) => {
                let form = {status: '5', id: row.id}
                await this.financeInvoiceService.updateStatusById(form)
                this.$message.success(data)
                this.refreshList()
              })
            }
          })
        })
      },
      isReceivables (row) {
        this.$confirm(`确定要确认收款吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let param = {id: row.id, receivablesStatus: '1'}
          this.financeInvoiceService.isReceivables(param).then(({data}) => {
            this.$message.success(data)
            this.refreshList()
          })
        })
      },
      recallReceivables (row) {
        this.$confirm(`确定要撤回收款吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let param = {id: row.id, receivablesStatus: '0'}
          this.financeInvoiceService.isReceivables(param).then(({data}) => {
            this.$message.success(data)
            this.refreshList()
          })
        })
      },
      changeBillingDateList (event) {
        if (this.commonJS.isNotEmpty(this.searchForm.billingDateList)) {
          console.log('event', event)
        }
      },
      openProgramPageForm () {
        this.$refs.programPageForm.init('1', false)
      },
      getProgram (rows) {
        if (this.commonJS.isNotEmpty(rows)) {
          this.searchForm.programName = rows[0].name
          this.searchForm.programId = rows[0].id
        }
      },
      clearProgram () {
        this.searchForm.programName = ''
        this.searchForm.programId = ''
      },
      // 自定义服务端导出
      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.financeInvoiceService.exportFile(params).then((res) => {
          // 将二进制流文件写入excel表，以下为重要步骤
          this.$utils.downloadExcel(res.data, options.filename)
        }).catch(function (err) {
          if (err.response) {
            console.log(err.response)
          }
        })
      },
      // 驳回后调整
      adjust (row) {
        this.financeInvoiceService.queryById(row.id).then(({data}) => {
          if (data.status !== '4') { // status的值不等于“驳回”，就弹出提示
            this.$message.error('数据已发生改变或不存在，请刷新数据')
            this.refreshList()
          } else {
            this.todo(row)
          }
        })
      },
      // 审核
      examine (row) {
        this.financeInvoiceService.queryById(row.id).then(({data}) => {
          if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
            this.$message.error('数据已发生改变或不存在，请刷新数据')
            this.refreshList()
          } else {
            this.todo(row)
          }
        })
      },
      // 审核或重新调整跳转
      todo (row) {
        let cUser = false
        this.taskService.getTaskDefInfo({
          taskId: row.taskId
        }).then(({data}) => {
          this.$router.push({
            path: '/flowable/task/TaskForm',
            query: {
              ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title', 'businessId'),
              isShow: false,
              formReadOnly: true,
              formTitle: `${data.taskName}`,
              cUser: cUser,
              title: `审批【${data.taskName || ''}】`,
              routePath: '/cw/invoice/InvoiceList'   // 数据处理后需要跳转的页面路径
            }
          })
        })
      },
      // 查询当前登录人是否是数据的审核人
      checkIsAudit (row) {
        let loginUserId = this.$store.state.user.id  // 获取当前登录用户id
        if (this.commonJS.isNotEmpty(row.auditUserIds)) {
          for (const userId of row.auditUserIds) {
            if (userId === loginUserId) {  // 当数据的审核人中包含当前登录人id时，返回true
              return true
            }
          }
        }
        return false
      },
      // 驳回后调整
      adjustInvalid (row) {
        this.financeInvoiceService.queryById(row.id).then(({data}) => {
          if (data.status !== '8') { // status的值不等于“驳回”，就弹出提示
            this.$message.error('数据已发生改变或不存在，请刷新数据')
            this.refreshList()
          } else {
            this.todoInvalid(row)
          }
        })
      },
      // 审核
      examineInvalid (row) {
        this.financeInvoiceService.queryById(row.id).then(({data}) => {
          if (data.status !== '6') { // status的值不等于“审核中”，就弹出提示
            this.$message.error('数据已发生改变或不存在，请刷新数据')
            this.refreshList()
          } else {
            this.todoInvalid(row)
          }
        })
      },
      // 审核或重新调整跳转
      todoInvalid (row) {
        let cUser = false
        this.taskService.getTaskDefInfo({
          taskId: row.invalidTaskId
        }).then(({data}) => {
          this.$router.push({
            path: '/flowable/task/TaskForm',
            query: {
              ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title', 'businessId'),
              isShow: false,
              formReadOnly: true,
              formTitle: `${data.taskName}`,
              cUser: cUser,
              title: `审批【${data.taskName || ''}】`,
              routePath: '/cw/invoice/InvoiceList'   // 数据处理后需要跳转的页面路径
            }
          })
        })
      },
      // 查询当前登录人是否是数据的审核人
      checkIsAuditInvalid (row) {
        let loginUserId = this.$store.state.user.id  // 获取当前登录用户id
        if (this.commonJS.isNotEmpty(row.auditUserIdsInvalid)) {
          for (const userId of row.auditUserIdsInvalid) {
            if (userId === loginUserId) {  // 当数据的审核人中包含当前登录人id时，返回true
              return true
            }
          }
        }
        return false
      }
    }
  }
</script>
<style scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
</style>
