<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item prop="date">
        <el-date-picker
          v-model="queryParams.params.date"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="subject">
        <el-select v-model="queryParams.params.subject" placeholder="请选择科目" clearable>
          <el-option
            v-for="dict in dict.type.voucher_subject_1"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="producer">
        <el-select style="width: 150px" v-model="queryParams.producer" placeholder="请选择制单人" clearable>
          <el-option
            v-for="item in createByOptions"
            :key="item.userId"
            :label="item.userName"
            :value="item.userName"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="凭证号" prop="subject">
        <el-input
          v-model="queryParams.params.startCode"
          clearable
          style="width: 100px"
        />
        至
        <el-input
          style="width: 100px"
          v-model="queryParams.params.endCode"
          clearable
        />
      </el-form-item>
      <el-form-item prop="summary" width="35px">
        <el-input
          v-model="queryParams.params.summary"
          placeholder="请输入摘要"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['buyer:auxiliaryvoucher:add']"
        >新增凭证
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-upload ref="importForm"
                   :action="importForm.url"
                   multiple
                   :show-file-list="false"
                   :before-upload="handleBeforeUpload"
                   :headers="importForm.headers"
                   :on-success="uploadSuccess"
        >
          <el-button
            type="primary"
            size="mini"
            @click="importData"
          >导入EXCEL
          </el-button>
        </el-upload>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          @click="downTemplate"
          v-hasPermi="['buyer:auxiliaryvoucher:export']"
        >下载EXCEL模板
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['buyer:auxiliaryvoucher:remove']"
        >批量删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table stripe :show-header="false" v-loading="loading" :data="auxiliaryvoucherList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" />
      <el-table-column>
        <template slot-scope="scope">
          <div style="border: 1px solid rgba(214, 214, 214, 1);background-color: #f8f8f9;">
            <el-row style="margin-left: 10px; padding-top: 10px; height: 35px">
              <el-col :span="4">
                日期：{{ scope.row.date }}
              </el-col>
              <el-col :span="4">
                <span style="float: left">凭证字号：</span>
                <dict-tag style="float: left" :options="dict.type.voucher_type" :value="scope.row.type" />
                -{{ scope.row.code }}
              </el-col>
              <el-col :span="4">
                附件：{{ scope.row.buyerFileInfos.length }}
              </el-col>
              <el-col :span="4">
                制单人：{{ scope.row.producer }}
              </el-col>
              <el-col :span="4">
                关联项目：{{ scope.row.buyerVoucherProjects.length }}
              </el-col>
              <el-col :span="4">
                <span style="float: left">支出类型：</span>
                <dict-tag style="float: left" :options="dict.type.voucher_expense_type" :value="scope.row.expenseType" />
              </el-col>
            </el-row>
            <el-table stripe show-summary v-loading="loading" :data="scope.row.buyerVoucherInfos">
              <el-table-column label="摘要信息" align="center" prop="summary" />
              <el-table-column label="科目名称1" align="center" prop="subject1">
                <template slot-scope="scope1">
                  <dict-tag :options="dict.type.voucher_subject_1" :value="scope1.row.subject1" />
                </template>
              </el-table-column>
              <el-table-column label="科目名称2" align="center" prop="subject2">
                <template slot-scope="{row}">
                  <dict-tag v-if="row.subject1 == 'type1'" :options="dict.type.voucher_subject_2" :value="row.subject2" />
                  <span v-else>{{ row.subject2 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="借方余额" align="center" prop="debitBalance" />
              <el-table-column label="贷方余额" align="center" prop="creditBalance" />
            </el-table>

            <el-row style="padding: 10px 0px 10px 0px">
              <el-col :span="1.5" :offset="18">
                <el-button v-if="scope.row.buyerVoucherProjects.length > 0"
                           type="primary"
                           size="mini"
                           @click="handleViewProject(scope.row)"
                >查看关联详情
                </el-button>
                <el-button v-else
                           type="primary"
                           size="mini"
                           @click="handleAddProject(scope.row)"
                >关联项目
                </el-button>
              </el-col>
              <el-col :span="1.5" style="margin-left: 10px">
                <el-button
                  type="info"
                  plain
                  size="mini"
                  @click="handleView(scope.row)"
                >查看
                </el-button>
              </el-col>
              <el-col :span="1.5" style="margin-left: 10px">
                <el-button
                  type="info"
                  plain
                  size="mini"
                  @click="handleCopy(scope.row)"
                >复制
                </el-button>
              </el-col>
              <el-col :span="1.5" style="margin-left: 10px">
                <el-button
                  type="danger"
                  plain
                  icon="el-icon-delete"
                  size="mini"
                  @click="handleSingleDelete(scope.row.id)"
                >删除
                </el-button>
              </el-col>
            </el-row>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改辅助帐凭证对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="100%" append-to-body>
      <el-form :model="form" ref="form" :rules="rules" size="small" :inline="true" v-show="showSearch">
        <el-form-item prop="type">
          <el-select v-if="isEditVoucherInfo" v-model="form.type">
            <el-option
              v-for="dict in dict.type.voucher_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
          <div v-else>
            <div v-for="dict in dict.type.voucher_type" :key="dict.value">
              <span v-if="dict.value == form.type">{{ dict.label }}</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item prop="code" style="width: 90px;">
          <el-row>
            <el-col :span="20">
              <el-input v-if="isEditVoucherInfo" v-model="form.code" />
              <span v-else>{{ form.code }}</span>
            </el-col>
            <el-col :span="4">号</el-col>
          </el-row>
        </el-form-item>
        <el-form-item prop="date" style="margin-left: 20px">
          <el-date-picker v-if="isEditVoucherInfo" clearable
                          v-model="form.date"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择日期"
          >
          </el-date-picker>
          <span v-else>{{ form.date }}</span>
        </el-form-item>
        <el-form-item label="附单据:" prop="accessoryNumber" style="margin-left: 20px">
          <el-row>
            <el-col :span="4">{{ fileList.length }}</el-col>
            <el-col :span="4">张</el-col>
            <el-col :span="16">
              <el-button type="primary" style="margin-left: 10px;" @click="openFileList">添加附件</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="制单人:" prop="producer" style="margin-left: 20px">
          <el-select v-if="isEditVoucherInfo" v-model="form.producer" placeholder="请选择制单人" clearable>
            <el-option
              v-for="item in createByOptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userName"
            >
            </el-option>
          </el-select>
          <span v-else>{{ form.producer }}</span>
        </el-form-item>
        <el-form-item label="支出类型:" prop="expenseType" style="margin-left: 20px">
          <el-select v-if="isEditVoucherInfo" v-model="form.expenseType" placeholder="请选择支出类型">
            <el-option
              v-for="dict in dict.type.voucher_expense_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
          <div v-else>
            <div v-for="dict in dict.type.voucher_expense_type" :key="dict.value">
              <span v-if="dict.value == form.expenseType">{{ dict.label }}</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button v-if="isEditVoucherInfo" type="primary" @click="submitForm">保 存</el-button>
          <el-button v-if="!isEditVoucherInfo && form.buyerVoucherProjects && form.buyerVoucherProjects.length > 0"
                     type="primary"
                     size="mini"
                     @click="handleViewProject(form)"
          >查看关联项目
          </el-button>
          <el-button v-if="!isEditVoucherInfo && form.buyerVoucherProjects && form.buyerVoucherProjects.length == 0"
                     type="primary"
                     size="mini"
                     @click="handleAddProject(form)"
          >关联项目
          </el-button>
          <el-button @click="cancel">取 消</el-button>
        </el-form-item>
      </el-form>

      <el-row>
        <el-col :span="1" style="float: right" v-if="isEditVoucherInfo">
          <el-button type="primary" icon="el-icon-circle-plus" circle style="margin-left: 10px;padding-bottom: 10px" @click="clickAddVoucher"></el-button>
          <el-button type="primary" icon="el-icon-remove" circle style="margin-top: 10px" @click="clickDeleteVoucher" :disabled="multiple1"></el-button>
        </el-col>
        <el-col :span="23">
          <el-table
            show-summary
            @selection-change="handleSelectionChange1"
            :data="voucherTableData"
            style="width: 100%"
          >
            <el-table-column v-if="isEditVoucherInfo" type="selection" align="center" />
            <el-table-column label="摘要信息" align="center" prop="summary">
              <template slot-scope="{row ,$index}">
                <div v-if="row.isEdit">
                  <el-input v-model="row.summary" placeholder="请输入摘要信息" clearable />
                </div>
                <div v-else>{{ row.summary }}</div>
              </template>
            </el-table-column>
            <el-table-column label="科目名称1" align="center" prop="subject1">
              <template slot-scope="{row ,$index}">
                <div v-if="row.isEdit">
                  <el-select v-model="row.subject1" placeholder="请选择科目" clearable>
                    <el-option
                      v-for="dict in dict.type.voucher_subject_1"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </div>
                <div v-else>
                  <dict-tag :options="dict.type.voucher_subject_1" :value="row.subject1" />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="科目名称2" align="center" prop="subject2">
              <template slot-scope="{row ,$index}">
                <div v-if="row.isEdit">
                  <el-select v-if="row.subject1 == 'type1'" v-model="row.subject2" placeholder="请选择科目" clearable>
                    <el-option
                      v-for="dict in dict.type.voucher_subject_2"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                  <el-select v-if="row.subject1 == 'type2'" default-first-option filterable
                             allow-create v-model="row.subject2" placeholder="请选择科目" clearable
                  >
                    <el-option label="工资、奖金、津贴和补贴" value="工资、奖金、津贴和补贴" />
                    <el-option label="社会保险费" value="社会保险费" />
                    <el-option label="住房公积金" value="住房公积金" />
                  </el-select>
                  <el-input v-if="row.subject1 !== 'type1' && row.subject1 !== 'type2'" v-model="row.subject2"
                            placeholder="请输入科目" clearable
                  />
                </div>
                <div v-else>
                  <dict-tag :options="dict.type.voucher_subject_2" :value="row.subject2" />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="借方余额" align="center" prop="debitBalance">
              <el-table-column prop="debitUnit1" label="亿" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.debitUnit1" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.debitUnit1 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="debitUnit2" label="千万" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.debitUnit2" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.debitUnit2 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="debitUnit3" label="百万" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.debitUnit3" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.debitUnit3 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="debitUnit4" label="十万" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.debitUnit4" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.debitUnit4 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="debitUnit5" label="万" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.debitUnit5" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.debitUnit5 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="debitUnit6" label="千" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.debitUnit6" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.debitUnit6 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="debitUnit7" label="百" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.debitUnit7" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.debitUnit7 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="debitUnit8" label="十" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.debitUnit8" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.debitUnit8 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="debitUnit9" label="元" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.debitUnit9" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.debitUnit9 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="debitUnit10" label="角" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.debitUnit10" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.debitUnit10 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="debitUnit11" label="分" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.debitUnit11" />
                  </div>
                  <div v-else>{{ row.debitUnit11 }}</div>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="贷方余额" align="center" prop="creditBalance">
              <el-table-column prop="creditUnit1" label="亿" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.creditUnit1" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.creditUnit1 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="creditUnit2" label="千万" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.creditUnit2" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.creditUnit2 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="creditUnit3" label="百万" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.creditUnit3" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.creditUnit3 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="creditUnit4" label="十万" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.creditUnit4" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.creditUnit4 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="creditUnit5" label="万" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.creditUnit5" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.creditUnit5 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="creditUnit6" label="千" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.creditUnit6" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.creditUnit6 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="creditUnit7" label="百" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.creditUnit7" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.creditUnit7 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="creditUnit8" label="十" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.creditUnit8" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.creditUnit8 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="creditUnit9" label="元" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.creditUnit9" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.creditUnit9 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="creditUnit10" label="角" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.creditUnit10" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.creditUnit10 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="creditUnit11" label="分" width="60">
                <template slot-scope="{row ,$index}">
                  <div v-if="row.isEdit">
                    <el-input v-model="row.creditUnit11" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'').slice(0, 1)" />
                  </div>
                  <div v-else>{{ row.creditUnit11 }}</div>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-dialog>

    <!-- 添加或修改辅助帐凭证对话框 -->
    <el-dialog :title="projectTitle" :visible.sync="projectOpen" width="50%" append-to-body>
      <div v-if="!projectNextOpen">
        <el-form size="small">
          <el-form-item prop="type" label="选择关联项目：">
            <el-select v-model="selectProjectList"
                       multiple
                       collapse-tags
                       style="margin-left: 20px;"
            >
              <el-option
                v-for="project in projectList"
                :key="project.id"
                :label="project.name"
                :value="project.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="type" label="已选择项目：">
            <div v-for="(project,i) in projectList" :key="i">
              <div v-for="id in selectProjectList" :key="id">
              <span style="float: left;border-width: 1px;border-style: solid;
              border-color: rgba(44, 140, 240, 1);border-radius: 4px;
              margin-left: 10px;" v-if="project.id == id"
              >
                <span style="margin-left: 10px;margin-right: 10px;">{{ project.name }}</span>
              </span>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="projectNext">下一步</el-button>
          <el-button @click="projectCancel">取 消</el-button>
        </div>
      </div>
      <div v-else>
        <el-tabs v-model="activeName">
          <el-tab-pane
            v-for="(item,index) in selectVoucherProjectList"
            :label="item.subjectLabel"
            :name="item.subject"
            :key="index"
          >
            <el-form :model="projectForm" ref="projectForm" size="small">
              <el-form-item prop="projectFormType" label="分摊方式：">
                <el-radio v-model="item.projectFormType" label="1">自动</el-radio>
                <el-radio v-model="item.projectFormType" label="2">手动</el-radio>
              </el-form-item>
            </el-form>
            <el-table stripe :data="item.buyerVoucherProjects">
              <el-table-column prop="projectName" label="项目名称"></el-table-column>
              <el-table-column prop="proportion" label="占比（%）">
                <template slot-scope="{row ,$index}">
                  <span v-if="item.projectFormType == '1'">{{ row.proportion }}</span>
                  <el-input v-if="item.projectFormType == '2'" v-model="row.proportion" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'')"
                    @blur="row.price = (row.balance * $event.target.value / 100).toFixed(2)"/>
                </template>
              </el-table-column>
              <el-table-column prop="price" label="金额">
                <template slot-scope="{row ,$index}">
                  <span v-if="item.projectFormType == '1'">{{ row.price }}</span>
                  <el-input v-if="item.projectFormType == '2'" v-model="row.price" onkeyup="value=value.replace(/^[^0-9]|[^\d]+/g,'')" />
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <el-row>
          <el-col :span="24">
            <span style="color: red;">提示：提交后不可修改，请谨慎操作！</span>
          </el-col>
        </el-row>
        <div slot="footer" class="dialog-footer" style="margin-top: 30px;margin-left: 40%">
          <el-button type="primary" @click="submitProjectData">提交</el-button>
          <el-button @click="projectCancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 关联项目明细对话框详情 -->
    <el-dialog title="关联项目明细" :visible.sync="viewProjectOpen" width="50%" append-to-body>
      <el-tabs v-model="activeName">
        <el-tab-pane v-for="(item,index) in selectVoucher.buyerVoucherProjects"
                     :label="item.subjectLabel"
                     :name="item.subject"
                     :key="index"
        >
          <el-table stripe :data="item.buyerVoucherProjects">
            <el-table-column prop="projectId" label="项目名称">
              <template slot-scope="{row ,$index}">
                <div v-for="(project,i) in projectList" :key="i">
              <span v-if="project.id == row.projectId">
                {{ project.name }}
              </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="proportion" label="占比（%）"></el-table-column>
            <el-table-column prop="price" label="金额"></el-table-column>
          </el-table>
          <el-row v-if="viewProjectOpen && item.buyerVoucherProjects" style="margin-top: 20px; margin-left: 20px">
            <el-col :span="24">
              <span>操作人：{{ item.buyerVoucherProjects[0].createBy }}</span>
              <span style="margin-left: 35px">时间：{{ item.buyerVoucherProjects[0].createTime }}</span>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 文件列表对话框详情 -->
    <el-dialog title="上传文件" :visible.sync="fileListOpen" width="50%" append-to-body>
      <el-upload
        ref="fileUpload"
        class="upload-demo"
        :action="uploadUrl"
        multiple
        :headers="headers"
        :on-error="handleUploadError"
        :on-success="handleUploadSuccess"
        :show-file-list="false"
        :file-list="fileList"
      >
        <el-button
          type="success"
          plain
          icon="el-icon-upload2"
          size="mini"
        >选择文件
        </el-button>
      </el-upload>

      <el-table stripe :data="fileList" style="padding-top: 20px">
        <el-table-column prop="fileAddr" label="名称"></el-table-column>
        <el-table-column label="时间" align="center" prop="createTime" width="180"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleDownLoad(scope.row)"
            >下载
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleFileDelete(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer" style="margin-top: 30px;margin-left: 40%">
        <el-button type="primary" @click="submitFileInfo">提交</el-button>
        <el-button @click="fileListOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAuxiliaryvoucher, getAuxiliaryvoucher, delAuxiliaryvoucher, addAuxiliaryvoucher, updateAuxiliaryvoucher, updateFileInfos } from '@/api/buyer/auxiliaryvoucher'
import { listUser, getUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus, deptTreeSelect } from '@/api/system/user'
import { listProject, getProject, delProject, addProject, updateProject } from '@/api/buyer/project'
import { listVoucherProject, getVoucherProject, delVoucherProject, addBatchVoucherProject, addVoucherProject, updateVoucherProject } from '@/api/buyer/voucherproject'
import { getToken } from '@/utils/auth'
import download from '@/plugins/download'

export default {
  name: 'Auxiliaryvoucher',
  dicts: ['voucher_type', 'voucher_expense_type', 'voucher_subject_1', 'voucher_subject_2'],
  data() {
    return {
      // 操作人列表
      createByOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 选中数组
      ids1: [],
      // 非单个禁用
      single1: true,
      // 非多个禁用
      multiple1: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 辅助帐凭证表格数据
      auxiliaryvoucherList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      projectTitle: '',
      // 是否显示弹出层
      projectOpen: false,
      // 是否显示弹出层
      viewProjectOpen: false,
      // 是否显示弹出层
      projectNextOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        remarks: null,
        deptId: null,
        code: null,
        type: null,
        date: null,
        accessoryNumber: null,
        producer: null,
        expenseType: null,
        balance: null,
        status: null,
        params: { date: [] }
      },
      // 表单参数
      form: {},
      // 表单参数
      projectForm: {},
      // 表单校验
      rules: {
        type: [{ required: true, message: '凭证号类型不能为空', trigger: 'blur' }],
        code: [{ required: true, message: '凭证号不能为空', trigger: 'blur' }],
        date: [{ required: true, message: '日期不能为空', trigger: 'blur' }],
        producer: [{ required: true, message: '制单人不能为空', trigger: 'blur' }],
        expenseType: [{ required: true, message: '支出类型不能为空', trigger: 'blur' }]
      },

      /** 新增凭证列表 */
      voucherTableData: [],

      // 立项管理表格数据
      projectList: [],

      // 当前选择的凭证
      selectVoucher: {},

      // 选择的项目id列表
      selectProjectList: [],

      // 是否可编辑
      isEditVoucherInfo: false,

      // 选择的tabname
      activeName: '',

      // 关联项目数组
      selectVoucherProjectList: [],

      fileList: [],
      uploadUrl: process.env.VUE_APP_BASE_API + '/common/upload',
      headers: {
        Authorization: 'Bearer ' + getToken()
      },

      // 是否显示上传列表
      fileListOpen: false,

      // 导入表单参数
      importForm: {
        // 上传的地址,这个地方写自己的后台地址
        url: process.env.VUE_APP_BASE_API + '/buyer/auxiliaryvoucher/importTable',
        headers: { 'Authorization': 'Bearer ' + getToken() },
        ContentType: 'application/json'
      }
    }
  },

  created() {
    this.getList()
    this.getListUser()
    this.getListProject()
  },

  methods: {
    handleBeforeUpload(file){
      const uploadTypes = ['xlsx']
      const filetype = file.name.replace(/.+\./, '')

      if (uploadTypes.indexOf(filetype.toLowerCase()) === -1) {
        this.$message.warning({
          message: '请上传后缀名为xlsx的表格文件'
        })
        return false
      }

      return true
    },
    uploadSuccess(response, file, fileList){
      if(response.code == 200 && response.data != 0){
        this.handleQuery();
      }else{
        this.$message.warning({
          message: '没有读取到有效数据，请检查文件数据！'
        })
      }
    },
    /** 查询员工列表 */
    getListUser() {
      listUser(null).then(response => {
          this.createByOptions = response.rows
        }
      )
    },

    /** 查询項目列表 */
    getListProject() {
      listProject(null).then(response => {
        this.projectList = response.rows
      })
    },

    /** 查询辅助帐凭证列表 */
    getList() {
      this.loading = true
      if (this.queryParams.params.date) {
        this.queryParams.params.startDate = this.queryParams.params.date[0]
        this.queryParams.params.endDate = this.queryParams.params.date[1]
      }
      listAuxiliaryvoucher(this.queryParams).then(response => {
        this.auxiliaryvoucherList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 取消按钮
    projectCancel() {
      this.projectOpen = false
      this.projectReset()
    },

    projectReset() {// 表单重置
      this.selectProjectList = []
      this.projectNextOpen = false
      this.projectForm = []
      this.selectVoucherProjectList = []
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remarks: null,
        delFlag: null,
        deptId: null,
        code: null,
        type: null,
        date: null,
        accessoryNumber: null,
        producer: null,
        expenseType: null,
        balance: null,
        status: '0'
      }
      this.resetForm('form')
      this.voucherTableData = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    // 多选框选中数据
    handleSelectionChange1(selection) {
      this.ids1 = selection.map(item => item.index)
      this.single1 = selection.length !== 1
      this.multiple1 = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.fileList = []
      this.isEditVoucherInfo = true
      this.reset()
      this.open = true
      this.title = '添加辅助帐凭证'
    },

    /** 查看按钮操作 */
    handleView(row) {
      this.isEditVoucherInfo = false
      this.form = row
      this.fileList = row.buyerFileInfos
      this.voucherTableData = row.buyerVoucherInfos
      this.open = true
      this.title = '查看凭证'
    },

    /** 复制按钮操作 */
    handleCopy(row) {
      this.isEditVoucherInfo = true
      this.form = row
      this.form.id = ''
      this.fileList = row.buyerFileInfos
      this.voucherTableData = row.buyerVoucherInfos
      this.open = true
      this.title = '添加辅助帐凭证'
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getAuxiliaryvoucher(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改辅助帐凭证'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (!this.voucherTableData || this.voucherTableData.length <= 1) {
            this.$modal.msgWarning('凭证详情列表数据列为空或者数据不对请检查后再试！')
          } else {
            let totalDebitBalance = 0
            let totalCreditBalance = 0
            for (const obj of this.voucherTableData) {
              obj.debitBalance = (Number(obj.debitUnit1 + obj.debitUnit2 + obj.debitUnit3
                + obj.debitUnit4 + obj.debitUnit5 + obj.debitUnit6 + obj.debitUnit7
                + obj.debitUnit8 + obj.debitUnit9 + '.' + obj.debitUnit10 + obj.debitUnit11))
              obj.creditBalance = (Number(obj.creditUnit1 + obj.creditUnit2 + obj.creditUnit3
                + obj.creditUnit4 + obj.creditUnit5 + obj.creditUnit6 + obj.creditUnit7
                + obj.creditUnit8 + obj.creditUnit9 + '.' + obj.creditUnit10 + obj.creditUnit11))
              totalDebitBalance += obj.debitBalance
              totalCreditBalance += obj.creditBalance
            }
            if (totalDebitBalance !== totalCreditBalance) {
              this.$modal.msgError('借方余额不等于贷方余额，请检查数据！')
            } else {
              this.form.buyerFileInfos = this.fileList
              this.form.balance = totalDebitBalance
              this.form.buyerVoucherInfos = this.voucherTableData
              addAuxiliaryvoucher(this.form).then(response => {
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.getList()
              })
            }
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除辅助帐凭证选中的数据项？').then(function() {
        return delAuxiliaryvoucher(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 删除按钮操作 */
    handleSingleDelete(id) {
      this.$modal.confirm('是否确认删除当前数据项？').then(function() {
        return delAuxiliaryvoucher(id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('buyer/auxiliaryvoucher/export', {
        ...this.queryParams
      }, `auxiliaryvoucher_${new Date().getTime()}.xlsx`)
    },

    /** 导出按钮操作 */
    downTemplate() {
      this.download('buyer/auxiliaryvoucher/downTemplate', {
        ...this.queryParams
      }, `凭证导入模板.xlsx`)
    },

    /** 新增凭证详情 */
    clickAddVoucher() {
      this.voucherTableData.push({
        index: this.voucherTableData.length,
        isEdit: true,
        summary: '',
        subject1: '',
        subject2: '',
        debitUnit1: 0, debitUnit2: 0, debitUnit3: 0, debitUnit4: 0, debitUnit5: 0, debitUnit6: 0, debitUnit7: 0, debitUnit8: 0, debitUnit9: 0, debitUnit10: 0, debitUnit11: 0,
        creditUnit1: 0, creditUnit2: 0, creditUnit3: 0, creditUnit4: 0, creditUnit5: 0, creditUnit6: 0, creditUnit7: 0, creditUnit8: 0, creditUnit9: 0, creditUnit10: 0, creditUnit11: 0
      })
    },

    /** 删除凭证详情 */
    clickDeleteVoucher() {
      for (const index of this.ids1) {
        for (const item in this.voucherTableData) {
          if (this.voucherTableData[item].index == index) {
            this.voucherTableData.splice(item, 1)
          }
        }
      }
    },

    /** 关联项目 */
    handleAddProject(obj) {
      this.selectVoucher = obj
      this.projectOpen = true
      for (const item of this.selectVoucher.buyerVoucherInfos) {
        if (item.subject1 == 'type1') {
          // 初始化定义第一个为活动的tab页
          this.activeName = item.subject2
          break
        }
      }
      this.projectTitle = '关联项目'
    },

    /** 查看关联项目 */
    handleViewProject(obj) {
      this.selectVoucher = obj
      this.viewProjectOpen = true
      for (const item of this.selectVoucher.buyerVoucherInfos) {
        if (item.subject1 == 'type1') {
          // 初始化定义第一个为活动的tab页
          this.activeName = item.subject2
          break
        }
      }
    },

    /** 下一步 */
    projectNext() {
      if (this.selectProjectList.length == 0) {
        this.$modal.msgWarning('请至少选择一个项目！')
      } else {
        this.projectNextOpen = true
        this.selectVoucherProjectList = []
        // 遍历凭证详情
        for (const info of this.selectVoucher.buyerVoucherInfos) {
          const balance = (info.creditBalance !== 0 ? info.creditBalance : info.debitBalance)
          // 处理 研发费用  类型数据
          if (info.subject1 == 'type1') {
            // 每个科目的项目分配列表
            let selectVoucherProjectList = []
            // 每个分的平均比例
            const proportion = Math.floor((1 / this.selectProjectList.length).toFixed(2) * 100)
            const otherProportion = 100 - this.selectProjectList.length * proportion
            const price = (balance * proportion / 100).toFixed(2)
            const otherPrice = (balance - this.selectProjectList.length * price).toFixed(2)
            for (const id of this.selectProjectList) {
              // 获取项目名称
              let projectName = ''
              for (const project of this.projectList) {
                if (project.id == id) {
                  projectName = project.name
                  break
                }
              }
              // 默认自动比例分配
              selectVoucherProjectList.push({
                projectName: projectName,
                projectId: id,
                voucherId: this.selectVoucher.id,
                proportion: proportion,
                price: price,
                balance: balance
              })
            }

            // 如果还有剩余比例需要补充到最后一个项目上
            if (otherProportion != 0) {
              selectVoucherProjectList[selectVoucherProjectList.length - 1].proportion
                = Number(selectVoucherProjectList[selectVoucherProjectList.length - 1].proportion) + Number(otherProportion)
              selectVoucherProjectList[selectVoucherProjectList.length - 1].price
                = Number(selectVoucherProjectList[selectVoucherProjectList.length - 1].price) + Number(otherPrice)
            }

            this.selectVoucherProjectList.push({
              projectFormType: '1',
              subject: info.subject2,
              subjectLabel: info.subject2Label,
              buyerVoucherProjects: selectVoucherProjectList
            })
          }
        }
      }
    },

    /** 提交项目关联数据 */
    submitProjectData() {
      // this.$refs["projectForm"].validate(valid => {
      //   if (valid) {
      addBatchVoucherProject(this.selectVoucherProjectList).then(response => {
        this.$modal.msgSuccess('新增成功')
        this.projectOpen = false
        this.projectReset()
        this.getList()
        this.open = false
      })
      //   }
      // });
    },

    // 打开文件上传列表
    openFileList() {
      this.fileListOpen = true
    },

    handleUploadSuccess(res, file) {
      // 如果上传成功
      if (res.code == 200) {
        this.fileList.push(res)
      } else {
        this.$message.error('文件上传失败')
      }
    },
    handleUploadError() {
      this.$message.error('文件上传失败')
    },

    // 删除附件
    handleFileDelete(row) {
      for (const item in this.fileList) {
        if (this.fileList[item].fileName == row.fileName) {
          this.fileList.splice(item, 1)
        }
      }
      this.$modal.msgSuccess('删除成功')
    },

    // 下载文件
    handleDownLoad(row) {
      download.name(row.fileName, 0)
    },

    // 更新关联文件
    submitFileInfo() {
      if (this.form.id) {
        updateFileInfos({ id: this.form.id, buyerFileInfos: this.fileList }).then(response => {
          this.$modal.msgSuccess('保存成功')
          this.fileListOpen = false
        })
      } else {
        this.$modal.msgSuccess('保存成功')
        this.fileListOpen = false
      }
    },

    // 导入数据
    importData() {
      this.$refs.importForm.submit()
    }
  }
}
</script>
