<template>
  <div class="page">
    <el-form :inline="true"
			 class="query-form m-b-10"
			 v-if="searchVisible"
			 ref="searchForm"
			 :model="searchForm"
			 @keyup.enter.native="refreshList()"
			 @submit.native.prevent>
      <!-- 搜索框-->
      <el-row :gutter="0">
        <el-form-item prop="no" label="发票申请编号">
          <el-input v-model="searchForm.no" placeholder="请输入发票申请编号" clearable  :style="styles"></el-input>
        </el-form-item>
        <el-form-item prop="number" label="发票号">
          <el-input v-model="searchForm.number" placeholder="请输入发票号" clearable  :style="styles"></el-input>
        </el-form-item>
<!--        <el-form-item prop="programName" label="项目名称">-->
<!--          <el-input  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
            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
            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' :modelValue="searchForm.reconciliationPeopleName" @update:modelValue='(value, label) => {searchForm.reconciliationPeopleName = value}'></UserSelect>-->
			<el-input  v-model="searchForm.reconciliationPeopleName" placeholder="请选择对账人">
				<template #suffix>
					<el-button style="background-color: white;color: #1b1e25;border-color: white;" type="primary" slot="append" icon="el-icon-search" @click="openUserDia1">
					</el-button>
				</template>
			</el-input>
		</el-form-item>
        <el-form-item v-if="showHideItem" label="经办人" prop="operator">
<!--          <UserSelect :limit='1' :modelValue="searchForm.operator" @update:modelValue='(value, label) => {searchForm.operator = value}'></UserSelect>-->
			<el-input  v-model="searchForm.operator" placeholder="请选择经办人">
				<template #suffix>
					<el-button style="background-color: white;color: #1b1e25;border-color: white;" type="primary" slot="append" icon="el-icon-search" @click="openUserDia2">
					</el-button>
				</template>
			</el-input>
		</el-form-item>
        <el-form-item v-if="showHideItem" prop="operatorOffice" label="经办人部门">
          <SelectTree
            ref="officeTree"
            :props="{
                  value: 'id',             // ID字段名
                  label: 'name',         // 显示名称
                  children: 'children'    // 子级字段名
                }"

            :url="`/system-server/sys/office/treeData?type=2`"
            :value="searchForm.operatorOffice"
            :clearable="true"
            :accordion="true"
			size="default"
            @getValue="(value) => {searchForm.operatorOffice=value}"/>
        </el-form-item>
        <el-form-item v-if="showHideItem" prop="billingWorkplaceReal" label="开票单位">
          <el-input v-model="searchForm.billingWorkplaceReal" placeholder="请输入开票单位" clearable  :style="styles"></el-input>
        </el-form-item>
		  <el-form-item v-if="showHideItem" prop="name" label="个人开票姓名">
			  <el-input v-model="searchForm.name" placeholder="请输入个人开票姓名" clearable  :style="styles"></el-input>
		  </el-form-item>

		  <el-form-item v-if="showHideItem" prop="programName" label="开票项目名称">
			  <el-input v-model="searchForm.programName" placeholder="开票项目名称" clearable  :style="styles"></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="/system-server/sys/area/treeData"
            :value="searchForm.reconciliationArea"
            :clearable="true"
            :accordion="true"
			size="default"
            @getValue="(value) => {searchForm.reconciliationArea=value}"/>
        </el-form-item>

        <el-form-item v-if="showHideItem" prop="billingDateList" label="开票日期">
          <el-date-picker
            @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
            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
			  v-if="showHideItem" label="报备类型" prop="reportType">
			  <el-select v-model="searchForm.reportType" placeholder="请选择报备类型" clearable style="width: 100%;">
				  <el-option
					  v-for="item in $dictUtils.getDictList('cw_work_client_report_type')"
					  :key="item.value"
					  :label="item.label"
					  :value="item.value">
				  </el-option>
			  </el-select>
		  </el-form-item>

		  <el-form-item
			  v-if="showHideItem" label="状态" prop="status">
			  <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 100%;">
				  <el-option
					  v-for="item in $dictUtils.getDictList('invoice_status')"
					  :key="item.value"
					  :label="item.label"
					  :value="item.value">
				  </el-option>
			  </el-select>
		  </el-form-item>

        <el-form-item>
          <el-button type="default" @click="showHide" :icon="showHideIcon">{{showHideName}}</el-button>
          <el-button type="primary" @click="refreshList()" icon="el-icon-search">查询</el-button>
          <el-button @click="resetSearch()" icon="el-icon-refresh-right">重置</el-button>
        </el-form-item>
      </el-row>
    </el-form>
    <div class="jp-table top" style="">
      <vxe-toolbar :refresh="{query: refreshList}" ref="toolbarRef" export custom>
        <template #buttons>
          <el-button v-if="hasPermission('cw_finance:invoice:add')" type="primary" icon="el-icon-plus" @click="start()">新建</el-button>
<!--          <el-button v-if="hasPermission('cw_finance:invoice:del')" type="danger"   icon="el-icon-delete" @click="del()" :disabled="$refs.invoiceTable && $refs.invoiceTable.getCheckboxRecords().length === 0" plain>删除</el-button>-->
			<el-button v-if="hasPermission('cw_finance:invoice:import')" type="primary" @click="importFinance()" plain>导入</el-button>
		</template>
		  <template #tools>
			  <vxe-button
				  text
				  type="primary"
				  :title="searchVisible ? '收起检索' : '展开检索'"
				  icon="vxe-icon-search"
				  class="tool-btn"
				  @click="searchVisible = !searchVisible"
			  ></vxe-button>
		  </template>
      </vxe-toolbar>
      <div style="height: calc(100% - 90px)">
        <vxe-table
          border="inner"
          auto-resize
          resizable
          height="auto"
          :loading="loading"
          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: ['xls'],
                    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="60" ></vxe-column>
          <vxe-column min-width="150" title="项目名称" align="center" field="programName">
            <template #default="scope">
              <el-link  type="primary" :underline="false" @click="viewProject(scope.row)">{{scope.row.programName}}</el-link>
            </template>
          </vxe-column>
          <vxe-column min-width="150" title="发票申请编号" align="center" field="no">
            <template #default="scope">
              <el-link  type="primary" :underline="false" @click="view(false, scope.row)">{{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="150" title="报备类型" align="center" field="reportType">
			  <template #default="scope">
				  {{$dictUtils.getDictLabel('cw_work_client_report_type', scope.row.reportType, '')}}
			  </template>
		  </vxe-column>
          <vxe-column min-width="120" title="开票内容" align="center" field="billingContent">
            <template #default="scope">
              {{$dictUtils.getDictLabel('invoice_billing_content', scope.row.billingContent, '')}}
            </template>
          </vxe-column>
          <vxe-column min-width="100" title="收款类型" align="center" field="receivablesType">
            <template #default="scope">
              {{$dictUtils.getDictLabel('invoice_receivables_type', scope.row.receivablesType, '')}}
            </template>
          </vxe-column>
          <vxe-column min-width="100" title="发票类型" align="center" field="type">
            <template #default="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"  align="center" title="是否收款" field="receivablesStatus">
            <template #default="scope">
              {{$dictUtils.getDictLabel('collect_not', scope.row.receivablesStatus, '')}}
            </template>
          </vxe-column>
          <vxe-column min-width="110"  align="center" title="是否作废" field="invalidStatus">
            <template #default="scope">
              {{scope.row.invalidStatus === '1'?'已作废':'未作废'}}
            </template>

          </vxe-column>
          <vxe-column  min-width="110"  align="center" title="状态" field="status" >
            <template #default="scope">
              <el-button @click="invoiceDetail(scope.row)" :type="$dictUtils.getDictLabel('invoice_status_info', scope.row.status, '')" effect="dark" >{{$dictUtils.getDictLabel("invoice_status", scope.row.status, '')}} </el-button>
            </template>
          </vxe-column>
          <vxe-column min-width="110" title="操作"  fixed="right" align="center">
            <template  #default="scope">
              <div v-if="isAdmin">
                <el-button v-if="(scope.row.status === '5')" text type="primary"  @click="editForm(scope.row.id)">修改</el-button>
                <el-button v-if="(scope.row.status === '5')" text type="primary"  @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')" text type="primary" @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'" text type="primary"  @click="invoiceReback(scope.row)">撤回</el-button>
              <el-button v-if="hasPermission('cw_finance:invoice:edit:detail')&&scope.row.status === '5'&&scope.row.receivablesStatus !== '1'" text type="primary"  @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'" text type="primary"  @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'" text type="primary"  @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'" text type="primary" @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')" text type="primary"  @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'" text type="primary" @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')" text type="primary"  @click="del(scope.row.id)">删除</el-button>
<!--              审核  发票申请-->
              <el-button v-if="scope.row.status==='2' && checkIsAudit(scope.row)" text type="primary"  @click="examine(scope.row)">审核</el-button>
<!--              <el-button v-if="scope.row.status==='5' && $store.state.user.officeId==='1602911350533177346'" text type="primary"  @click="examine(scope.row)">审核</el-button>-->
<!--              被驳回后当前申请人重新调整  发票申请-->
              <el-button v-if="scope.row.createBy.id === $store.state.user.id&&scope.row.status === '4'" text type="primary"  @click="adjust(scope.row)">驳回调整</el-button>
<!--              审核  发票作废-->
              <el-button v-if="scope.row.status==='6' && checkIsAuditInvalid(scope.row)" text type="primary"  @click="examineInvalid(scope.row)">作废审核</el-button>
<!--              被驳回后当前申请人重新调整  发票作废-->
              <el-button v-if="scope.row.createBy.id === $store.state.user.id&&scope.row.status === '8'" text type="primary" @click="adjustInvalid(scope.row)">驳回调整</el-button>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
        <vxe-pager
          background
          :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>
	  <ProjectForm ref="projectForm"></ProjectForm>
	  <ReportManagementForm ref="reportManagementForm"></ReportManagementForm>
	  <user-select1 ref="userSelect1" @doSubmit="selectUser1"></user-select1>
	  <user-select2 ref="userSelect2" @doSubmit="selectUser2"></user-select2>
	  <CwFinanceImport ref="cwFinanceImport" @refreshDataList="refreshList"></CwFinanceImport>
  </div>

	<el-dialog title="详情信息" v-model="dialogFormVisible">
		<el-form :model="form">
			<el-row  :gutter="15">
				<el-col :span="21">
					<el-form-item label="详情" prop="programName">
						<el-input :readonly="true" style="width: 100%" type="textarea" maxlength="500" v-model="searchForm.programName" show-word-limit>{{this.searchForm.programName}}</el-input>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
		</div>
	</el-dialog>


</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 SelectTree from '@/components/treeSelect/treeSelect.vue'
  import ProgramPageForm from '@/views/finance/invoice/ProgramPageForm'
  import InvoiceUpdateForm from './InvoiceUpdateForm'
  import ProjectForm from '@/views/cw/projectRecords/ProjectRecordsForm'
  import ReportManagementForm from '@/views/cw/reportManagement/ReportManagementForm'
  import UserSelect1 from '@/views/utils/UserTreeSelect'
  import UserSelect2 from '@/views/utils/UserTreeSelect'
  import CwFinanceImport from "./CwFinanceImport";
  export default {
    data () {
      return {
		  styles:{
			  width : '200px !important'
		  },
	    dialogFormVisible:false,
		searchVisible: true,
        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: '',
		  label:'',
		  loginName:this.$store.state.user.name,
		  reportType:'',
			status:'',
			name:''
        },
        dataList: [],
        tablePage: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          orders: []
        },
        loading: false,
        processDefinitionId: '',
        procDefKey: '',
        processDefinitionInvalidId: '',
        procDefInvalidKey: '',
		  processDefinitionIdPreInvoice: '',
		  procDefKeyPreInvoice: '',
        isAdmin: false,
	    financeInvoiceBaseDTOList:[],
		  recordType:''
      }
    },
    computed: {
      userName () {
        return this.$store.state.user.name
      }
    },
    created () {
    },
    components: {
      InvoiceForm,
      UserSelect,
      SelectTree,
      ProgramPageForm,
      ProgramForm,
      InvoiceUpdateForm,
	  ProjectForm,
		ReportManagementForm,
		UserSelect1,
		UserSelect2,
		CwFinanceImport
    },
    mounted () {
		this.$nextTick(() => {
			//将表格和工具栏进行关联
			const $table = this.$refs.invoiceTable;
			const $toolbar = this.$refs.toolbarRef;
			$table.connect($toolbar);
		})
      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 () {
        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, row) {
        this.$refs.invoiceForm.init(flag, row.id)
      },
      // 查看项目数据
      viewProject (row) {
		console.log(row)
      	if (row.recordType=='1' || row.recordType=='4'){
			this.$refs.projectForm.init('view', row.programId)
		}else if (row.recordType=='2'){
			this.$refs.reportManagementForm.init('view', row.programId, '报告审核单下载')
		}else if (row.recordType=='0'){
			this.dialogFormVisible=true
			this.searchForm.programName=row.programName
		}

      },
      // 获取数据列表
      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 = ''
        }
        financeInvoiceService.list({
          'current': this.tablePage.currentPage,
          'size': this.tablePage.pageSize,
          'orders': this.tablePage.orders,
          ...this.searchForm
        }).then((data) => {
        	console.log('data',data.records)
        	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 = ''
          //   }
          // })
          this.tablePage.total = data.total
          this.loading = false
        })
        this.checkIsAdmin()
        processService.getByName('会计-发票申请').then((data) => {
          if (!this.commonJS.isEmpty(data.id)) {
            this.processDefinitionId = data.id
            this.procDefKey = data.key
          }
        })
        processService.getByName('会计-发票作废').then((data) => {
          if (!this.commonJS.isEmpty(data.id)) {
            this.processDefinitionInvalidId = data.id
            this.procDefInvalidKey = data.key
          }
        })
		  processService.getByName('会计-预开票申请').then((data) => {
			  if (!this.commonJS.isEmpty(data.id)) {
				  this.processDefinitionIdPreInvoice = data.id
				  this.procDefKeyPreInvoice = 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
          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: '',
		  reportType:'',
        }
        this.$refs.searchForm.resetFields()
        this.refreshList()
      },
      start () {
        // 读取流程表单
        let tabTitle = `发起流程【会计-发票申请】`
        let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [会计-发票申请]`
        taskService.getTaskDef({ procDefId: this.processDefinitionId,
          status: 'startAndHold'}).then((data) => {
            this.$router.push({
              path: '/flowable/task/TaskForm',
              query: {
                ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
                procDefId: this.processDefinitionId,
                procDefKey: this.procDefKey,
                status: 'startAndHold',
                title: tabTitle,
                formType: data.formType,
                formUrl: 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'
		  }
		  console.log('row',row)
      	if (this.commonJS.isNotEmpty(row.isPreInvoice) && row.isPreInvoice === '1'){
			taskService.getTaskDef({ procDefId: this.processDefinitionIdPreInvoice,
				businessId: row.id,
				businessTable: 'cw_finance_invoice'}).then((data) => {
				this.$router.push({
					path: '/flowable/task/TaskForm',
					query: {
						...pick(data,  'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
						procDefId: this.processDefinitionIdPreInvoice,
						procDefKey: this.procDefKeyPreInvoice,
						title: title,
						formType: data.formType,
						formUrl: data.formUrl,
						formTitle: processTitle,
						businessTable: 'cw_finance_invoice',
						businessId: row.id,
						isShow: 'false',
						status: status,
						routePath: '/cw/invoice/InvoiceList'
					}
				})
			})
		}else {
			taskService.getTaskDef({ procDefId: this.processDefinitionId,
				businessId: row.id,
				businessTable: 'cw_finance_invoice'}).then((data) => {
				this.$router.push({
					path: '/flowable/task/TaskForm',
					query: {
						...pick(data,  'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
						procDefId: this.processDefinitionId,
						procDefKey: this.procDefKey,
						title: title,
						formType: data.formType,
						formUrl: data.formUrl,
						formTitle: processTitle,
						businessTable: 'finance_invoice',
						businessId: row.id,
						isShow: 'false',
						status: status,
						routePath: '/cw/invoice/InvoiceList'
					}
				})
			})
		}


      },
      // 发起发票作废审批
      invoiceInvalidPush (row) {
      	//预开票项目且与项目下的报告已完成关联则不允许作废
		  financeInvoiceService.getByNo(row.no).then((data)=>{
				if (data){
					this.$message.error('该发票已与预开票项目中的报告关联,无法作废')
					throw new Error('该发票已与预开票项目中的报告关联,无法作废')
				}else {
					// 读取流程表单
					let title = `发起流程【发票作废】`
					let processTitle = `${this.userName} 发起了 ${row.no} [发票作废]`
					let status = 'startAndHold'
					if (row.status === '7') {
						status = 'startAndClose'
					} else if (row.status === '8') {
						status = 'reapplyFlag'
					}
					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, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
								procDefId: this.processDefinitionInvalidId,
								procDefKey: this.procDefInvalidKey,
								title: title,
								formType: data.formType,
								formUrl: 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 {
          	if (this.commonJS.isNotEmpty(row.isPreInvoice) && row.isPreInvoice === '1'){
				taskService.getTaskDef({
					procInsId: row.procInsId,
					procDefId: this.processDefinitionIdPreInvoice
				}).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'
						}
					})
				})
			}else {
				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) {
        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 financeInvoiceService.queryById(row.id).then((data) => {
            if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
              this.$message.error('数据已发生改变或不存在，请刷新数据')
              this.refreshList()
            } else {
              processService.revokeProcIns(row.procInsId).then(async (data) => {
                let form = {status: '3', id: row.id}
                await financeInvoiceService.updateStatusById(form)
                this.$message.success(data)
                this.refreshList()
              })
            }
          })
        })
      },
      invoiceInvalidReBack (row) {
        this.$confirm(`确定要撤回该申请吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await financeInvoiceService.queryById(row.id).then((data) => {
            if (data.status !== '6') { // status的值不等于“审核中”，就弹出提示
              this.$message.error('数据已发生改变或不存在，请刷新数据')
              this.refreshList()
            } else {
              processService.revokeProcIns(row.financeInvoiceInvalidDTO.procInsId).then(async (data) => {
                let form = {status: '5', id: row.id}
                await 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'}
          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'}
          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
        }
      },
	  getProgram1 (rowsType) {
        if (this.commonJS.isNotEmpty(rowsType)) {
          this.searchForm.rowsType = rows[0].rowsType
        }
      },
      clearProgram () {
        this.searchForm.programName = ''
        this.searchForm.programId = ''
      },
	  clearProgram1 () {
        this.searchForm.rowsType = ''
      },
      // 自定义服务端导出
      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 financeInvoiceService.exportFile(params).then((res) => {
          // 将二进制流文件写入excel表，以下为重要步骤
          this.$utils.downloadExcel(res, options.filename+ ".xls")
        }).catch(function (err) {
          if (err.response) {
            console.log(err.response)
          }
        })
      },
      // 驳回后调整
      adjust (row) {
        financeInvoiceService.queryById(row.id).then((data) => {
			console.log('data1', data)
          if (data.status !== '4') { // status的值不等于“驳回”，就弹出提示
            this.$message.error('数据已发生改变或不存在，请刷新数据')
            this.refreshList()
          } else {
            this.todo(row)
          }
        })
      },
      // 审核
      examine (row) {
        financeInvoiceService.queryById(row.id).then((data) => {
          if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
            this.$message.error('数据已发生改变或不存在，请刷新数据')
            this.refreshList()
          } else {
            this.todo(row)
          }
        })
      },
      // 审核或重新调整跳转
      todo (row) {
		  console.log('row.taskId', row.taskId)
        let cUser = false
        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) {
        financeInvoiceService.queryById(row.id).then((data) => {
			console.log('data2', data)
          if (data.status !== '8') { // status的值不等于“驳回”，就弹出提示
            this.$message.error('数据已发生改变或不存在，请刷新数据')
            this.refreshList()
          } else {
            this.todoInvalid(row)
          }
        })
      },
      // 审核
      examineInvalid (row) {
        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
        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
      },
		openUserDia1(){
			this.$refs.userSelect1.init()
		},
		selectUser1(user){
			console.log(user[0].name)
			this.searchForm.reconciliationPeopleName=user[0].name
		},
		openUserDia2(){
			this.$refs.userSelect2.init()
		},
		selectUser2(user){
			console.log(user[0].name)
			this.searchForm.operator=user[0].name
		},
		importFinance(){
			this.$refs.cwFinanceImport.init()
		}


    }
  }
</script>
<style scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
</style>
