<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <!--      <el-form-item label="数据类型" prop="type">-->
      <!--        <el-select-->
      <!--          v-model="queryParams.type"-->
      <!--          placeholder="请选择数据类型"-->
      <!--          clearable-->
      <!--          filterable-->
      <!--          class="se"-->
      <!--        >-->
      <!--          <el-option-->
      <!--            v-for="dict in typeList"-->
      <!--            :key="dict.value + 'typeList'"-->
      <!--            :label="dict.label"-->
      <!--            :value="dict.value"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item label="采集状态" prop="collStatus">
        <el-select
          v-model="queryParams.collStatus"
          placeholder="请选择采集状态"
          clearable
          filterable
          class="se"
        >
          <el-option
            v-for="dict in collStatus"
            :key="dict.value + 'collStatus'"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上报状态" prop="reportStatus">
        <el-select
          v-model="queryParams.reportStatus"
          placeholder="请选择上报状态"
          clearable
          filterable
          class="se"
        >
          <el-option
            v-for="dict in reportStatus"
            :key="dict.value + 'reportStatus'"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="approveStatus">
        <el-select
          v-model="queryParams.approveStatus"
          placeholder="请选择审核状态"
          clearable
          filterable
          class="se"
        >
          <el-option
            v-for="(dict, index) in approveStatus"
            :key="dict.value + 'approveStatus'"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="年度" prop="year">
        <el-date-picker
          v-model="queryParams.year"
          type="year"
          format="yyyy"
          value-format="yyyy"
          placeholder="选择年度"
          class="se"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="月份" prop="month">
        <el-date-picker
          v-model="queryParams.month"
          type="month"
          format="MM"
          value-format="MM"
          placeholder="选择月份"
          class="se"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" @click="onOpenDialog('old')"
          >历史数据导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          v-hasPermi="['gather:GATHER:upload']"
          @click="onOpenDialog('new')"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          @click="handleDownload()"
          :title="radio === '' ? '请先选择下面对应的单位模板' : ''"
          :disabled="radio === '' ? true : false"
          >下载导入模板</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          @click="importFile({ type: '0', mark: '1' })"
          v-hasPermi="['gather:GATHER:upload']"
          >海关部分贸易导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          @click="importFile({ type: '0', mark: '2' })"
          v-hasPermi="['gather:GATHER:upload']"
          >海关进出口总值导入</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      :data="GATHERList"
      @selection-change="handleSelectionChange"
      @row-click="showRow"
    >
      <!-- @current-change="handleCurrentChange" -->
      <el-table-column label="选择" fixed="left" width="70" center>
        <template scope="scope">
          <el-radio
            class="radio"
            v-model="radio"
            :label="scope.$index"
            @change.native="getCurrentRow(scope.row)"
            >{{ "" }}</el-radio
          >
        </template>
      </el-table-column>
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="单位名称" align="center" prop="deptId_dictText">
        <template slot-scope="scope">
          {{ scope.row.deptId_dictText }}
        </template>
      </el-table-column>
      <el-table-column label="数据类型" align="center" prop="type">
        <template slot-scope="scope">
          <span v-if="scope.row.type == 0">量化指标数据</span>
          <span v-if="scope.row.type == 1">月报表数据</span>
        </template>
      </el-table-column>
      <el-table-column label="年份" align="center" prop="month">
        <template slot-scope="scope">
          {{ scope.row.year }}
        </template>
      </el-table-column>
      <el-table-column label="月份" align="center" prop="month">
        <template slot-scope="scope">
          {{ "01-" + scope.row.month }}
        </template>
      </el-table-column>
      <el-table-column label="采集状态" align="center" prop="collStatus">
        <template slot-scope="scope">
          <span v-if="scope.row.collStatus == 0">未采集</span>
          <span v-if="scope.row.collStatus == 1">已采集</span>
        </template>
      </el-table-column>
      <el-table-column
        label="采集人"
        align="center"
        prop="collName"
        width="110"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.collName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="采集时间"
        align="center"
        prop="collTime"
        width="100"
      >
      </el-table-column>
      <el-table-column label="上报状态" align="center" prop="reportStatus">
        <template slot-scope="scope">
          <span v-if="scope.row.reportStatus == 0">未上报</span>
          <span v-if="scope.row.reportStatus == 1">已上报</span>
        </template>
      </el-table-column>
      <el-table-column
        label="上报人"
        align="center"
        prop="reportName"
        width="110"
      />
      <el-table-column
        label="上报时间"
        align="center"
        prop="reportTime"
        width="100"
      />
      <el-table-column
        label="审核人"
        align="center"
        prop="approveName"
        width="110"
      />
      <el-table-column
        label="审核时间"
        align="center"
        prop="approveTime"
        width="100"
      />
      <el-table-column label="审核状态" align="center" prop="approveStatus">
        <template slot-scope="scope">
          <span v-if="scope.row.audit == 0 && scope.row.auditTime == null"
            >未提交审核</span
          >
          <span
            v-if="scope.row.approveStatus == 0 && scope.row.approveTime == null"
            >未审核</span
          >
          
          <span v-if="scope.row.approveStatus == 1">审核通过</span>
          <span v-if="scope.row.approveStatus == 2">审核拒绝</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- <el-button
            style="margin: 0 2px"
            size="mini"
            type="text"
            @click="handleDownload(scope.row)"
            >下载导入模板</el-button
          > -->
          <!--          todo不加 template 会造成浏览器渲染问题 导致无法弹出 el-popconfirm 组件-->

          <template
            v-if="
              scope.row.collStatus == 0 && checkPermi(['gather:GATHER:add'])
            "
          >
            <el-button
              style="margin: 0 2px"
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
              >录入</el-button
            >
          </template>
          <template
            v-if="
              scope.row.collStatus == 1 &&
              (scope.row.audit == 0 || scope.row.audit == null) &&
              checkPermi(['gather:GATHER:approve'])
            "
          >
            <el-popconfirm
              title="确定提交审核吗？"
              @confirm="handleAudit(scope.row)"
            >
              <el-button
                style="margin: 0 2px"
                size="mini"
                type="text"
                slot="reference"
                >提交审核</el-button
              >
            </el-popconfirm>
          </template>
          <!--              已采集，未上报，未提交审核 或 审核拒绝-->

          <!-- collStatus = 1 , audit = 1 , -->
          <!-- <template>
            {{ scope.row.collStatus }} || {{ scope.row.audit }}||
            {{ scope.row.approveStatus }} || {{ scope.row.reportStatus }} ||
            {{ checkPermi(["gather:GATHER:check"]) }}普通 ---
            {{ checkPermi(["gather:GATHER:approve"]) }}管理
          </template> -->
          <template
            v-if="
              scope.row.collStatus == 1 &&
              scope.row.audit == 1 &&
              (scope.row.approveStatus == 0 ||
                scope.row.approveStatus == null ||
                scope.row.approveStatus == 2) &&
              checkPermi(['gather:GATHER:check'])
            "
          >
            <!-- <el-popconfirm
              title="确定提交吗？"
              @confirm="handleApprove(scope.row)"
            > -->
            <el-button
              @click="handleApprove(scope.row)"
              style="margin: 0 2px"
              size="mini"
              type="text"
              slot="reference"
              >审核绩效</el-button
            >
            <!-- </el-popconfirm> -->
          </template>

          <!--              已采集，未上报，审核通过 -->
          <template
            v-if="
              scope.row.collStatus == 1 &&
              scope.row.reportStatus == 0 &&
              scope.row.approveStatus == 1 &&
              checkPermi(['gather:GATHER:report'])
            "
          >
            <el-popconfirm
              title="确定上报吗？"
              @confirm="handleReport(scope.row)"
            >
              <el-button
                style="margin: 0 2px"
                size="mini"
                slot="reference"
                type="text"
                >上报</el-button
              >
            </el-popconfirm>
          </template>

          <el-button
            style="margin: 0 2px"
            v-if="scope.row.collStatus == 1"
            size="mini"
            type="text"
            @click="handleDetail(scope.row, 0)"
            >查看</el-button
          >
          <!-- {{scope.row.collStatus}}--{{scope.row.approveStatus}} -->

          <el-button
            style="margin: 0 2px"
            v-if="
              scope.row.collStatus == 1 && // 已采集
              scope.row.audit == 0 && // 未审核
              checkPermi(['gather:GATHER:edit']) // 编辑权限
            "
            size="mini"
            type="text"
            @click="handleDetail(scope.row, 1)"
            >修改</el-button
          >
        </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
      center
      title="导入"
      :visible.sync="openUpload"
      width="50%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="uploadForm"
        :model="uploadForm"
        :rules="rules"
        label-width="120px"
      >
        <!--        <el-form-item label="数据类型" prop="type">-->
        <!--          <el-select-->
        <!--            v-model="uploadForm.type"-->
        <!--            placeholder="请选择数据类型"-->
        <!--            clearable-->
        <!--            filterable-->
        <!--          >-->
        <!--            <el-option-->
        <!--              v-for="dict in typeList"-->
        <!--              :key="dict.value + 'typeList'"-->
        <!--              :label="dict.label"-->
        <!--              :value="dict.value"-->
        <!--            />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="文件" prop="linkUrl">
          <el-upload
            class="upload-demo"
            ref="upload"
            action="#"
            :http-request="httprequest"
            :before-upload="uploadFile"
            :file-list="fileList"
            :auto-upload="false"
            :limit="1"
          >
            <el-button slot="trigger" size="small" type="primary"
              >选取文件</el-button
            >
          </el-upload>
        </el-form-item>
        <div class="tips-text">
          <span class="tit">提示</span>
          <p>1.请先下载对应单位名称模板；</p>
          <p>2.上传前，请先检查数据的完整性；</p>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpload">导 入</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 录入数据采集对话框 -->
    <el-dialog
      center
      :title="title"
      :visible.sync="open"
      width="50%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-tabs
        v-if="this.form.type == 0"
        v-model="activeName"
        type="border-card"
        @tab-click="handleClick"
      >
        <el-tab-pane
          v-for="(item, index) in tabList"
          :key="index + 'tabs'"
          :label="item.normName"
          :name="item.normName"
        >
          <template v-for="listItem in form.feeLists">
            <el-form
              v-if="listItem.normId == item.normId"
              :rules="validatorList(listItem.normfeeName)"
              :model="listItem"
              :ref="'form' + listItem.normfeeId"
              :key="listItem.normfeeId"
            >
              <!-- :key="index + listIndex + listItem.normId" -->
              <!-- :rules="rules" ref="form" -->
              <el-form-item
                :label="
                  listItem.normfeeName + '（' + listItem.funit_dictText + '）'
                "
                prop="collCalue"
              >
                <!-- 这里科研失败！想动态绑定校验规则的 -->
                <!-- :prop="listItem.normfeeId" -->
                <!-- :rules="rules.listItem.normfeeId" -->
                <el-input
                  v-model="listItem.collCalue"
                  :placeholder="'请输入' + listItem.normfeeName"
                ></el-input>
              </el-form-item>
            </el-form>
          </template>
          <!-- 这里是第二种写法 -->
          <!-- <el-form :model="form" label-width="300px">
            <el-form-item
              v-for="(listItem, listIndex) in item.list"
              :key="listIndex + 'item.list'"
              :label="listItem.normfeeName"
            >
              <el-input
                v-model="listItem.collCalue"
                :placeholder="'请输入' + listItem.normfeeName"
              ></el-input>
            </el-form-item>
          </el-form> -->
        </el-tab-pane>
      </el-tabs>
      <template v-else-if="this.form.type == 1">
        <el-form
          v-for="listItem in form.feeLists"
          :model="listItem"
          :ref="'form' + listItem.normfeeId"
          :rules="rules"
          :key="listItem.normfeeId"
        >
          <!-- :rules="rules" ref="form" -->
          <el-form-item
            :label="
              listItem.normfeeName + '（' + listItem.funit_dictText + '）'
            "
            prop="collCalue"
          >
            <!-- 这里科研失败！想动态绑定校验规则的 -->
            <!-- :prop="listItem.normfeeId" -->
            <!-- :rules="rules.listItem.normfeeId" -->
            <el-input
              v-model="listItem.collCalue"
              :placeholder="'请输入' + listItem.normfeeName"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('add')">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
        <!-- <el-button @click="cancel">取 消</el-button> -->
      </div>
    </el-dialog>

    <!-- 查看或修改 -->
    <el-dialog
      center
      @close="handleClose"
      :title="title"
      :visible.sync="openDetail"
      width="50%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-tabs
        v-if="this.form.type == 0"
        v-model="activeName"
        type="border-card"
        @tab-click="handleClick"
      >
        <el-tab-pane
          v-for="(item, index) in tabList"
          :key="index + 'tabs'"
          :label="item.normName"
          :name="item.normName"
        >
          <template v-for="listItem in form.feeLists">
            <el-form
              v-if="listItem.normId == item.normId"
              :model="listItem"
              :ref="'form' + listItem.normfeeId"
              :rules="rules"
              :key="listItem.normfeeId"
            >
              <!-- :rules="rules" ref="form" -->
              <el-form-item
                prop="collCalue"
                :label="
                  listItem.normfeeName + '（' + listItem.funit_dictText + '）'
                "
              >
                <!-- 这里科研失败！想动态绑定校验规则的 -->
                <!-- :prop="listItem.normfeeId" -->
                <!-- :rules="rules.listItem.normfeeId" -->
                <el-input
                  :disabled="!edit"
                  v-model="listItem.collCalue"
                  :placeholder="'请输入' + listItem.normfeeName"
                ></el-input>
              </el-form-item>
            </el-form>
          </template>

          <!-- 这里是第二种写法 -->
          <!-- <el-form :model="form" label-width="150px">
            <el-form-item
              v-for="(listItem, listIndex) in item.list"
              :key="listIndex + 'item.list'"
              :label="listItem.normfeeName"
            >
              <el-input
                v-model="listItem.collCalue"
                :placeholder="'请输入' + listItem.normfeeName"
              ></el-input>
            </el-form-item>
          </el-form> -->
        </el-tab-pane>
      </el-tabs>

      <template v-else-if="this.form.type == 1">
        <el-form
          v-for="listItem in form.feeLists"
          :model="listItem"
          :ref="'form' + listItem.normfeeId"
          :rules="rules"
          :key="listItem.normfeeId"
        >
          <!-- :rules="rules" ref="form" -->
          <el-form-item
            :label="
              listItem.normfeeName + '（' + listItem.funit_dictText + '）'
            "
            prop="collCalue"
          >
            <!-- 这里科研失败！想动态绑定校验规则的 -->
            <!-- :prop="listItem.normfeeId" -->
            <!-- :rules="rules.listItem.normfeeId" -->
            <el-input
              v-model="listItem.collCalue"
              :placeholder="'请输入' + listItem.normfeeName"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>

      <!--
      <el-form :model="form" v-else-if="this.form.type == 1">
        <el-form-item
          v-for="(listItem, listIndex) in form.feeLists"
          :key="listIndex"
          :label="listItem.normfeeName + '（' + listItem.funit_dictText + '）'"
        >
          <el-input
            :disabled="!edit"
            v-model="listItem.collCalue"
            :placeholder="'请输入' + listItem.normfeeName"
          ></el-input>
        </el-form-item>
      </el-form>
      -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('edit')" v-if="edit"
          >确 定</el-button
        >
        <el-button type="primary" v-if="check" @click="handleCheck(1)"
          >通 过</el-button
        >
        <el-button type="warning" v-if="check" @click="handleReject"
          >驳 回</el-button
        >
        <el-button type="primary" @click="cancel">返 回</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getInfo } from "@/api/login.js";
import {
  listGATHER,
  getGATHER,
  delGATHER,
  addGATHER,
  updateGATHER,
  getInfoByColl,
  approve,
  report,
  setAudit,
  download,
  upload,
  uploadnew,
  bsqAudit,
} from "@/api/portal/GATHER/GATHER.js";
import importFile from "./importFile.vue";
import { saveAs } from "file-saver";
import { getToken } from "@/utils/auth";
import axios from "axios";
import { checkPermi, checkRole } from "@/utils/permission"; // 权限判断函数

export default {
  name: "GATHER",
  data() {
    return {
      // 审核、驳回
      check: false,
      // 数据id
      dataId: null,
      edit: Boolean, //false 查看  true修改
      tabList: [],
      feeLists: [],
      activeName: "",
      //数据类型(0=量化指标数据,1=月报表数据)
      typeList: [
        { label: "量化指标数据", value: "0" },
        { label: "月报表数据", value: "1" },
      ],
      //采集状态(0=未采集,1=已采集)
      collStatus: [
        { label: "未采集", value: "0" },
        { label: "已采集", value: "1" },
      ],
      //上报状态(0=未上报,=1已上报)
      reportStatus: [
        { label: "未上报", value: "0" },
        { label: "已上报", value: "1" },
      ],
      //审核状态(0=未审核,1审核中,2=审核通过,3=审核拒绝)
      approveStatus: [
        { label: "未审核", value: "0" },
        { label: "审核通过", value: "1" },
        { label: "审核拒绝", value: "2" },
      ],
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据采集表格数据
      GATHERList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openDetail: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        delFlag: null,
        deptId: null,
        type: null,
        year: null,
        month: null,
        collStatus: null,
        reportStatus: null,
        approveStatus: null,
        audit: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // id: [{ required: true, message: "$comment不能为空", trigger: "blur" }],
        collCalue: [
          { required: true, message: "不能为空", trigger: "blur" },
          { trigger: "blur", validator: this.validatorFloatNum },
        ],
      },
      rulesOne: {},

      //设置文件名字
      setFileName: "",
      radio: "",
      rowData: {},
      fileList: [],
      uploadForm: {},
      openUpload: false,
      uploadFileType: "old", // old、new
    };
  },

  created() {
    this.getList();
    getInfo().then((res) => {
      console.log(res);
      // this.data = res;
    });
  },
  methods: {
    checkPermi,
    checkRole,
    // 下面这个validatorNum写重复了吗？
    // validatorNum(rule, value, callback) {},
    validatorFloatNum(rule, value, callback) {
      let reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g;
      if (!reg.test(value)) {
        callback(new Error("请输入数字和正确格式的数字"));
      } else if (typeof value == "string" && value.split(".").length > 2) {
        callback(new Error("请输入正确格式的数字")); //防止输入多个小数点
      }
      // else if (value.indexOf('.') != -1 && value.split('.')[1].length > 2) {
      //   callback(new Error('最多只能输入两位小数')); //小数点后两位
      // }
      else {
        callback();
      }
    },
    validatorNum(rule, value, callback) {
      let reg = /^[+]?(0|([1-9]\d*))(\.\d+)?$/g;
      if (!reg.test(value)) {
        callback(new Error("请输入正数和正确格式的数字"));
      } else if (typeof value == "string" && value.split(".").length > 2) {
        callback(new Error("请输入正确格式的数字")); //防止输入多个小数点
      }
      // else if (value.indexOf('.') != -1 && value.split('.')[1].length > 2) {
      //   callback(new Error('最多只能输入两位小数')); //小数点后两位
      // }
      else {
        callback();
      }
    },
    validatorList(name) {
      if (typeof name != "string") return;

      if (
        name.includes("增幅") ||
        name.includes("验收率") ||
        name.includes("开发率") ||
        name.includes("比重")
      ) {
        return {
          collCalue: [
            { required: true, message: "不能为空", trigger: "blur" },
            { trigger: "blur", validator: this.validatorFloatNum },
          ],
        };
      }

      // if (name == '期末单位面积企业从业人员' || name == '活跃企业数' || name == '期末企业从业人员') {
      //   return {
      //     collCalue: [
      //       { required: true, message: '不能为空', trigger: 'blur' },
      //       { pattern: /^[1-9]\d*$/, message: '请输入正整数', trigger: 'blur' }
      //     ]
      //   };
      // } else {
      //   return {
      //     collCalue: [
      //       { required: true, message: '不能为空', trigger: 'blur' },
      //       { trigger: 'blur', validator: this.validatorNum }
      //     ]
      //   };
      // }
      switch (name) {
        case "期末单位面积企业从业人员":
        case "活跃企业数":
        case "期末企业从业人员":
          return {
            collCalue: [
              { required: true, message: "不能为空", trigger: "blur" },
              {
                pattern: /^[1-9]\d*$/,
                message: "请输入正整数",
                trigger: "blur",
              },
            ],
          };
          break;

        default:
          return {
            collCalue: [
              { required: true, message: "不能为空", trigger: "blur" },
              { trigger: "blur", validator: this.validatorNum },
            ],
          };
          break;
      }
    },
    importFile(param) {
      let title = param.mark == "1" ? "海关一般数据导入" : "海关特殊数据导入";
      this.iframe({
        obj: importFile,
        param: param,
        title: title,
        width: "500px",
        height: "50%",
      });
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    httprequest() {},
    getCurrentRow(val) {
      console.log(val);
    },
    handleCurrentChange(val, index) {
      this.currentRow = val;
      this.$emit("data", val.pkg);
    },
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-3);
    },
    showRow(row) {
      //赋值给radio
      this.radio = this.GATHERList.indexOf(row);
      this.rowData = row;
    },

    handleClose() {
      this.check = false;
    },
    /**
     * 打开上传弹窗
     * @params string type  old/new
     */
    onOpenDialog(type) {
      this.uploadFileType = type;
      this.openUpload = true;
    },
    //导入
    uploadFile(file) {
      let formData = new FormData();
      formData.append("file", file);
      formData.append("type", this.uploadForm.type);
      if (this.uploadFileType === "old") {
        upload(formData).then((res) => {
          this.$modal.msgSuccess("上传采集附件成功!");
          this.getList();
          this.cancel();
          this.openUpload = false;
        });
      } else {
        uploadnew(formData).then((res) => {
          this.$modal.msgSuccess("上传采集附件成功!");
          this.getList();
          this.cancel();
          this.openUpload = false;
        });
      }
    },
    //下载模板
    handleDownload() {
      let row = this.rowData;
      axios({
        url: process.env.VUE_APP_BASE_API + "/gather/download/" + row.id,
        method: "get",
        responseType: "blob",
        headers: {
          Authorization: "Bearer " + getToken(),
        },
      }).then((res) => {
        const temp = res.headers["content-disposition"]
          .split(";")[1]
          .split("filename=")[1];
        const fileName = decodeURIComponent(temp);
        const blob = new Blob([res.data]);
        saveAs(blob, fileName);
        this.getList();
      });
    },
    //上报
    handleReport(data) {
      report(data).then((res) => {
        this.$modal.msgSuccess("上报成功");
        this.getList();
      });
    },
    //提交审核
    handleApprove(row) {
      this.tabList = [];
      this.form = [];
      const id = row.id || this.ids;
      this.edit = false;
      this.check = true;
      this.dataId = row.id;
      getGATHER(id).then((response) => {
        //深拷贝，而不是拷贝地址
        this.form = JSON.parse(JSON.stringify(response.data));
        this.openDetail = true;
        this.title = "数据查看";
        //深拷贝，而不是拷贝地址
        this.tabList = JSON.parse(JSON.stringify(response.data.feeLists));
        let dataList = response.data.feeLists;
        //去重获取tab
        //遍历如果遇到相同的id则删掉
        for (var i = 0; i < this.tabList.length - 1; i++) {
          //设置激活的tab
          if (i == 0) {
            this.activeName = this.tabList[0].normName;
          }
          for (var j = i + 1; j < this.tabList.length; j++) {
            if (this.tabList[i].normId == this.tabList[j].normId) {
              this.tabList.splice(j, 1);
              //因为数组长度减小1，所以直接 j++ 会漏掉一个元素，所以要 j--
              j--;
            }
          }
        }
      });
    },
    handleCheck(val) {
      let data = {
        gatherId: this.dataId,
        type: 1,
      };
      let audit = {
        gatherId: this.dataId,
        auditType: 2,
      };
      if (val == 1) {
        approve(data).then((res) => {
          if (res.code == 200) {
            this.$modal.msgSuccess("通过审核成功");
            this.getList();
            this.openDetail = false;
          }
        });
      } else {
        bsqAudit(audit).then((res) => {
          if (res.code == 200) {
            this.$modal.msgSuccess("驳回成功");
            this.getList();
            this.openDetail = false;
          }
        });
      }
    },

    // 驳回处理
    handleReject() {
      this.$prompt("请驳回理由：", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputType: "textarea",
      })
        .then(({ value }) => {
          // console.log(value);
          this.handleCheck(2);
          // this.$message({
          //   type: 'success',
          //   message: '你的邮箱是: ' + value
          // });
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '取消输入'
          // });
        });
    },

    handleClick(tab, event) {},
    /** 查询数据采集列表 */
    getList() {
      this.loading = true;
      listGATHER(this.queryParams).then((response) => {
        this.GATHERList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.check = false;
      this.open = false;
      this.openDetail = false;
      this.openUpload = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        delFlag: null,
        deptId: null,
        type: null,
        month: null,
        collStatus: "0",
        reportStatus: "0",
        approveStatus: "0",
      };
      this.uploadForm = {
        type: "",
      };
      this.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    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;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.openDetail = true;
      this.title = "添加数据采集";
    },
    /** 录入按钮操作 */
    handleUpdate(row) {
      // this.reset();
      this.tabList = [];
      this.form = [];
      const id = row.id || this.ids;
      getInfoByColl(id).then((response) => {
        //深拷贝，而不是拷贝地址
        this.form = JSON.parse(JSON.stringify(response.data));
        this.open = true;
        this.title = "数据录入";
        //深拷贝，而不是拷贝地址
        this.tabList = JSON.parse(JSON.stringify(response.data.feeLists));
        let dataList = response.data.feeLists;
        //去重获取tab
        //遍历如果遇到相同的id则删掉
        for (var i = 0; i < this.tabList.length - 1; i++) {
          //设置激活的tab
          if (i == 0) {
            this.activeName = this.tabList[0].normName;
          }
          for (var j = i + 1; j < this.tabList.length; j++) {
            if (this.tabList[i].normId == this.tabList[j].normId) {
              this.tabList.splice(j, 1);
              //因为数组长度减小1，所以直接 j++ 会漏掉一个元素，所以要 j--
              j--;
            }
          }
        }

        // 这里科研失败！想动态绑定校验规则的
        //遍历设置表单校验  我好困
        // for (const i in this.form.feeLists) {
        //   this.$set(this.rules,this.form.feeLists[i].normfeeId,[
        //     {  required: true, message: this.form.feeLists[i].normfeeName+"不能为空", trigger: "blur"  }
        //   ])
        // }

        // console.log(this.rules);

        //这里是第二种写法
        //获取分类ID相同的子集
        // for (let index = 0; index < this.tabList.length; index++) {
        //   this.$set(this.tabList[index],'list',[])
        //   for (let i = 0; i < dataList.length; i++) {
        //     if (dataList[i].normId == this.tabList[index].normId) {
        //       this.tabList[index].list.push(dataList[i]);
        //     }
        //   }
        // }
      });
    },

   
    handleAudit(row) {
      let data = {
        type: "1",
        gatherId: row.id,
      };
      setAudit(data).then((res) => {
        if (res.code) {
          this.$message.success("审核成功");
          this.getList();
        }
      });
    },
    /** 查看按钮操作 */
    handleDetail(row, type) {
      //false 查看  true修改
      if (type == 0) {
        this.edit = false;
      } else if (type == 1) {
        this.edit = true;
      }
      // this.reset();
      this.tabList = [];
      this.form = [];
      const id = row.id || this.ids;
      getGATHER(id).then((response) => {
        //深拷贝，而不是拷贝地址
        this.form = JSON.parse(JSON.stringify(response.data));
        this.openDetail = true;
        this.title = "数据查看";
        //深拷贝，而不是拷贝地址
        this.tabList = JSON.parse(JSON.stringify(response.data.feeLists));
        let dataList = response.data.feeLists;
        //去重获取tab
        //遍历如果遇到相同的id则删掉
        for (var i = 0; i < this.tabList.length - 1; i++) {
          //设置激活的tab
          if (i == 0) {
            this.activeName = this.tabList[0].normName;
          }
          for (var j = i + 1; j < this.tabList.length; j++) {
            if (this.tabList[i].normId == this.tabList[j].normId) {
              this.tabList.splice(j, 1);
              //因为数组长度减小1，所以直接 j++ 会漏掉一个元素，所以要 j--
              j--;
            }
          }
        }

        // 这里科研失败！想动态绑定校验规则的
        //遍历设置表单校验  我好困
        // for (const i in this.form.feeLists) {
        //   this.$set(this.rules,this.form.feeLists[i].normfeeId,[
        //     {  required: true, message: this.form.feeLists[i].normfeeName+"不能为空", trigger: "blur"  }
        //   ])
        // }

        // console.log(this.rules);

        //这里是第二种写法
        //获取分类ID相同的子集
        // for (let index = 0; index < this.tabList.length; index++) {
        //   this.$set(this.tabList[index],'list',[])
        //   for (let i = 0; i < dataList.length; i++) {
        //     if (dataList[i].normId == this.tabList[index].normId) {
        //       this.tabList[index].list.push(dataList[i]);
        //     }
        //   }
        // }
      });
    },
    /** 提交按钮 */
    submitForm(type) {
      // for (const i in this.form.feeLists) {
      //   if (
      //     this.form.feeLists[i].collCalue == "" ||
      //     this.form.feeLists[i].collCalue == null
      //   ) {
      //     return this.$message({
      //       message:
      //         this.form.feeLists[i].normName +
      //         " - " +
      //         this.form.feeLists[i].normfeeName +
      //         " 未填写！",
      //       type: "warning",
      //     });
      //   }
      // }
      // 验证表单
      let p = [];
      p = this.form.feeLists.map((item, index) => {
        return new Promise((resolve, reject) => {
          this.$refs["form" + item.normfeeId][0].validate((valid) => {
            // this.$refs["form" + index].validate((valid) => {
            if (valid) {
              resolve(); //完成态
            } else {
              reject(); //已失败
            }
          });
        });
      });
      Promise.all(p)
        .then(() => {
          if (type == "add") {
            addGATHER(this.form).then((response) => {
              this.$modal.msgSuccess("录入成功");
              this.open = false;
              this.getList();
            });
          } else if (type == "edit") {
            updateGATHER(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.openDetail = false;
              this.getList();
            });
          }
        })
        .catch((err) => {
          console.log(err);
          debugger;
          this.$message.error("请检查是否有必填项未输入!");
        });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除数据采集编号为"' + ids + '"的数据项？')
        .then(function () {
          return delGATHER(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "business/GATHER/export",
        {
          ...this.queryParams,
        },
        `GATHER_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
