<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" >
      <el-form-item label="企业名称" prop="orgName">
        <el-input
          v-model="queryParams.data.enterpriseName"
          placeholder="请输入企业名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.data.status"
          placeholder="请选择状态"
          clearable
          size="small"
          style="width: 100%"
          @change="handleQuery"
        >
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="creditList">
      <el-table-column
        label="序号"
        type="index"
        width="100"
        align="left"
        fixed
      />
      <el-table-column
        label="企业名称"
        align="left"
        prop="enterpriseName"
        min-width="120"
      />
      <el-table-column
        label="项目名称"
        align="left"
        prop="projectName"
        min-width="120"
      />
      <el-table-column
        label="资质类别"
        align="left"
        prop="qualificationCategory"
        :formatter="qualificationCategoryFormat"
        min-width="120"
      />
      <el-table-column
        label="状态"
        align="left"
        prop="status"
        min-width="120"
        :formatter="statusFormat"
      />
      <el-table-column
        label="申报管理区划"
        align="left"
        prop="declarationManagementZones"
        :formatter="formatDeclarationManagementZones"
        min-width="120"
      />
      <el-table-column
        label="良好行为"
        align="left"
        prop="behavior"
        min-width="120"
      />
      <el-table-column
        label="表彰等级"
        align="left"
        prop="commendationLevel"
        min-width="120"
      />
      <el-table-column
        label="颁发机构"
        align="left"
        prop="authority"
        min-width="120"
      />
      <el-table-column
        label="加分值"
        align="left"
        prop="bonusPoints"
        min-width="120"
      />
      <el-table-column
        label="有效期（年）"
        align="left"
        prop="validityPeriod"
        min-width="120"
      />
      <el-table-column
        label="获奖公示网址"
        align="left"
        prop="awardAnnouncementWebsite"
        min-width="120"
      />
      <el-table-column
        label="评价日期"
        align="left"
        prop="evaluationDate"
        min-width="120"
      />
      <el-table-column
        label="重合同守信用情况"
        align="left"
        prop="trustworthyPerformance"
        min-width="140"
      />
      <el-table-column
        label="附件"
        align="left"
        prop="attachment"
        min-width="180"
      >
        <template slot-scope="scope">
          <div
            v-for="(item, index) in JSON.parse(scope.row.attachment)"
            :key="item + index"
          >
            <i class="el-icon-document"></i>
            {{ item.name }}
            <i
              class="el-icon-download"
              @click="downloadFile(scope, index)"
              style="cursor: pointer"
            ></i>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="审核流程"
        align="left"
        prop="attachment"
        min-width="120"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button type="primary" @click="openAuditProcess(scope.row)">
            审核流程
          </el-button>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="right"
        class-name="small-padding fixed-width"
        width="184"
        fixed="right"
      >
        <template slot-scope="scope">
          <!-- ===============审核按钮=========== -->
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.status == '1'"
            icon="el-icon-edit-outline"
            @click="handleExamine(scope.row)"
            v-hasPermi="['enterpriseMange:credit:examine']"
          >审核</el-button
          >
          <el-button
            v-if="scope.row.status == '1'"
            size="mini"
            type="text"
            icon="el-icon-time"
            v-hasPermi="['enterprise:credit:report']"
          >待审核</el-button
          >
          <el-button
            v-if="scope.row.status == '2'"
            size="mini"
            type="text"
            icon="el-icon-time"
            v-hasPermi="['enterprise:credit:report']"
          >已驳回</el-button
          >
          <el-button
            v-if="scope.row.status == '3'"
            size="mini"
            type="text"
            icon="el-icon-time"
            v-hasPermi="['enterprise:credit:report']"
            @click="handleReport(scope.row)"
          >已审核</el-button
          >
          <el-button
            v-if="scope.row.status == '4'"
            size="mini"
            type="text"
            icon="el-icon-time"
            v-hasPermi="['enterprise:credit:report']"
          >已公示</el-button
          >
          <el-button
            v-if="scope.row.status == '5'"
            size="mini"
            type="text"
            icon="el-icon-time"
            v-hasPermi="['enterprise:credit:report']"
          >已发布</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
      :title="title"
      :visible.sync="open"
      width="1200px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-row :gutter="15">
        <el-form ref="form" :model="form" :rules="rules" label-width="110px">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <!-- <el-input
                v-model="form.projectName"
                placeholder="请输入项目名称"
              /> -->
              <el-select
                ref="selectPro"
                v-model="form.projectName"
                placeholder="请输入项目名称"
                filterable
                clearable
                size="small"
                style="width: 100%"
                remote
                :remote-method="remoteMethod"
                @change="handleProNameChange"
                :loading="selectLoading"
                @visible-change="visibleChange"
              >
                <el-option
                  v-for="dict in projectNameOptions"
                  :key="dict.projectName + dict.id"
                  :label="dict.projectName + '[' + dict.proCode + ']'"
                  :value="dict.projectName + '[' + dict.proCode + ']'"
                  @click.native="getId(dict)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资质类别" prop="qualificationCategory">
              <el-select
                v-model="form.qualificationCategory"
                placeholder="请选择资质类别"
                style="width: 100%"
                disabled
              >
                <el-option
                  v-for="dict in qualificationCategoryOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="申报管理区划"
              prop="declarationManagementZones"
            >
              <!-- <el-input
                v-model="form.declarationManagementZones"
                placeholder="请输入申报管理区划"
              /> -->
              <el-cascader
                :options="areasOptions"
                v-model="form.declarationManagementZones"
                :props="areasOptionProps"
                placeholder="请选择申报管理区划"
                clearable
                size="small"
                style="width: 100%"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="良好行为" prop="behavior">
              <el-input v-model="form.behavior" placeholder="请输入良好行为" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="表彰等级" prop="commendationLevel">
              <!-- <el-select
                v-model="form.commendationLevel"
                placeholder="请选择表彰等级"
                style="width: 100%"
              >
                <el-option label="请选择字典生成" value="" />
              </el-select> -->
              <el-input
                v-model="form.commendationLevel"
                placeholder="请输入表彰等级"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="颁发机构" prop="authority">
              <el-input v-model="form.authority" placeholder="请输入颁发机构" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加分值" prop="bonusPoints">
              <el-input v-model="form.bonusPoints" placeholder="请输入加分值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核时间" prop="evaluationDate">
              <el-date-picker
                clearable
                size="small"
                style="width: 100%"
                v-model="form.evaluationDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择审核日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效期" prop="validityPeriod">
              <el-date-picker
                clearable
                size="small"
                style="width: 100%"
                v-model="form.validityPeriod"
                type="year"
                value-format="yyyy"
                placeholder="选择有效期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="获奖公示网址" prop="awardAnnouncementWebsite">
              <el-input
                v-model="form.awardAnnouncementWebsite"
                placeholder="请输入获奖公示网址"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="重合同守信用情况" prop="trustworthyPerformance" label-width="150px">
              <el-input
                style="width:70%;"
                type="textarea"
                :autosize="{ minRows: 6}"
                v-model="form.trustworthyPerformance"
                placeholder="请输入重合同守信用情况"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="评价日期" prop="evaluationDate">
              <el-date-picker
                style="width: 100%"
                v-model="form.evaluationDate"
                type="date"
                placeholder="选择评价日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="附件" prop="attachment">
              <!-- <el-input v-model="form.attachment" placeholder="请输入附件" /> -->
              <el-upload ref="uploadTemplate"
                class="upload-demo"
                action="thinking/common/upload"
                :headers="headers"
                :before-upload="(file) => $fileBeforeUpload(file, 'fileList')"
                :on-preview="handlePreview"
                :on-remove="(file) => handleRemove(file, 'fileList')"
                :before-remove="beforeRemove"
                multiple
                :on-exceed="handleExceed"
                :on-success="
                  (_, fileList) => submitUpload(fileList, 'fileList')
                "
                :file-list="fileList"
              >
                <el-button size="small" type="primary" plain @click="$ButtonClick()" @click.stop="beforeUploadFile">
                  <i class="el-icon-upload el-icon--right"></i>
                  点击上传
                </el-button>
                <div slot="tip" class="el-upload__tip">
                  支持jpg/png/pdf/word/excel文件等，不超过200M
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--上报或者审核 -->
    <el-dialog
      :title="viewTitle"
      :visible.sync="viewOpen"
      width="1200px"
      append-to-body
      @close="closeView"
      :close-on-click-modal="false"
    >
      <!-- 动态信用 -->
      <!-- <div class="infoTitle">动态信用</div>
      <div class="draLine"></div> -->
      <div class="content">
        <el-descriptions
          class="margin-top"
          :column="2"
          border
          :labelStyle="{
            'text-align': 'left',
            width: '180px',
            height: '50px',
          }"
          :contentStyle="{ minWidth: '350px' }"
        >
          <el-descriptions-item>
            <template slot="label"> 项目名称 </template>
            {{ this.creditMsg.projectName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 资质类别 </template>
            {{ qualificationCategoryFormat(this.creditMsg) }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 状态 </template>
            {{ statusFormat(this.creditMsg) }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 申报管理区划 </template>
            {{ this.creditMsg.declarationManagementZones }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 良好行为 </template>
            {{ this.creditMsg.behavior }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 表彰等级 </template>
            {{ this.creditMsg.commendationLevel }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 颁发机构 </template>
            {{ this.creditMsg.authority }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 加分值 </template>
            {{ this.creditMsg.bonusPoints }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 审核日期 </template>
            {{ this.creditMsg.evaluationDate }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 有效期（年） </template>
            {{ this.creditMsg.validityPeriod }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 重合同守信用情况 </template>
            {{ this.creditMsg.trustworthyPerformance }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 附件 </template>
            <template v-if="this.creditMsg.attachment">
              <div
                v-for="(item, index) in JSON.parse(this.creditMsg.attachment)"
                :key="item + index"
              >
                {{ item.name }}

                <i
                  class="el-icon-download"
                  @click="downloadFile2(item, index)"
                  style="cursor: pointer"
                ></i>
              </div>
            </template>
          </el-descriptions-item>

          <el-descriptions-item v-if="this.creditMsg.status == '2'">
            <template slot="label"> 驳回意见 </template>
            {{ this.creditMsg.remark }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div slot="footer" class="dialog-footer">
        <!-- 审核通过按钮 -->
        <el-button
          type="primary"
          @click="passExamine"
          v-hasPermi="['enterpriseMange:credit:passExamine']"
          v-if="creditMsg.status=='1'"
        >通过审核</el-button
        >
        <el-button
          type="primary"
          @click="publicity"
          v-hasPermi="['enterpriseMange:credit:passExamine']"
          v-if="creditMsg.status=='3'"
        >公示信息</el-button
        >
        <!-- 驳回按钮 -->
        <el-popover
          placement="top"
          width="300"
          v-model="visible"
          style="margin: 0 10px"
        >
          <el-input
            v-model="remark"
            placeholder="请输入驳回意见"
            type="textarea"
            maxlength="250"
            show-word-limit
            style="margin-bottom: 10px"
          ></el-input>
          <div style="text-align: right; margin: 0">
            <el-button type="primary" size="mini" @click="TurnDownExamine">
              确定
            </el-button>
            <el-button size="mini" type="text" @click="visible = false">
              取消
            </el-button>
          </div>

          <el-button
            slot="reference"
            type="warning"
            v-if="creditMsg.status=='1'"
            v-hasPermi="['enterpriseMange:credit:TurnDownExamine']"
          >
            驳回审核
          </el-button>
        </el-popover>

        <el-button
          v-if="creditMsg.status == '0' || creditMsg.status == '2'"
          type="primary"
          @click="upExamine"
          v-hasPermi="['enterpriseMange:credit:upExamine']"
        >上 报</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审核流程 -->
    <el-dialog
      :center="true"
      :title="processTitle"
      :visible.sync="processOpen"
      width="1000px"
      append-to-body
      @close="closeProcess"
      :close-on-click-modal="false"
      class="process"
    >
      <el-table v-loading="loading" :data="processList">
        <el-table-column
          label="序号"
          type="index"
          width="50"
          align="center"
          fixed
        />

        <el-table-column
          label="流程进度"
          align="center"
          prop="processProgress"
          min-width="120"
        />
        <el-table-column
          label="审批意见"
          align="center"
          prop="approvalOpinions"
          min-width="120"
        />
        <el-table-column
          label="审批时间"
          align="center"
          prop="approvalTime"
          min-width="120"
        />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCredit,
  getCredit,
  delCredit,
  addCredit,
  updateCredit,
  exportCredit,
} from "@/api/enterprise/credit";
import { listPerformanceRecord } from "@/api/enterprise/performanceRecord";
import { listApproval } from "@/api/enterprise/approval";
import { getToken } from "@/utils/auth";
import { getFileStream } from "@/api/system/upload";
import { getAreasData } from "@/api/areas/index";
import { regionData, codeToText, TextToCode } from "element-china-area-data";
import { listInfo } from "@/api/build/projectInfo";


export default {
  name: "goodCredit",
  data() {
    return {
      areasOptionProps: {
        emitPath: false, //value返回最后一级的
        checkStrictly: true, //选择任意一级
      },
      areasOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      isMajorProjectOptions:[],
      typeOptions:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 动态信用表格数据
      creditList: [],
      // 弹出层标题
      title: "",
      viewTitle: "",
      processTitle: "",
      // 是否显示弹出层
      open: false,
      viewOpen: false,
      visible: false,
      processOpen: false,
      // 资质类别字典
      qualificationCategoryOptions: [],
      proQueryParams: {
        pageNum: 1,
        pageSize: 10,
        ids: null,
        data: {},
        // 排序方式
        params: {
          // 按哪个字段排序
          orderBy: "create_time",
          // desc降序，升序asc
          sortBy: "desc",
        },
      },
      // 审核状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ids: null,
        data: {
          enterpriseId: null,
          projectName: null,
          qualificationCategory: null,
          declarationManagementZones: null,
          behavior: null,
          goodBehavior: null,
          commendationLevel: null,
          authority: null,
          bonusPoints: null,
          validityPeriod: null,
          awardAnnouncementWebsite: null,
          attachment: null,
          status: "1",
          type: null,
          badBehavior: null,
          createUid: null,
          updateUid: null,
          owerDept: null,
        },
        // 排序方式
        params: {
          // 按哪个字段排序
          orderBy: "create_time",
          // desc降序，升序asc
          sort: "desc",
        },
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectName: [
          { required: true, message: "请选择项目名称", trigger: "blur" },
        ],
        behavior: [{ max: 250, message: "字符长度最大为250", trigger: "blur" }],
        commendationLevel: [
          { max: 250, message: "字符长度最大为250", trigger: "blur" },
        ],
        authority: [
          { max: 250, message: "字符长度最大为250", trigger: "blur" },
        ],
        awardAnnouncementWebsite: [
          { max: 250, message: "字符长度最大为250", trigger: "blur" },
        ],
        bonusPoints: [
          { required: true, message: "请输入加分值", trigger: "blur" },
          {
            pattern:
              /(^[1-9]([0-9]{0,6})?(\.[0-9]{1,2})?$|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$))/,
            message: "请输入数字,整数7位,可保留两位小数",
            trigger: "blur",
          },
        ],
      },
      projectNameOptions: [],
      selectLoading: false,
      // 请求头
      headers: {
        jianwei: "jwtech " + getToken(),
      },
      fileList: [],
      creditMsg: {},
      remark: "",
      processList: [],
      projectNameOption: [],
    };
  },
  async created() {
    const typeOptionsRes = await this.getDicts("zt_status")
    this.typeOptions = typeOptionsRes.data;
    // this.getDicts("zt_status").then((response) => {
    //   this.typeOptions = response.data;
    // });
    listInfo(this.proQueryParams).then((response) => {
      this.projectNameOptions = response.records;
    });
    this.getTreeData();
    this.getList();
    this.getDicts("qualification_type").then((response) => {
      this.qualificationCategoryOptions = response.data;
    });
    this.getDicts("review_status").then((response) => {
      this.statusOptions = response.data;
    });
    listPerformanceRecord({ data: { enterpriseId: this.enterpriseId } }).then(
      (response) => {
        this.projectNameOption = response.records;
      }
    );
  },
  methods: {
    visibleChange(visible) {
      // console.log(visible);
      // 下拉框显示隐藏
      if (visible) {
        const ref = this.$refs.selectPro;
        let popper = ref.$refs.popper;
        if (popper.$el) popper = popper.$el;
        // 判断是否有添加按钮
        if (
          !Array.from(popper.children).some((v) => v.className === "btn-box")
        ) {
          const el = document.createElement("div");
          el.className = "btn-box";
          el.innerHTML = `<div style="display:flex;align-items:center;justify-content: center;background:#f0f0f0">
                              <a class="btn" style="font-size:16px;display:block;line-height:38px;text-align:center;" >
                                <span style="font-size:12px">只展示10个项目，其余项目的选择可搜索</span>
                              </a>
                          </div>
                          `;
          popper.appendChild(el);
          el.onclick = () => {
            //TODO
          };
        }
      }
    },
    remoteMethod(query) {
      this.selectLoading = true;
      if (query !== "") {
        // console.log(444, query);
        this.proQueryParams.data.projectName = query;
      } else {
        // this.reset();
        this.proQueryParams.data.projectName = null;
      }
      listInfo(this.proQueryParams).then((res) => {
        this.projectNameOptions = res.records;
        this.selectLoading = false;
      });
    },
    handleProNameChange(keyWork) {
      // if (!keyWork) {
      console.log(666);
      this.selectLoading = true;
      this.proQueryParams.data.projectName = null;
      listInfo(this.proQueryParams).then((res) => {
        this.projectNameOptions = res.records;
        this.selectLoading = false;
      });
      // }/
    },
    getId(res) {
      this.form.proNo = res.proNo;
      this.form.proCode = res.proCode;
    },

    chooseProjectName(data) {
      this.form.recordId = data.id;
      this.form.qualificationCategory = data.qualificationCategory;
    },
    download(filename, name) {
      let a = document.createElement("a");
      a.href = "/static/" + filename;
      //路径中'/'为根目录，即index.html所在的目录
      a.download = name;
      a.click();
    },
    openAuditProcess(row) {
      listApproval({
        data: { creditId: row.id }, // 排序方式
        params: {
          // 按哪个字段排序
          orderBy: "create_time",
          // desc降序，升序asc
          sortBy: "asc",
        },
      }).then((res) => {
        console.log(6666, res);
        this.processList = res.records;
        this.processOpen = true;
        this.processTitle = "审核流程进度";
      });
    },
    closeProcess() {
      this.processList = [];
    },
    formatDeclarationManagementZones(row) {
      const regex = /^[+-]?\d+(\.\d+)?$/;
      if (!regex.test(row.declarationManagementZones)){
        return ""
      }
      if (row.declarationManagementZones) {
        let provinceCode = row.declarationManagementZones.slice(0, 2);
        let cityCode = row.declarationManagementZones.slice(2, 4);
        let areaCode = row.declarationManagementZones.slice(4, 6);
        if (areaCode != "00") {
          return (
            codeToText[provinceCode] +
            "-" +
            codeToText[provinceCode + cityCode] +
            "-" +
            codeToText[provinceCode + cityCode + areaCode]
          );
        } else if (cityCode != "00") {
          return (
            codeToText[provinceCode] + "-" + codeToText[provinceCode + cityCode]
          );
        } else {
          return codeToText[provinceCode];
        }
      }
    },
    getTreeData() {
      getAreasData().then((items) => {
        // console.log("getAreasData", items.data);
        let res = [];
        let getChildren = (res, pid) => {
          for (const i of items.data) {
            if (i.parentid === pid) {
              const newItem = {
                label: i.name,
                value: i.id,
              };
              if (i.layer != 3) newItem.children = [];
              res.push(newItem);
              getChildren(newItem.children, newItem.value);
            }
          }
        };
        getChildren(res, items.data[0].parentid);
        // console.log("areasOptions", res);
        this.areasOptions = res;
        // 当不是admin时，默认行政区域
        // if (this.$userProfile.createUid != "admin") {
        //   this.queryParams.data.adcd = this.areasOptions[0].value;
        // }
        // return res;
      });
    },
    /** 查询动态信用列表 */
    getList() {
      this.loading = true;
      this.queryParams.data.type = "1";

      listCredit(this.queryParams).then((response) => {
        this.creditList = response.records;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 资质类别字典翻译
    qualificationCategoryFormat(row, column) {
      return this.selectDictLabel(
        this.qualificationCategoryOptions,
        row.qualificationCategory
      );
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.viewOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      // this.fileList = [];
      this.form = {
        id: null,
        enterpriseId: null,
        projectName: null,
        qualificationCategory: null,
        declarationManagementZones: null,
        behavior: null,
        goodBehavior: null,
        commendationLevel: null,
        authority: null,
        bonusPoints: null,
        validityPeriod: null,
        awardAnnouncementWebsite: null,
        evaluationDate:null,
        trustworthyPerformance:null,
        attachment: null,
        status: null,
        type: null,
        badBehavior: null,
        createUid: null,
        updateUid: null,
        createTime: null,
        updateTime: null,
        owerDept: null,
        remark: null,
      };
      this.resetForm("form");
    },
    // 查询表单重置
    resetQueryForm() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        data: {
          id: null,
          enterpriseId: null,
          projectName: null,
          qualificationCategory: null,
          declarationManagementZones: null,
          behavior: null,
          goodBehavior: null,
          commendationLevel: null,
          authority: null,
          bonusPoints: null,
          validityPeriod: null,
          awardAnnouncementWebsite: null,
          attachment: null,
          status: null,
          type: null,
          badBehavior: null,
          createUid: null,
          updateUid: null,
          createTime: null,
          updateTime: null,
          owerDept: null,
          remark: null,
        },
        // 排序方式
        params: {
          // 按哪个字段排序
          orderBy: "create_time",
          // desc降序，升序asc
          sort: "desc",
        },
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetQueryForm();
      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.title = "添加良好行为加分申报";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCredit(id).then((response) => {
        this.form = response.data;
        if (this.form.attachment) {
          this.fileList = JSON.parse(this.form.attachment);
        }
        this.open = true;
        this.title = "修改良好行为加分申报";
      });
    },
    // 审核
    handleExamine(row) {
      this.creditMsg = row;
      console.log("this.creditMsg", this.creditMsg);
      this.viewTitle = "审核信息";
      this.viewOpen = true;
    },
    // 上报
    handleReport(row) {
      this.creditMsg = row;
      console.log("this.creditMsg", this.creditMsg);
      if (row.status == "0") this.viewTitle = "上报信息";
      if (row.status == "1") this.viewTitle = "待审核信息";
      if (row.status == "2") this.viewTitle = "驳回信息";
      if (row.status == "3") this.viewTitle = "审核通过信息";
      if (row.status == "4") this.viewTitle = "公示信息";
      if (row.status == "5") this.viewTitle = "发布信息";

      this.viewOpen = true;
    },
    // 关闭弹窗
    closeView() {
      this.creditMsg = {};
      this.remark = "";
    },

    // 通过审核
    passExamine() {
      this.creditMsg.status = "3";
      updateCredit(this.creditMsg).then((response) => {
        if (response.code === 200) {
          this.msgSuccess("审核通过成功");
          this.viewOpen = false;
          this.getList();
        }
      });
    },

    publicity() {
      this.creditMsg.status = "4";
      updateCredit(this.creditMsg).then((response) => {
        if (response.code === 200) {
          this.msgSuccess("信息公示成功");
          this.viewOpen = false;
          this.getList();
        }
      });
    },
    // 驳回审核
    TurnDownExamine() {
      this.visible = false;
      this.creditMsg.status = "2";
      this.creditMsg.remark = this.remark;
      updateCredit(this.creditMsg).then((response) => {
        if (response.code === 200) {
          this.msgSuccess("审核驳回成功");
          this.viewOpen = false;
          this.getList();
        }
      });
    },
    // 上报审核
    upExamine() {
      if (this.creditMsg.status == "1") {
        this.msgInfo("请勿重复上报");
      } else {
        this.creditMsg.status = "1";
        updateCredit(this.creditMsg).then((response) => {
          if (response.code === 200) {
            this.msgSuccess("审核上报成功");
            this.viewOpen = false;
            this.getList();
          }
        });
      }
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.enterpriseId = this.enterpriseId;
          this.form.attachment = JSON.stringify(this.fileList);
          // this.form.status = "1";
          if (this.form.id != null) {
            updateCredit(this.form).then((response) => {
              if (response.code === 200) {
                console.log(111111, this.form);
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            this.form.type = "1";
            this.form.status = "0";
            addCredit(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      if (ids) {
        this.$confirm("是否删除选中的数据？", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return delCredit(ids);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          })
          .catch(function () {});
      } else {
        this.$message.warning("请选择要删除的数据！！");
      }
    },
    submitUpload(fileList, name) {
      console.log(name, fileList);
      this[name].push({
        name: fileList.name,
        fileName: fileList.response.fileName,
        url: fileList.response.url,
        uid: fileList.uid,
      });
      console.log(name, this[name]);
    },
    handleRemove(file, name) {
      // console.log(file, fileList1);
      let index = this[name].findIndex((item) => item.uid === file.uid);
      // 删除文件
      this[name].splice(index, 1);
    },
    downloadFile(scope, index) {
      // console.log(scope);
      let file = JSON.parse(scope.row.attachment)[index];
      this.handlePreview(file);
    },
    downloadFile2(info, index) {
      console.log(info);
      this.handlePreview(info);
    },

    // 点击预览的文件进行下载
    handlePreview(file) {
      // console.log(file);
      getFileStream({ fileName: file.fileName }).then((res) => {
        const blob = new Blob([res], {
          // type类型后端返回来的数据中会有，根据自己实际进行修改
          // 表格下载为 application/xlsx，压缩包为 application/zip等，
          type: "application/xlsx",
        }); //excel,pdf等
        const href = URL.createObjectURL(blob); //创建新的URL表示指定的blob对象
        const a = document.createElement("a"); //创建a标签
        a.style.display = "none";
        a.href = href; // 指定下载链接
        a.download = file.name; //指定下载文件名
        a.click(); //触发下载
        URL.revokeObjectURL(a.href); //释放URL对象
      });
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/css/dialog.scss";
// ::v-deep {
// .el-dialog {
//     margin-top: 10vh !important;
//  }
// }
.topFile {
  width: 100%;
  background: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #f0f0f0;
}
.process ::v-deep {
  .el-dialog {
    height: 500px;
    overflow-y: scroll;
  }
}
</style>
