<template>
  <div class="app-container">
    <!-- 面包屑 -->
    <el-breadcrumb separator="/" style="margin-bottom: 20px">
      <el-breadcrumb-item
        v-for="(item, index) in routeList"
        :key="item + index"
        :to="{ path: item.path }"
        >{{ item.routeName }}</el-breadcrumb-item
      >
    </el-breadcrumb>

    <el-row :gutter="20" v-show="showSearch">
      <el-col :span="22">
        <!-- 搜索条件 -->
        <el-form :model="queryParams" :inline="true" label-width="80px">
          <el-form-item label="项目名称" prop="projectName">
            <el-input
              v-model="queryParams.data.projectName"
              placeholder="请输入项目名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            >
              <el-button
                type="primary"
                slot="append"
                icon="el-icon-search"
                size="small"
                @click="handleQuery"
              ></el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="项目编码" prop="projectCode">
            <el-input
              v-model="queryParams.data.projectCode"
              placeholder="请输入项目编码"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            >
              <el-button
                type="primary"
                slot="append"
                icon="el-icon-search"
                size="small"
                @click="handleQuery"
              ></el-button>
            </el-input>
          </el-form-item>
          <!-- <el-form-item label="项目类型" prop="projectType">
            <el-select
              v-model="queryParams.data.projectType"
              placeholder="项目类型"
              clearable
              size="small"
              @change="handleQuery"
            >
              <el-option
                v-for="dict in projectTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item label="行政区划" prop="adcd">
            <el-cascader
              :options="areasOptions"
              v-model="queryParams.data.adcd"
              :props="areasOptionProps"
              placeholder="请选择行政区划"
              clearable
              size="small"
              style="width: 100%"
              @change="handleQuery"
            >
            </el-cascader>
          </el-form-item>
          <el-form-item>
            <!-- <el-button
              type="cyan"
              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-col>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['earlyStage:feasibility:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['earlyStage:feasibility:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['earlyStage:feasibility:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!--    列表-->
    <el-table
      v-loading="loading"
      :data="feasibilityList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" fixed />
      <el-table-column
        label="序号"
        type="index"
        width="50"
        align="center"
        fixed
      />

      <el-table-column
        label="项目名称"
        align="center"
        prop="projectName"
        min-width="150"
      />
      <el-table-column
        label="项目编码"
        align="center"
        prop="projectCode"
        min-width="180"
      />
      <el-table-column
        label="行政区划"
        align="center"
        prop="adcd"
        min-width="180"
        :formatter="$formatAdcd"
      />
      <el-table-column
        label="项目类型"
        align="center"
        prop="projectType"
        :formatter="projectTypeFormat"
        min-width="150"
      />
      <el-table-column
        label="编制单位"
        align="center"
        prop="compilingUnit"
        min-width="120"
      />
      <el-table-column
        label="投资概算"
        align="center"
        prop="projectInvestmentEstimate"
        min-width="120"
      />
      <!-- <el-table-column
        label="批复部门"
        align="center"
        prop="approvalDepartment"
        min-width="120"
      />
      <el-table-column
        label="批复文号"
        align="center"
        prop="approvalNo"
        min-width="120"
      /> -->
      <!-- <el-table-column
        label="批复意见"
        align="center"
        prop="approvalOpinion"
        min-width="180"
      /> -->
      <!-- <el-table-column
        label="可行性研究报告文件"
        align="center"
        prop="feasibilityReportFile"
        min-width="180"
      >
        <template slot-scope="scope">
          <div
            v-for="(item, index) in JSON.parse(scope.row.feasibilityReportFile)"
            :key="item + index"
          >
            <i class="el-icon-document"></i>
            {{ item.name }}
            <i
              class="el-icon-download"
              @click="downloadFile1(scope, index)"
              style="cursor: pointer"
            ></i>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="可行性研究报告相关附件"
        align="center"
        prop="feasibilityReportAttachment"
        min-width="180"
      >
        <template slot-scope="scope">
          <div
            v-for="(item, index) in JSON.parse(
              scope.row.feasibilityReportAttachment
            )"
            :key="item + index"
          >
            <i class="el-icon-document"></i>
            {{ item.name }}
            <i
              class="el-icon-download"
              @click="downloadFile3(scope, index)"
              style="cursor: pointer"
            ></i>
          </div>
        </template>
      </el-table-column> -->

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        min-width="120"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="180"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="viewInfo(scope.row)"
            v-hasPermi="['earlyStage:feasibility:view']"
            >查看</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['earlyStage:feasibility:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['earlyStage:feasibility:remove']"
            >删除</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
      style="margin-top: 0"
      @close="clear"
      :close-on-click-modal="false"
    >
      <el-row :gutter="15">
        <el-form ref="form" :model="form" :rules="rules" label-width="150px">
          <el-col :span="12">
            <el-form-item label="是否有建议书审批" prop="isApproval">
              <el-select
                v-model="form.isApproval"
                placeholder="请选择是否有建议书审批"
                clearable
                size="small"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in isApprovalOptions"
                  :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="projectName"
              v-if="form.isApproval == '0'"
            >
              <el-input
                v-model="form.projectName"
                placeholder="请输入项目名称"
                size="small"
              ></el-input>
            </el-form-item>
            <!-- 有建议书审批 -->
            <el-form-item label="项目名称" prop="projectName" v-else>
              <el-select
                v-model="form.projectName"
                placeholder="请选择项目名称"
                filterable
                clearable
                size="small"
                style="width: 100%"
                :disabled="!form.isApproval"
              >
                <el-option
                  v-for="dict in projectNameOptions"
                  :key="dict.projectName + dict.id"
                  :label="dict.projectName + '[' + dict.projectCode + ']'"
                  :value="dict.projectName + '[' + dict.projectCode + ']'"
                  @click.native="getId(dict)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 无建议书审批时 -->
          <el-col :span="12" v-if="form.isApproval == '0'">
            <el-form-item label="项目类型" prop="projectType">
              <el-select
                v-model="form.projectType"
                placeholder="请选择项目类型"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="dict in projectTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 无建议书审批时，选择行政区划 -->
          <el-col :span="12" v-if="form.isApproval == '0'">
            <el-form-item label="行政区划" prop="adcd">
              <el-cascader
                :options="areasOptions"
                v-model="form.adcd"
                :props="areasOptionProps"
                placeholder="请选择行政区划"
                clearable
                size="small"
                style="width: 100%"
                @change="handleChange"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.isApproval == '0'">
            <el-form-item label="项目编码" prop="projectCode">
              <el-input
                v-model="form.projectCode"
                placeholder="请输入项目编码"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="编制单位" prop="compilingUnit">
              <el-input
                v-model="form.compilingUnit"
                placeholder="请输入编制单位"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="投资概算" prop="projectInvestmentEstimate">
              <el-input
                v-model="form.projectInvestmentEstimate"
                placeholder="请输入投资概算"
              >
                <template slot="append">万元</template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="上报时间" prop="reportTime">
              <el-date-picker
                clearable
                size="small"
                style="width: 100%"
                v-model="form.reportTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择上报时间"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批时间" prop="approvalTime">
              <el-date-picker
                clearable
                size="small"
                style="width: 100%"
                v-model="form.approvalTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择审批时间"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批复部门" prop="approvalDepartment">
              <el-input
                v-model="form.approvalDepartment"
                placeholder="请输入批复部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批复文号" prop="approvalNo">
              <el-input
                v-model="form.approvalNo"
                placeholder="请输入批复文号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="批复意见" prop="approvalOpinion">
              <el-input
                v-model="form.approvalOpinion"
                placeholder="请输入批复意见"
                type="textarea"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="项目内容" prop="projectContent">
              <el-input
                v-model="form.projectContent"
                placeholder="请输入项目内容"
                type="textarea"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="研究报告文件" prop="feasibilityReportFile">
              <el-upload
                class="upload-demo"
                action="thinking/common/upload"
                :headers="headers"
                :before-upload="(file) => $fileBeforeUpload(file, 'fileList')"
                :on-preview="handleFilePreview"
                :on-remove="handleFileRemove"
                :before-remove="beforeFileRemove"
                multiple
                :on-exceed="handleFileExceed"
                :on-success="submitFileUpload"
                :file-list="fileList"
              >
                <el-button size="small" type="primary" plain>
                  <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-col :span="12">
            <el-form-item
              label="可行性研究报告相关附件"
              prop="opinionAttachment"
            >
              <!-- <el-input
                v-model="form.opinionAttachment"
                placeholder="请输入意见附件"
              /> -->
              <el-upload
                class="upload-demo"
                action="thinking/common/upload"
                :headers="headers"
                :before-upload="
                  (file) => $fileBeforeUpload(file, 'attachmentList')
                "
                :on-preview="handleAttachmentPreview"
                :on-remove="handleAttachmentRemove"
                :before-remove="beforeAttachmentRemove"
                multiple
                :on-exceed="handleAttachmentExceed"
                :on-success="submitAttachmentUpload"
                :file-list="attachmentList"
              >
                <el-button size="small" type="primary" plain>
                  <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.reportMsg.isApproval }}
          </el-descriptions-item> -->
          <el-descriptions-item>
            <template slot="label"> 项目名称 </template>
            <!-- {{ this.viewTitle }} -->
            {{ this.reportMsg.projectName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 项目编码 </template>
            {{ this.reportMsg.projectCode }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 行政区划 </template>
            {{ $formatAdcd(this.reportMsg) }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 编制单位 </template>
            {{ this.reportMsg.compilingUnit }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 投资概算（万元） </template>
            {{ this.reportMsg.projectInvestmentEstimate }}
            <!-- {{ this.reportMsg.projectInvestmentEstimate ? " 万元" : "" }} -->
          </el-descriptions-item>
          <!-- <el-descriptions-item>
            <template slot="label"> 项目编码 </template>
            {{ this.reportMsg.projectCode }}
          </el-descriptions-item> -->
          <el-descriptions-item>
            <template slot="label"> 上报时间 </template>
            {{ this.reportMsg.reportTime }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 审批时间 </template>
            {{ this.reportMsg.approvalTime }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 批复部门 </template>
            {{ this.reportMsg.approvalDepartment }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 批复文号 </template>
            {{ this.reportMsg.approvalNo }}
          </el-descriptions-item>
          <el-descriptions-item span="2">
            <template slot="label"> 批复意见 </template>
            {{ this.reportMsg.approvalOpinion }}
          </el-descriptions-item>

          <el-descriptions-item span="2">
            <template slot="label"> 项目内容 </template>
            {{ this.reportMsg.projectContent }}
          </el-descriptions-item>

          <el-descriptions-item span="2">
            <template slot="label"> 可行性研究报告文件 </template>
            <template v-if="this.reportMsg.feasibilityReportFile">
              <div
                v-for="(item, index) in JSON.parse(
                  this.reportMsg.feasibilityReportFile
                )"
                :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 span="2">
            <template slot="label"> 可行性研究报告相关附件 </template>
            <template v-if="this.reportMsg.feasibilityReportAttachment">
              <div
                v-for="(item, index) in JSON.parse(
                  this.reportMsg.feasibilityReportAttachment
                )"
                :key="item + index"
              >
                {{ item.name }}

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

<script>
import {
  listFeasibility,
  getFeasibility,
  delFeasibility,
  addFeasibility,
  updateFeasibility,
  exportFeasibility,
} from "@/api/earlyStage/feasibility";
import { listProposal, getProposal } from "@/api/earlyStage/proposal";
import { getFileStream } from "@/api/system/upload";
import { getToken } from "@/utils/auth";
import { getAreasData } from "@/api/areas/index";
import { regionData, codeToText, TextToCode } from "element-china-area-data";
import { v4 as uuidv4 } from "uuid";

export default {
  name: "Feasibility",
  data() {
    return {
      // 禁选当前时间之后的时间
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() > new Date().getTime();
        },
      },
      areasOptionProps: {
        emitPath: false,
        checkStrictly: true, //选择任意一级
        // lazy: true,
        // lazyLoad: function qylazyLoad(node) {
        //   // node.level = 5;
        //   console.log("node", node.level);
        // },
      },
      areasOptions: [],
      //附件
      attachmentList: [],
      // 文件
      fileList: [],
      // 请求头
      headers: {
        jianwei: "jwtech " + getToken(),
      },
      //项目名称
      projectNameOptions: [],
      //是否
      IS: ["是", "否"],
      // 面包屑，路由信息
      routeList: [
        {
          path: "/project/report",
          routeName: "可行性研究报告",
        },
      ],
      // 规划类型字典
      projectTypeOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 可行性研究报告表格数据
      feasibilityList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      viewOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ids: null,
        data: {
          projectName: null,
          projectType: null,
          compilingUnit: null,
          projectContent: null,
          projectInvestmentEstimate: null,
          isApproval: null,
          relationProjectProposal: null,
          feasibilityReportFile: null,
          feasibilityReportAttachment: null,
          reportTime: null,
          approvalTime: null,
          approvalOpinion: null,
          projectCode: null,
          proNo: null,
          createUid: null,
          createTime: null,
          updateUid: null,
          updateTime: null,
          owerDept: null,
          remark: null,
        },
        cv: {},
        // 排序方式
        params: {
          // 按哪个字段排序
          orderBy: "create_time",
          // desc降序，升序asc
          sortBy: "desc",
        },
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        isApproval: [
          {
            required: true,
            message: "请选择是否有建议书审批",
            trigger: "change",
          },
        ],
        projectCode: [
          {
            required: true,
            message: "请输入项目编码",
            trigger: "blur",
          },
        ],
        projectType: [
          {
            required: true,
            message: "请选择项目类型",
            trigger: "change",
          },
        ],
        proCode: [
          {
            required: true,
            message: "请输入项目编码",
            trigger: "blur",
          },
        ],
        adcd: [
          {
            required: true,
            message: "请选择行政区划",
            trigger: "change",
          },
        ],
        reportTime: [
          {
            trigger: "blur",
            validator: this.compareTime,
          },
        ],
        approvalTime: [
          {
            trigger: "blur",
            validator: this.compareTime,
          },
        ],
        approvalDepartment: [
          {
            required: true,
            message: "请输入批复部门",
            trigger: "blur",
          },
          { max: 250, message: "字符长度最大为250", trigger: "blur" },
        ],
        approvalNo: [
          {
            required: true,
            message: "请输入批复文号",
            trigger: "blur",
          },
          { max: 250, message: "字符长度最大为250", trigger: "blur" },
        ],
        compilingUnit: [
          { max: 250, message: "字符长度最大为250", trigger: "blur" },
        ],
        projectName: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
        ],
        projectInvestmentEstimate: [
          { 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",
          },
        ],
        approvalOpinion: [
          { max: 65500, message: "字符长度最大为65500", trigger: "blur" },
        ],
        projectContent: [
          { max: 65500, message: "字符长度最大为65500", trigger: "blur" },
        ],
      },
      projectType: "",
      proNo: "",
      projectCode: "",
      proCodeList: [],
      // projectCode: "",
      viewTitle: "",
      reportMsg: {},
      //是否又建议书审批字典
      isApprovalOptions: [],
      isEdit: false,
    };
  },
  created() {
    this.getTreeData();
    this.getList();
    this.getDicts("plan_type").then((response) => {
      this.projectTypeOptions = response.data;
    });
    this.getDicts("whether").then((response) => {
      this.isApprovalOptions = response.data;
    });
  },
  methods: {
    getId(res) {
      // console.log(res)
      getProposal(res.id).then((response) => {
        // console.log(response.data)
        this.projectType = response.data.projectType;
        this.proNo = response.data.proNo;
        this.projectCode = response.data.projectCode;
        this.form.adcd = response.data.adcd;
      });
    },
    compareTime(rule, value, callback) {
      if (this.form.reportTime && this.form.approvalTime) {
        //  dateStr = dateStr.substring(0,19);
        let dateStr1 = this.form.reportTime.replace(/-/g, "/");
        let dateStr2 = this.form.approvalTime.replace(/-/g, "/");
        let timeTamp1 = new Date(dateStr1).getTime();
        let timeTamp2 = new Date(dateStr2).getTime();
        // console.log(1111, timeTamp1, timeTamp2);
        if (timeTamp1 <= timeTamp2) {
          callback();
        } else {
          callback(new Error("上报时间不能晚于审批时间"));
        }
      } else {
        callback();
      }
    },
    formatAdcd(row) {
      if (row.adcd) {
        let provinceCode = row.adcd.slice(0, 2);
        let cityCode = row.adcd.slice(2, 4);
        let areaCode = row.adcd.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;
      });
    },
    handleChange(value) {
      //value为省市区code数组
      if (value) {
        console.log("value", value);
      }
    },
    // getId(res) {
    //   // console.log(res)
    //   getProposal(res.id).then((response) => {
    //     // console.log(response.data);
    //     this.projectType = response.data.projectType;
    //     this.proNo = response.data.proNo;
    //     // console.log("this.proNo ", this.proNo);
    //     this.projectCode = response.data.projectCode;
    //     this.form.adcd = response.data.adcd;
    //     // console.log(55555555, this.form.adcd);
    //   });
    // },
    clear() {
      this.fileList = [];
      this.attachmentList = [];
      this.proCodeList = [];
    },
    // 规划类型字典翻译
    projectTypeFormat(row, column) {
      return this.selectDictLabel(this.projectTypeOptions, row.projectType);
    },
    // projectNameFormat(row) {
    //   return row.projectName.slice(0, row.projectName.indexOf("["));
    // },
    // 是否有建议书审批字典翻译
    isApprovalFormat(row, column) {
      return this.selectDictLabel(this.isApprovalOptions, row.isApproval);
    },
    /** 查询可行性研究报告列表 */
    getList() {
      this.loading = true;
      listFeasibility(this.queryParams).then((response) => {
        this.feasibilityList = response.records;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectName: null,
        projectType: null,
        compilingUnit: null,
        projectContent: null,
        projectInvestmentEstimate: null,
        isApproval: null,
        relationProjectProposal: null,
        feasibilityReportFile: null,
        feasibilityReportAttachment: null,
        reportTime: null,
        approvalTime: null,
        approvalOpinion: null,
        projectCode: null,
        proNo: null,
        createUid: null,
        createTime: null,
        updateUid: null,
        updateTime: null,
        owerDept: null,
        remark: null,
      };
      this.resetForm("form");
    },
    // 查询表单重置
    resetQueryForm() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        data: {
          id: null,
          projectName: null,
          projectType: null,
          compilingUnit: null,
          projectContent: null,
          projectInvestmentEstimate: null,
          isApproval: null,
          relationProjectProposal: null,
          feasibilityReportFile: null,
          feasibilityReportAttachment: null,
          reportTime: null,
          approvalTime: null,
          approvalOpinion: null,
          projectCode: null,
          proNo: null,
          createUid: null,
          createTime: null,
          updateUid: null,
          updateTime: null,
          owerDept: null,
          remark: null,
        },
        cv: {},
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // this.queryParams.cv.name = "projectName";
      // this.queryParams.cv.type = "like";
      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.isEdit = false;
      this.form = {};
      this.fileList = [];
      this.attachmentList = [];

      listProposal(this.queryParams).then((response) => {
        this.projectNameOptions = response.records;
      });
      this.open = true;
      this.title = "添加可行性研究报告";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isEdit = true;
      // listProjectinfo(this.queryParams).then((response)=>{
      //   this.projectNameOptions = response.records;
      // })

      const id = row.id || this.ids;
      getFeasibility(id).then((response) => {
        this.form = response.data;
        console.log(99999, this.form);
        // 附件信息
        if (response.data.feasibilityReportFile) {
          this.fileList = JSON.parse(response.data.feasibilityReportFile);
        }
        if (response.data.feasibilityReportAttachment) {
          this.attachmentList = JSON.parse(
            response.data.feasibilityReportAttachment
          );
        }
        this.form.projectName =
          this.form.projectName + "[" + this.form.projectCode + "]";

        // getProjectCode(response.data.proNo).then((response)=>{
        //
        //   this.proCodeList = response.data;
        //   // console.log(this.proCodeList)
        // })
        listProposal(this.queryParams).then((response) => {
          this.projectNameOptions = response.records;
        });
        this.open = true;
        this.title = "修改可行性研究报告";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 附件
          this.form.feasibilityReportFile = JSON.stringify(this.fileList);
          this.form.feasibilityReportAttachment = JSON.stringify(
            this.attachmentList
          );
          if (this.proNo) {
            this.form.proNo = this.proNo;
          }
          if (this.projectCode) {
            this.form.projectCode = this.projectCode;
          }
          if (this.projectType) {
            this.form.projectType = this.projectType;
          }
          if (
            this.form.projectName &&
            this.form.projectName.indexOf("[") != -1
          ) {
            this.form.projectName = this.form.projectName.slice(
              0,
              this.form.projectName.indexOf("[")
            );
          }
          if (this.form.id != null) {
            updateFeasibility(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            if (this.form.isApproval == "0") {
              // console.log("uuidv4()", uuidv4());
              this.form.proNo = uuidv4();
            }
            addFeasibility(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },

    // 查看信息
    viewInfo(row) {
      this.viewTitle = row.projectName;
      getFeasibility(row.id).then((response) => {
        this.reportMsg = response.data;
        // this.reportMsg.projectName =
        //   this.reportMsg.projectName + "[" + this.reportMsg.projectCode + "]";
        console.log("reportMsg", row);
        this.viewOpen = true;
      });
    },
    // 关闭弹窗
    closeView() {
      this.reportMsg = {};
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      if (ids) {
        this.$confirm("是否删除选中的数据？", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return delFeasibility(ids);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          })
          .catch(function () {});
      } else {
        this.$message.warning("请选择要删除的数据！！");
      }
    },

    // ==============================可研性报告文件==============================
    submitFileUpload(_, fileList) {
      console.log("fileList", fileList);
      this.fileList.push({
        name: fileList.name,
        fileName: fileList.response.fileName,
        url: fileList.response.url,
        uid: fileList.uid,
      });
    },
    // 表格中下载
    downloadFile1(scope, index) {
      // console.log(scope);
      let file = JSON.parse(scope.row.feasibilityReportFile)[index];
      this.handleFilePreview(file);
    },
    // 查看信息中, 下载
    downloadFile2(info, index) {
      console.log(info);
      this.handleFilePreview(info);
    },
    // 点击预览下载文件
    handleFilePreview(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对象
      });
    },
    handleFileRemove(file, fileList) {
      // console.log(file, fileList);
      let index = this.fileList.findIndex((item) => item.uid === file.uid);
      // 删除文件
      this.fileList.splice(index, 1);
    },
    beforeFileRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleFileExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },

    // ==============================相关附件===========================

    submitAttachmentUpload(_, fileList) {
      console.log("fileList", fileList);
      this.attachmentList.push({
        name: fileList.name,
        fileName: fileList.response.fileName,
        url: fileList.response.url,
        uid: fileList.uid,
        // fileList: fileList,
      });
    },
    // 表格中下载
    downloadFile3(scope, index) {
      let file = JSON.parse(scope.row.feasibilityReportAttachment)[index];
      this.handleAttachmentPreview(file);
    },
    // 查看信息中, 下载
    downloadFile4(info, index) {
      console.log(info);
      this.handleAttachmentPreview(info);
    },
    handleAttachmentPreview(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对象
      });
    },
    handleAttachmentRemove(file, fileList) {
      // console.log(file, fileList);
      let index = this.attachmentList.findIndex(
        (item) => item.uid === file.uid
      );
      // 删除文件
      this.attachmentList.splice(index, 1);
    },
    beforeAttachmentRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleAttachmentExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/css/dialog.scss";
// ::v-deep {
//   .el-dialog {
//     margin-top: 2vh !important;
//   }
// }
</style>
