<template>
  <div class="L-public-main" id="L-size-main">
    <div class="L-main">
      <header id="L-header">
        <el-form :inline="true" :model="formInline" size="small" class="demo-form-inline" ref="queryFrom">
          <el-col :span="20">
            <el-form-item label="企业名称:" prop="enterpriseName">
              <el-input v-model.trim="formInline.enterpriseName" placeholder="请输入内容"></el-input>
            </el-form-item>
            <!-- <el-form-item label="统一社会信用代码:" prop="enterUnit">
              <el-input v-model.trim="formInline.enterUnit" placeholder="请输入内容"></el-input>
            </el-form-item>
            <el-form-item label="经营状态:" prop="policyLevel">
              <el-select class="ignoreElement" v-model="formInline.policyLevel" placeholder="请选择">
                <el-option
                  label="省级"
                  value="0">
                </el-option>
                <el-option
                  label="市级"
                  value="1">
                </el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item>
              <el-button size="mini" @click="resetQuery('queryFrom')">重置</el-button>
              <el-button size="mini" type="primary" @click="handleQuery('queryFrom')">查询</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <div class="btnss">
              <el-button type="primary" class="import-btn" icon="icon iconfont icon-jc-daoru" size="mini" @click="importBtn">导入企业</el-button>
              <el-button type="primary" class="import-btn import-btn-export" size="mini" @click="deriveBtn" :loading="exportLoading">导出</el-button>
            </div>
          </el-col>
        </el-form>
      </header>
      <section>
        <el-table v-loading="loading" :data="tableData" :row-class-name="tableRowClassName" :height="tabHeader" :max-height="tabHeader">
          <el-table-column label="企业名称" prop="enterpriseName" />
          <el-table-column label="统一社会信用代码" prop="creditCode" />
          <!-- <el-table-column label="法定代表人" prop="policyLevel" />
          <el-table-column label="经营状态" prop="enterTime" />
          <el-table-column label="成立日期" prop="createBy" />
          <el-table-column label="注册资本" prop="createTime" /> -->
          <el-table-column label="组织机构代码" prop="institutionCode" />
          <el-table-column label="登记注册统计类别" prop="statisticalCategories" />
          <el-table-column label="行业代码" prop="industryCode" />
          <el-table-column label="企业类型" prop="enterpriseType" />
          <el-table-column label="所属行业" prop="industry" />
          <el-table-column label="成立日期" prop="createTime">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime,"{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="组织机构代码" prop="createTime" />
          <el-table-column label="参保人数" prop="createTime" />
          <el-table-column label="曾用名" prop="createTime" />
          <el-table-column label="注册地址" prop="createTime" />
          <el-table-column label="注册类型" prop="createTime" />
          <el-table-column label="经营范围" prop="createTime" /> -->
          <el-table-column label="操作" prop="userId" class-name="table-operation">
            <template slot-scope="scope">
              <span class="look-info" @click="goInfo(scope.row)">查看详情</span>
              <!-- <span class="edit-info" @click="editInfo(scope.row)">编辑</span>
              <span class="del-info" @click="delInfo(scope.row)">删除</span> -->
            </template>
          </el-table-column>
        </el-table>
        <my-pagination 
          id="L-pagination"
          :total="total"
          :page="pagination.pageNum"
          :limit="pagination.pageSize"
          @pagination="getPagination"
          :current-page.sync="pagination.pageNum" 
        ></my-pagination>
      </section>
    </div>
    <!--  :rules="rules" -->
    <my-dialog :title="title" @close="importClose" @confirm="confirm" ref="importProject" closeText="关闭" :myclass="true">
      <el-row>
        <el-col :span="12">
          <div class="btnsFlex">
            <el-button type="primary" class="import-btn" icon="icon iconfont icon-jc-daoru" size="mini" @click="importExcel">导入企业</el-button>
            <el-upload
              ref="upload"
              :limit="1"
              v-show="false"
              accept=".xlsx, .xls"
              :before-upload="handleBeforeUpload"
              :headers="upload.headers"
              :action="upload.url"
              :disabled="upload.isUploading"
              :on-progress="handleFileUploadProgress"
              :on-success="handleFileSuccess"
            >
              <template slot="trigger">
                <!-- <div ref="uploadRef">
                  <i class="icon iconfont icon-jc-daoru"></i>
                  导入新项目
                </div> -->
                <el-button type="primary" class="import-btn" icon="icon iconfont icon-jc-daoru" size="mini" ref="uploadRef">导入企业</el-button>
              </template>
            </el-upload>
          </div>
        </el-col>
        <el-col :span="12">
          <el-button type="text" @click="frontDownload">下载模板</el-button>
        </el-col>
        <!-- <el-col :span="12">
          文件列表
          <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
            <li :key="file.url" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
              <el-link :href="`${baseUrl}${file.url}`" :underline="false" target="_blank">
                <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
              </el-link>
              <div class="ele-upload-list__item-content-action">
                <el-link :underline="false" @click="handleDelete(index)" type="danger">删除</el-link>
              </div>
            </li>
          </transition-group>
        </el-col> -->
      </el-row>
    </my-dialog>
  </div>
</template>
<script>
import myPagination from "@/views/components/Pagination/index.vue"
import myDialog from "@/views/components/myDialog/index.vue"
import { getEnterList, enterpriseBasicInfoNew, enterpriseBasicInfoChange, enterpriseBasicInfoId, enterpriseBasicInfoDel } from "@/api/jin_ji_hu/enterList"
import { getToken } from "@/utils/auth";
export default {
  components:{myPagination, myDialog},
  dicts: ['jjh_project_type'],
  data() {
    return {
      userType: this.$store.state.user.userType,
      deptId: this.$store.state.user.deptId,
      total:0,
      pagination: {
        pageNum:1,
        pageSize:10,
      },
      loading:false,
      formInline: {
        enterpriseName: '',
      },
      tableData:[],
      tabHeader: undefined,
      addFrom: {
        name:"",
        joinProject:"",
        enterUnit:"",
        policyLevel:"",
        enterTime:"",
      },
      rules:{
        name:[
          { required: true, message: '请填写政策文件名称', trigger: 'blur' }
        ],
        joinProject:[
          { required: true, message: '请填写政策等级', trigger: 'blur' }
        ],
        enterUnit:[
          { required: true, message: '请填写发文单位', trigger: 'blur' }
        ],
        policyLevel:[
          { required: true, message: '请选择发文时间', trigger: 'change' }
        ],
        enterTime:[
          { required: true, message: '请选择关联项目', trigger: 'change' }
        ],
      },
      title:"导入企业",
      infoVisible:false,
      baseUrl: location.origin + '/api' ,
      // 用户导入参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: location.origin + '/api'  + "/system/enterpriseBasicInfo/importEnterprise"
      },
      fileList: [],
      number: 0,
      uploadList: [],
      // 导出遮罩层
      exportLoading: false,
    }
  },
  mounted() {
    this.cancalDebounce();
    window.addEventListener('resize', this.cancalDebounce);
    if(this.$route.params.enterpriseName) {
      this.formInline.enterpriseName = this.$route.params.enterpriseName;
      this.pagination = { ...this.pagination,...this.formInline };
    }
    this.getList();
  },
  destroyed() {
    window.removeEventListener('resize', this.cancalDebounce);
  },
  methods:{
    // 列表获取
    getList(){
      this.loading = true;
      getEnterList(this.pagination).then(res=>{
        this.loading = false;
        this.total = res.total;
        this.tableData = res.rows;
      })
    },
    // 获取页码
    getPagination(pages) {
      this.pagination.pageNum = pages.page;
      this.pagination.pageSize = pages.limit;
      this.getList();
    },
    // 查询
    handleQuery() {
      this.pagination = {
        pageNum: 1,
        pageSize: 10
      }
      this.pagination = { ...this.pagination,...this.formInline };
      // console.log(this.pagination);
      // console.log(this.formInline);
      this.getList();
    },
    // 重置
    resetQuery(formName){
      this.$refs[formName].resetFields();
      this.pagination = {
        pageNum: 1,
        pageSize: 10
      }
      this.getList();
    },
    // 修改table背景色
    tableRowClassName({row, rowIndex}){
      if (rowIndex % 2 !== 0) {
        return 'evenNumber-row';
      }
      return '';
    },
    // 查看详情
    goInfo(row){
      this.$router.push({
        name: 'enterInfo',
        query: { userId: row.id, creditCode: row.creditCode }
      })
    },
    // 编辑
    editInfo(row){
    },
    // 导出操作
    deriveBtn(){
      this.$confirm("是否确认导出企业库数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          this.download(
            "/system/enterpriseBasicInfo/export",
            {
              ...this.formInline
            },
            "企业库数据" + new Date().getTime() + ".xlsx"
          );
          this.exportLoading = false;
        })
        .catch(() => { });
    },
    // 导入按钮
    importBtn(){
      this.$refs.importProject.open();
    },
    // 导入事件触发
    importExcel(){
      this.$refs['upload'].$refs['upload-inner'].handleClick()
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      this.$modal.loading("正在上传文件,请稍候...");
      return true;
    },
    handleFileUploadProgress(){},
    // 文件上传成功
    handleFileSuccess(response, file, fileList) {
      if(response.code === 200) {
        this.$refs.upload.clearFiles();
        this.$alert(
          "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
            response.msg +
            "</div>",
          "导入结果",
          { dangerouslyUseHTMLString: true }
        );
        this.importClose();
        this.$refs.importProject.close();
        this.$modal.closeLoading();
        this.getList();
      } else {
        this.$modal.closeLoading();
        this.$modal.msgError(response.msg);
      }
    },
    //下载模版
    frontDownload() {
      var a = document.createElement("a"); //创建一个<a></a>标签
      a.href = "/demo/JinJiHu/static/企业库数据.xlsx";
        //给a标签的href属性值加上地址,注意,这里是绝对路径,不用加 点.
        a.download ="企业库模板.xlsx";
        //设置下载文件文件名,这里加上.xlsx指定文件类型,pdf文件就指定.fpd即可
        a.style.display = "none"; // 障眼法藏起来a标签
        document.body.appendChild(a);
        // 将a标签追加到文档对象中
        a.click(); //模拟点击了a标签,会触发a标签的href的读取,浏览器就会自动下载了
        a.remove();
        // 一次性的,用完就删除a标签
    },
    // 导入弹框的关闭事件触发
    importClose(){
      this.$refs.importProject.close();
    },
    // 删除文件
    handleDelete(index) {
      this.fileList.splice(index, 1);
      this.$emit("input", this.listToString(this.fileList));
    },
    // 获取文件名称
    getFileName(name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    // 导入弹框的确认按钮
    confirm(){

    },
    // 删除
    delInfo(row){
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {

        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 屏幕尺寸变化
    cancalDebounce(){
      const element = document.getElementById('L-size-main'); // 通过元素的 ID 获取元素
      const header = document.getElementById('L-header'); // 通过元素的 ID 获取元素
      const pagination = document.getElementById('L-pagination'); // 通过元素的 ID 获取元素
      const elementHeight = element.offsetHeight;
      const headerHeight = header.offsetHeight;
      const paginationtHeight = pagination.offsetHeight;
      this.tabHeader = elementHeight - headerHeight - paginationtHeight - 140;
    }
  },
}
</script>