<template>
  <div class="app-container form-box" style="padding:20px">
    <el-form ref="form" :model="form" label-width="120px">
      <el-card class="top15 ">
        <div class="table-card">
          <el-row type="flex" justify="space-around">
            <el-col :span="8"></el-col>
            <el-col :span="8" class="formTitle"> {{title}}</el-col>
            <el-col :span="8" style="text-align: right;padding-right: 20px;">
              <BottomBtn :accessId="accessId" :isAuthorised="isAuthorised" @onConfirm="handleBtTottom" />
            </el-col>
          </el-row>
        </div>
        <div class="table-card table-card-content">
          <el-row>
            <el-col :span="12">
              <el-form-item label="单号" prop="claimNo" v-if="$route.query.id">
                <el-input size="small" v-model="form.claimNo" disabled placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="公司名称">
                <CommonName str="cn" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目名称" prop="projectName">
                <el-input :disabled="disabled" size="small" v-model="form.projectName" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="申请人">
                <CommonName str="an" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请部门">
                <CommonName str="apt" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="报销事由" prop="reason" :rules="[{ message: '请输入', required: true, trigger: 'blur'}]">
                <el-input type="textarea" size="small" :disabled="disabled" v-model="form.reason" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注信息" prop="remark">
                <el-input type="textarea" size="small" :disabled="disabled" v-model="form.remark" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="费用归属部门" prop="costDeptId" :rules="[{ message: '请选择', required: true, trigger: 'change'}]">
                <el-cascader clearable v-model="form.costDeptId" :disabled="disabled" filterable class="wd100" :options="deptOptions" :props="$store.getters.newDefaultProps"></el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="附件" prop="files">
                <UploadFile @onUploadFile="handleUpload" :files="fileList" />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 行程信息 -->
          <el-row v-if="$route.query.typeStr == 'business'">
            <el-col :span="24">
              <el-form-item label="行程信息">
                <div class="rode-box">
                  <div class="item-box" v-for="(item,index) in form.expenseClaimTrips" :key="index">
                    <div class="box-tt">
                      <span>行程{{index + 1}}
                        <span v-if="item.tripPartners.length">
                          <el-button icon="el-icon-user" type="text" :disabled="disabled" @click="handleShowFw(item.tripPartners,index)">查看{{item.tripPartners.length}}位同行人</el-button>
                        </span>
                      </span>
                      <span class="delicon" v-if="form.expenseClaimTrips.length >1" @click="handleDelRode(index)"><i class="el-icon-delete"></i></span>
                    </div>
                    <div class="box-content">
                      <el-row class="rw-bt">
                        <el-col :span="12">
                          <el-form-item label="行程时间" :prop="`expenseClaimTrips.${index}.time`" :rules="[{ message: '请选择', required: true, trigger: 'change'}]">
                            <el-date-picker class="wd100" :disabled="disabled" v-model="item.time" size="small" @change="handleTimeChange($event,index)" type="daterange" align="right" start-placeholder="开始日期" end-placeholder="结束日期">
                            </el-date-picker>
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="出差天数" :prop="`expenseClaimTrips.${index}.tripDay`" :rules="[{ message: '请输入', required: true, trigger: 'blur'},{ validator: VerifyFunc.newNumber }]">
                            <el-input-number class="wd100" :disabled="disabled" :controls="false" size="small" v-model="item.tripDay" placeholder="请输入" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="出差类型" :prop="`expenseClaimTrips.${index}.tripType`" :rules="[{ message: '请选择', required: true, trigger: 'change'}]">
                            <el-select v-model="item.tripType" :disabled="disabled" class="wd100" size="small" placeholder="请选择" filterable>
                              <el-option v-for="it of tripTypeList" :key="it.id" :value="it.id" :label="it.label"></el-option>
                            </el-select>
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row class="rw-bt">
                        <el-col :span="12">
                          <el-form-item label="出发地" :prop="`expenseClaimTrips.${index}.departureLocation`" :rules="[{ message: '请选择', required: true, trigger: 'change'}]">
                            <el-cascader size="small" :disabled="disabled" filterable clearable :props="defaultProps" class="wd100" v-model="item.departureLocation" :options="$store.getters.areaTree"></el-cascader>
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item label="目的地" :prop="`expenseClaimTrips.${index}.destinationLocation`" :rules="[{ message: '请选择', required: true, trigger: 'change'}]">
                            <el-cascader size="small" :disabled="disabled" clearable filterable :props="defaultProps" class="wd100" v-model="item.destinationLocation" :options="$store.getters.areaTree"></el-cascader>
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row class="rw-bt">
                        <el-col :span="24">
                          <el-form-item label="行程时间" class="op0">
                            <el-button icon="el-icon-plus" :disabled="disabled" @click="handleAddFw(index)" size="small" plain type="primary"> 添加同行人</el-button>
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </div>
                    <!--  费用列表 -->
                    <div class="item-box" v-for="(nItem,nIndex) in item.expenseClaimDetails" :key="nIndex" style="border: none;">
                      <div class="box-tt">
                        <span>费用{{nIndex + 1}}
                          <el-button icon="el-icon-collection-tag" :disabled="disabled" type="text" @click="handleShowIe(1,index,nIndex)">关联发票</el-button>
                          <span style="margin-left:10px">
                            <el-button type="text">报销规则</el-button>
                          </span>
                        </span>
                        <span class="delicon" :disabled="disabled" v-if="item.expenseClaimDetails.length >1" @click="handleDelAccount(1,index,nIndex)"><i class="el-icon-delete"></i></span>
                      </div>
                      <div class="box-content">
                        <el-row class="rw-bt">
                          <el-col :span="12">
                            <el-form-item label="费用类型" :prop="'expenseClaimTrips.' + index +'.expenseClaimDetails.' + nIndex + '.feeType'" :rules="[{ message: '请输入', required: true, trigger: 'change'}]">
                              <el-select v-model="nItem.feeType" :disabled="disabled" class="wd100" size="small" filterable placeholder="请选择" clearable>
                                <el-option v-for="it of expenseClaimDetails" :key="it.id" :value="it.value" :label="it.label"></el-option>
                              </el-select>
                            </el-form-item>
                          </el-col>
                          <el-col :span="12">
                            <el-form-item label="金额" :prop="'expenseClaimTrips.' + index +'.expenseClaimDetails.' + nIndex + '.amount'" :rules="[{ message: '格式错误', required: true, trigger: 'blur'},{ validator: VerifyFunc.money }]">
                              <el-input-number :disabled="disabled" class="wd100" :controls="false" size="small" v-model="nItem.amount" placeholder="请输入" @blur="hadnleItemAmount($event,index)" />
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row class="rw-bt">
                          <el-col :span="12">
                            <el-form-item label="发票/凭证张数" :prop="'expenseClaimTrips.' + index +'.expenseClaimDetails.' + nIndex + '.invoiceCount'" :rules="[{ message: '请关联', required: true, trigger: 'change'}]">
                              <el-input size="small" disabled v-model="nItem.invoiceCount" @click="handleNum" placeholder="关联发票后自动读取" />
                            </el-form-item>
                          </el-col>
                          <el-col :span="12">
                            <el-form-item label="备注" :prop="'expenseClaimTrips.' + index +'.expenseClaimDetails.' + nIndex + '.remark'">
                              <el-input size="small" :disabled="disabled" v-model="nItem.remark" placeholder="请输入" />
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row class="rw-bt" v-if="nIndex == (item.expenseClaimDetails.length - 1)">
                          <el-col :span="24">
                            <el-form-item label="行程时间" class="op0">
                              <el-button :disabled="disabled" icon="el-icon-plus" @click="handleAddAccount(1,index)" size="small" plain type="primary">添加费用</el-button>
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <!-- 发票信息 -->
                        <el-row v-if="nItem.ieList && nItem.ieList.length">
                          <el-col :span="24">
                            <el-form-item label="发票信息">
                              <el-table stripe border :data="nItem.ieList" ref="oaReimburseFeeitem">
                                <el-table-column label="发票缩略图" align="center" prop="files">
                                  <template v-slot="scope">
                                    <el-image style="width: 10px; height: 10px" @click="handleShowPdf(scope.row.files[0].url)" v-if="scope.row.files && scope.row.files.length && isPdf(scope.row.files[0].url)" :src="scope.row.files && scope.row.files.length ?scope.row.files[0].url : ''" fit="cover"></el-image>
                                    <el-image style="width: 100px; height: 100px" v-else :preview-src-list="filterPreView(scope.row.files)" :src="scope.row.files && scope.row.files.length ?scope.row.files[0].url : ''" fit="cover"></el-image>
                                  </template>
                                </el-table-column>
                                <el-table-column label="发票代码" align="center" prop="invoiceCode" />
                                <el-table-column label="发票号码" align="center" prop="invoiceNum" />
                                <el-table-column label="开票日期" prop="invoiceDate" width="180">
                                  <template v-slot="scope">
                                    <span>{{ parseTime(scope.row.invoiceDate) }}</span>
                                  </template>
                                </el-table-column>
                                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                                  <template v-slot="scope">
                                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(1,scope.row.id,index,nIndex)">删除</el-button>
                                  </template>
                                </el-table-column>
                              </el-table>
                            </el-form-item>
                          </el-col>
                        </el-row>
                      </div>
                    </div>
                    <el-row>
                      <el-col :span="24">
                        <div class="account-box">
                          <el-form-item :prop="`expenseClaimTrips.${index}.amount`" :rules="[{ message: '请输入正整数', required: false, trigger: 'blur'},{ validator: VerifyFunc.money }]">
                            <span style="margin-right:10px">行程{{index+1}}预计费用</span> <span>￥<el-input-number :disabled="disabled" v-model="item.amount" style="width:100px" :controls="false"></el-input-number></span>
                          </el-form-item>
                        </div>
                      </el-col>
                    </el-row>
                  </div>``
                  <div>
                  </div>
                </div>
                <div class="btn-box" @click="handleAddRode" v-if="!disabled">
                  <i class="el-icon-plus" style="color:#1890ff"></i> <span style="color:#1890ff">添加行程信息</span>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 费用列表-->
          <el-row v-if="$route.query.typeStr == 'daily'">
            <el-col :span="24">
              <el-form-item label="费用列表">
                <div class="rode-box">
                  <div class="item-box" v-for="(item,index) in form.expenseClaimDetails" :key="index">
                    <div class="box-tt">
                      <span>费用{{index + 1}}
                        <el-button icon="el-icon-collection-tag" type="text" @click="handleShowIe(2,index)">关联发票</el-button>
                        <span style="margin-left:10px">
                          <el-button type="text">报销规则</el-button>
                        </span>
                      </span>
                      <span class="delicon" v-if="form.expenseClaimDetails.length >1" @click="handleDelAccount(2,index)"><i class="el-icon-delete"></i></span>
                    </div>
                    <div class="box-content">
                      <el-row class="rw-bt">
                        <el-col :span="12">
                          <el-form-item label="费用类型" :prop="`expenseClaimDetails.${index}.feeType`" :rules="[{ message: '请输入', required: true, trigger: 'change'}]">
                            <el-select v-model="item.feeType" :disabled="disabled" class="wd100" size="small" placeholder="请选择" clearable filterable>
                              <el-option v-for="it of expenseClaimDetails" :key="it.id" :value="it.value" :label="it.label"></el-option>
                            </el-select>
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item label="金额" :prop="`expenseClaimDetails.${index}.amount`" :rules="[{ message: '请输入正整数', required: true, trigger: 'blur'},{ validator: VerifyFunc.newNumber }]">
                            <el-input-number class="wd100" :disabled="disabled" :controls="false" size="small" v-model="item.amount" placeholder="请输入" />
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row class="rw-bt">
                        <el-col :span="12">
                          <el-form-item label="发票/凭证张数" :prop="`expenseClaimDetails.${index}.invoiceCount`" :rules="[{ message: '关联发票后自动读取', required: true, trigger: 'change'}]">
                            <el-input size="small" disabled v-model="item.invoiceCount" @click="handleNum" placeholder="请选择" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item label="备注" :prop="`expenseClaimDetails.${index}.remark`" :rules="[{ message: '请选择', required: true, trigger: 'blur'}]">
                            <el-input size="small" :disabled="disabled" v-model="item.remark" placeholder="请输入" />
                          </el-form-item>
                        </el-col>
                      </el-row>

                      <!-- 发票信息 -->
                      <el-row v-if="item.ieList && item.ieList.length">
                        <el-col :span="24">
                          <el-form-item label="发票信息">
                            <el-table stripe border :data="item.ieList" ref="oaReimburseFeeitem">
                              <el-table-column label="发票缩略图" align="center" prop="files">
                                <template v-slot="scope">
                                  <el-image style="width: 100px; height: 100px" :preview-src-list="filterPreView(scope.row.files)" :src="scope.row.files && scope.row.files.length ?scope.row.files[0].url : ''" fit="cover"></el-image>
                                </template>
                              </el-table-column>
                              <el-table-column label="发票代码" align="center" prop="invoiceCode" />
                              <el-table-column label="发票号码" align="center" prop="invoiceNum" />
                              <el-table-column label="开票日期" prop="invoiceDate" width="180">
                                <template v-slot="scope">
                                  <span>{{ parseTime(scope.row.invoiceDate) }}</span>
                                </template>
                              </el-table-column>
                              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                                <template v-slot="scope">
                                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(2,scope.row.id,index)">删除</el-button>
                                </template>
                              </el-table-column>
                            </el-table>
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </div>
                  </div>
                </div>
                <div class="btn-box" @click="handleAddAccount(2)">
                  <i class="el-icon-plus" style="color:#1890ff"></i> <span style="color:#1890ff">添加费用</span>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </el-form>
    <!-- 添加同行人 -->
    <Together :isOpen="tgIsOpen" @onDept="hadnleInitDept" :selectUserIds="selectUserIds" @onCancel="handleTgCl" @onConfirm="handleTgCm" @onList="handleInit" />
    <!-- 展示同行人列表 -->
    <List :isOpen="lsIsOpen" :userList="userList" :selectIds="selectIds" @onCancel="handleLsCl" @onConfirm="handleLsCm" />
    <!-- 打印信息 -->
    <el-dialog :visible.sync="showPrintPage" width='1200px' custom-class="print-dialog" style="height: 98vh;overflow-y: auto;">
      <div style="text-align: right;margin-bottom:10px;">
        <el-button @click="PrintRow" type='primary' size='mini' plain>确认打印</el-button>
      </div>
      <div id="printMe" ref="print" class="print-main">
        <print-html :infoForm='form' :tasks="tasks" :dialogTitle="'报销申请单'" :tripTypeList="tripTypeList" :userList="userList" />
      </div>
    </el-dialog>
    <!-- 添加发票信息 -->
    <AccountList :isOpen="lsAcIsOpen" :selectIds="accountSelectIds" @onCancel="lsAcIsOpen=false" @onConfirm="handleAcCm" />
    <!-- 审批流程信息 -->
    <FlowDialog ref="FlowDialog" :isOpen="showFlow" @onCancel="showFlow = false" @onSetId="handleSetApprovalId" @onTasks="handleTasks" :processInstanceId="form.processInstanceId" />
    <!-- 文件在线预览 -->
    <FilePreview :previewFile="previewFile" :fileUrl="fileUrl" @update="handleFileClose" />
  </div>
</template>

<script>
import { debounce } from 'lodash'
import dayjs from "dayjs";
import { listData } from "@/api/system/dict/data";
import { createExpenseClaim, getExpenseClaim } from "@/api/bs/expenseClaim";
import VerifyFunc from "@/utils/verity";
import { isPdf, truncateDecimal } from '@/utils'
import { getInvoicePage } from "@/api/bs/invoice";
export default {
  name: 'supplierTb',
  components: {
    FilePreview: () => import('@/components/FilePreview'),
    FlowDialog: () => import('@/components/FlowDialog'),
    printHtml: () => import('./printHtml'),
    BottomBtn: () => import('@/components/BottomBtn'),
    UploadFile: () => import('@/components/UploadFile'),
    CommonName: () => import('@/components/CommonName'),
    Together: () => import('../../../components/Together'),
    List: () => import('../../../components/TogetherList'),
    AccountList: () => import('./accountList'),
  },
  created() {
    if (this.$route.query.id) {
      this.handleInitForm(this.$route.query.id)
    }
    this.handleInitList()
  },
  computed: {
    disabled() {
      return !['add', 'edit'].includes(this.$route.query.flag)
    },
    accountSelectIds() {
      let arr = []
      if (this.$route.query.typeStr === 'business') {
        this.form.expenseClaimTrips.forEach(n => n.expenseClaimDetails.forEach(z => {
          z.invoiceIds.forEach(p => {
            arr.push(p)
          })
        }))
      } else {
        this.form.expenseClaimDetails.forEach(z => {
          z.invoiceIds.forEach(p => {
            arr.push(p)
          })
        })
      }
      return arr
    },
    title() {
      return this.$route.query.title
    },
  },
  data() {
    return {
      showFlow: false,
      isAuthorised: false,
      accessId: null,
      tasks: {},
      newDefaultProps: {
        children: "children",
        label: "name",
        value: 'id',
        emitPath: false,
        checkStrictly: true
      },
      deptOptions: [],
      showPrintPage: false,
      selectUserIds: [],
      VerifyFunc,
      defaultProps: {
        children: "children",
        label: "name",
        value: 'id',
        checkStrictly: false
      },
      areaTree: [],
      previewFile: false,
      fileUrl: null,
      mode: null,
      selectIds: [],
      lsIsOpen: false,
      tgIsOpen: false,
      addressList: [],
      tripTypeList: [],
      //上传后的文件列表
      fileList: [],
      form: {
        applyNo: null,
        projectName: null,
        reason: null,
        remark: null,
        costDeptId: null,
        expenseClaimTrips: [
          {
            time: '',
            startTime: null,
            endTime: null,
            departureLocation: null,
            destinationLocation: null,
            tripDay: undefined,
            tripType: null,
            tripPartners: [], // 出差同行人
            amount: undefined,
            expenseClaimDetails: [
              {
                show: false,
                invoiceName: '',
                ieList: this.ieList,
                invoiceIds: [],
                feeType: null,
                amount: undefined,
                invoiceCount: undefined,
                remark: null,
              }
            ]
          }
        ],
        // 日常申请的
        expenseClaimDetails: [
          {
            invoiceIds: [],
            feeType: null,
            amount: undefined,
            invoiceCount: undefined,
            remark: null,
          }
        ]
      },
      isShow: false,
      userList: [],
      index: 0,
      lsAcIsOpen: false,
      expenseClaimDetails: [],
      type: 1,  // 1 行程信息费用列表 2 费用列表
      nIndex: 1, //
    }
  },
  methods: {
    isPdf,
    handleFileClose() {
      this.previewFile = false
    },
    handleShowPdf(url) {
      this.fileUrl = url
      this.previewFile = true
    },
    handleTasks(tasks) {
      this.tasks = tasks
    },
    handleSetApprovalId(id) {
      this.accessId = id
    },
    handleUpload(list) {
      this.fileList = list

    },
    handleBtTottom(val) {
      if (val === 0 || val === 1) {
        this.submitForm(val)
      } else if (val == 2) {
        this.showPrintPage = true
      } else {
        this.showFlow = true
      }
    },
    hadnleItemAmount(e, index) {
      let arr = (this.form.expenseClaimTrips[index].expenseClaimDetails.map(item => Number(item.amount)))
      let total = arr.reduce(function (prev, cur) {
        return prev + cur;
      }, 0);
      this.$set(this.form.expenseClaimTrips[index], 'amount', truncateDecimal(total, 2))
      // console.log('sss', truncateDecimal(total, 2));
    },
    filterPreView(list) {
      return (list || []).map(item => item.url)
    },
    handleShowFw(list, index) {
      this.selectIds = list
      this.index = index
      this.lsIsOpen = true
    },
    handleDelete(type, id, index, nIndex) {
      if (type === 1) {
        let arr = (this.form.expenseClaimTrips[index].expenseClaimDetails[nIndex].ieList || []).filter(item => item.id !== id)
        this.$set(this.form.expenseClaimTrips[index].expenseClaimDetails[nIndex], 'ieList', arr)
        this.$set(this.form.expenseClaimTrips[index].expenseClaimDetails[nIndex], 'invoiceIds', arr.map(item => item.id))
        this.$set(this.form.expenseClaimTrips[index].expenseClaimDetails[nIndex], 'invoiceCount', arr.length ? arr.length : undefined)
        this.$nextTick(() => {
          this.$refs.form.clearValidate([`expenseClaimTrips.${index}expenseClaimDetails.${nIndex}.invoiceCount`])
        })
      } else {
        let arr = (this.form.expenseClaimDetails[index].ieList || []).filter(item => item.id !== id)
        this.$set(this.form.expenseClaimDetails[index], 'ieList', arr)
        this.$set(this.form.expenseClaimDetails[index], 'invoiceIds', arr.map(item => item.id))
        this.$set(this.form.expenseClaimDetails[this.index], 'invoiceCount', arr.length ? arr.length : undefined)
        this.$nextTick(() => {
          this.$refs.form.clearValidate([`expenseClaimDetails.${index}.invoiceCount`])
        })
      }
    },
    handleNum() {
      console.log('32222');
    },
    hadnleInitDept(list) {
      this.deptOptions = list
    },
    PrintRow: debounce(function () { //确认打印档案
      this.$print(this.$refs.print)
    }, 200),
    handlePrint() {
      this.showPrintPage = true
    },
    handleLoop(array) {
      array.forEach(el => {
        if (el.children && !el.children.length) {
          delete el.children
        } else {
          this.handleLoop(el.children)
        }
      });
    },
    handleInitList() {
      listData({
        pageNo: 1,
        pageSize: 50,
        dictType: 'bs_trip_type',
      }).then((res) => {
        this.tripTypeList = res.data.list || []
      })
      listData({
        pageNo: 1,
        pageSize: 50,
        dictType: 'bs_invoice_type',
      }).then((res) => {
        this.expenseClaimDetails = res.data.list || []
      })
    },
    handleTimeChange(val, index) {
      let trips = this.form.expenseClaimTrips
      if (trips.length && val && val.length) {
        // 判断行程时间是否在已经有的时间范围内
        let start1 = dayjs(val[0]);
        let end1 = dayjs(val[1]);
        let range1 = { start: start1, end: end1 };
        for (let i = 0; i < trips.length; i++) {
          let start2 = dayjs(trips[i].time[0]);
          let end2 = dayjs(trips[i].time[1]);
          let range2 = { start: start2, end: end2 };
          if (index !== i && range1.start.isBefore(range2.end) && range2.start.isBefore(range1.end)
          ) {
            this.$set(this.form.expenseClaimTrips[index], 'time', null)
            return this.$modal.msgWarning(`行程时间范围与行程${i + 1}时间范围冲突！`)
          }
        }
      }
      let startTime = val && val.length && dayjs(val[0]).format('YYYY/MM/DD 00:00:00')
      let endTime = val && val.length && dayjs(val[1]).format('YYYY/MM/DD 23:59:59')
      this.$set(this.form.expenseClaimTrips[index], 'startTime', startTime)
      this.$set(this.form.expenseClaimTrips[index], 'endTime', endTime)
      let day = val && val.length && dayjs(val[1]).diff(dayjs(val[0]), 'day')
      this.$set(this.form.expenseClaimTrips[index], 'tripDay', day ? Number(day) + 1 : undefined)
      this.$nextTick(() => {
        this.$refs.form.clearValidate([`expenseClaimTrips.${index}.tripDay`])
      })
    },
    handleOutSubmit() {

    },
    handleLsCl() {
      this.lsIsOpen = false
    },
    handleLsCm(list) {
      this.$set(this.form.expenseClaimTrips[this.index], 'tripPartners', list)
      this.lsIsOpen = false
    },
    handleAcCm(list) {
      if (this.$route.query.typeStr === 'business') {
        let arr = (this.form.expenseClaimTrips[this.index].expenseClaimDetails[this.nIndex]).ieList || []
        list.forEach(n => { arr.push(n) })
        this.$set(this.form.expenseClaimTrips[this.index].expenseClaimDetails[this.nIndex], 'ieList', arr)
        this.$set(this.form.expenseClaimTrips[this.index].expenseClaimDetails[this.nIndex], 'invoiceIds', (arr || []).map(item => item.id))
        this.$set(this.form.expenseClaimTrips[this.index].expenseClaimDetails[this.nIndex], 'invoiceCount', arr.length)
        this.$nextTick(() => {
          this.$refs.form.clearValidate([`expenseClaimTrips.${this.index}.expenseClaimDetails.${this.nIndex}.invoiceCount`])
        })
      } else {
        let arr = (this.form.expenseClaimDetails[this.index]).ieList || []
        list.forEach(n => { arr.push(n) })
        this.$set(this.form.expenseClaimDetails[this.index], 'ieList', arr)
        this.$set(this.form.expenseClaimDetails[this.index], 'invoiceIds', (arr || []).map(item => item.id))
      }
      this.lsAcIsOpen = false
    },
    handleShowIe(type, index, nIndex) {
      if (this.disabled) {
        return
      }
      // this.selectIds = list
      this.index = index
      this.nIndex = nIndex
      this.type = type
      this.lsAcIsOpen = true
    },
    handleInit(list) {
      this.userList = list
    },
    handleTgCl() {
      this.tgIsOpen = false
    },
    handleTgCm(list) {
      let flag = (list.filter(item => this.selectUserIds.includes(item)) || [])
      if (flag.length) {
        const { username } = this.userList.find(item => item.id === flag[0])
        this.$modal.msgError(`同行人${username}已经被添加，请勿重复添加！`);
      } else {
        list.forEach(v => {
          this.form.expenseClaimTrips[this.index].tripPartners.push(v)
        })
        this.tgIsOpen = false
      }
    },
    handleAddFw(index) {
      this.index = index
      this.tgIsOpen = true
      this.selectUserIds = this.form.expenseClaimTrips[index].tripPartners
    },
    handleDelRode(index) {
      if (this.disabled) {
        return
      }
      this.form.expenseClaimTrips.splice(index, 1)
    },
    handleDelAccount(type, index, nIdx) {
      if (this.disabled) {
        return
      }
      if (type === 1) {
        this.form.expenseClaimTrips[index].expenseClaimDetails.splice(nIdx, 1)
      } else {
        this.form.expenseClaimDetails.splice(index, 1)
      }
    },
    handleAddRode() {
      if (this.disabled) {
        return
      }
      this.form.expenseClaimTrips.push({
        time: '',
        startTime: null,
        endTime: null,
        departureLocation: null,
        destinationLocation: null,
        tripDay: undefined,
        tripType: null,
        tripPartners: [], // 出差同行人
        amount: undefined,
        expenseClaimDetails: [
          {
            show: false,
            invoiceName: '',
            ieList: this.ieList,
            invoiceIds: [],
            feeType: null,
            amount: undefined,
            invoiceCount: undefined,
            remark: null,
          }
        ]
      })
    },
    handleAddAccount(type, index) {
      if (this.disabled) {
        return
      }
      if (type === 1) {
        this.form.expenseClaimTrips[index].expenseClaimDetails.push({
          invoiceIds: [],
          feeType: null,
          amount: undefined,
          invoiceCount: undefined,
          remark: null,
        })
      } else {
        this.form.expenseClaimDetails.push({
          invoiceIds: [],
          feeType: null,
          amount: undefined,
          invoiceCount: undefined,
          remark: null,
        })
      }
    },
    //上传文件的事件
    uploadFile(item) {
      //上传文件的需要formdata类型;所以要转
      let FormDatas = new FormData()
      FormDatas.append('file', item.file);
      FormDatas.append('path', item.file.name);
      this.$modal.loading("正在上传，请稍候...");
      uploadFileApi(FormDatas).then((res) => {
        this.fileList.push({ name: item.file.name, url: res.data });//成功过后手动将文件添加到展示列表里
        if (this.fileList.length > 0) {//如果上传了附件就把校验规则给干掉
          this.fileflag = false;
        }
        this.$modal.closeLoading()
      })
    },
    //上传了的文件给移除的事件，由于我没有用到默认的展示，所以没有用到
    handleRemove() {
    },
    //这是我自定义的移除事件
    handleClose(i) {
      this.fileList.splice(i, 1);//删除上传的文件
      if (this.fileList.length == 0) {//如果删完了
        this.fileflag = true;//显示url必填的标识
        // this.$set(this.demoObj.url, 0, { required: true, validator: this.validatorUrl, trigger: 'blur' })//然后动态的添加本地方法的校验规则
      }
    },
    handleBack() {
      history.back()
    },
    handleInitForm(id) {
      this.processInstanceLoading = true
      getExpenseClaim(id).then(response => {
        // 获取所有发票
        getInvoicePage({
          pageNo: 1,
          pageSize: 100,
        }).then((newS) => {
          let invoceList = response.data.list || []
          this.form = response.data || {};
          if (this.$route.query.typeStr === 'business') {
            this.form.expenseClaimTrips = this.form.expenseClaimTrips.map((item) => {
              return {
                ...item,
                departureLocation: Number(item.departureLocation),
                destinationLocation: Number(item.destinationLocation),
                tripType: Number(item.tripType),
                time: [new Date(dayjs(item.startTime).format('YYYY/MM/DD HH:mm:ss')), new Date(dayjs(item.startTime).format('YYYY/MM/DD HH:mm:ss'))],
                expenseClaimDetails: (item.expenseClaimDetails || []).map(item => {
                  return {
                    ...item,
                    ieList: invoceList.filter(nItem => nItem.invoiceIds.includes(nItem.id)) || []
                  }
                })
              }
            })
          } else {
            this.form.expenseClaimDetails = (this.form.expenseClaimDetails || []).map(item => {
              return {
                ...item,
                ieList: invoceList.filter(nItem => nItem.invoiceIds.includes(nItem.id)) || []
              }
            })
          }
          this.fileList = this.form.files || []
          this.$nextTick(() => {
            this.form.processInstanceId && this.$refs.FlowDialog.getDetail(this.form.processInstanceId)
          })
          this.isAuthorised = this.form.isAuthorised
        })
      });
    },
    submitForm(type) {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 添加/修改的提交
        let newForm = {
          ...this.form,
          billType: this.$route.query.typeStr == 'business' ? 'CLBX' : 'RCBX',
          status: type,
          files: this.fileList,
          expenseClaimTrips: (this.form.expenseClaimTrips || []).map(
            item => {
              return {
                ...item,
                departureLocation: Array.isArray(item.departureLocation) ? item.departureLocation[item.departureLocation.length - 1] : item.departureLocation,
                destinationLocation: Array.isArray(item.destinationLocation) ? item.destinationLocation[item.destinationLocation.length - 1] : item.destinationLocation,
                startTime: dayjs(item.startTime).valueOf(),
                endTime: dayjs(item.endTime).valueOf()
              }
            }
          )
        }
        if (this.$route.query.typeStr === 'daily') {
          delete newForm.expenseClaimTrips
        } else {
          delete newForm.expenseClaimDetails
        }
        this.$modal.loading("正在提交，请稍候...");
        createExpenseClaim(newForm).then(response => {
          this.$modal.closeLoading()
          this.$modal.msgSuccess(`${this.form.id ? '修改成功!' : '新增成功!'}`);
          history.back()
        }).catch(() => {
          this.$modal.closeLoading()
        })
      });
    },
    cancel() {
      this.$emit('onCancel')
    },
  }
}
</script>
<style lang="scss" scoped>
@import '@/assets/styles/form/index.scss';
.my-process-designer {
  background: #fff !important;
}
</style>