<template>
  <div class="app-container" id="app-container">
    <el-form id="I-form" :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="企业名录分类" prop="enterpriseDirectory">
        <el-input
          v-model="queryParams.enterpriseDirectory"
          placeholder="请输入业名录分类"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申报模版" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入申报模版"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="责任单位" prop="responsibilityUnit">
        <el-select v-model="queryParams.responsibilityUnit" placeholder="请选择责任单位" clearable>
          <el-option
            v-for="dict in dict.type.bms_responsibility_unit"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item class="search_btn">
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" class="btn">查询</el-button>
      </el-form-item>
    </el-form>
    <el-row id="I-rowOne" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="handleAdd"
          class="btn"
        >新增申报记录</el-button>
      </el-col>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="contentList"
      :height="tabHeader"
    >
      <el-table-column label="序号" align="center" width="50" fixed>
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="enterpriseDirectory" label="企业名录分类" :show-overflow-tooltip="true" min-width="190"></el-table-column>
      <el-table-column prop="templateName" label="模版名称" min-width="180" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="级别" min-width="60">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bms_level" :value="scope.row.level"/>
        </template>
      </el-table-column>
      <el-table-column prop="perms" label="申报途径"  min-width="100" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bms_declaration_channels" :value="scope.row.road"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="开放时间" :show-overflow-tooltip="true" min-width="180" >
        <template slot-scope="scope">
          <span>{{ scope.row.startTime }}~{{ scope.row.endTime }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="责任单位" min-width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bms_responsibility_unit" :value="scope.row.responsibilityUnit"/>
        </template>
      </el-table-column>
      <el-table-column prop="notes" label="说明" min-width="210" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime"  min-width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createByName" label="创建人" min-width="80"></el-table-column>
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleView(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleExport(scope.row)"
          >导出</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      id="L-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="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="责任单位" prop="responsibilityUnit">
              <el-select v-model="form.responsibilityUnit" placeholder="请选择责任单位" style="width: 100%;" @change="changeResponsibilityUnit">
                <el-option
                  v-for="dict in dict.type.bms_responsibility_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="申报表单模版" prop="templateId">
              <el-select v-model="form.templateId" placeholder="请选择申报表单模版" style="width: 100%;" @change="changeTemplate">
                <el-option
                  v-for="dict in templateList"
                  :key="dict.id"
                  :label="dict.templateName"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="企业名录分类" prop="enterpriseDirectory">
              <el-input v-model="form.enterpriseDirectory" placeholder="请选择申报表单模版后带出" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="申报时间" prop="reportTime">
              <el-date-picker
                v-model="form.reportTime"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width:  100%;"
                value-format="yyyy-MM-dd"
                @change="changeDateRange"
                >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="申报途径" prop="road">
              <el-select v-model="form.road" placeholder="请选择申报途径" style="width: 100%;">
                <el-option
                  v-for="dict in dict.type.bms_declaration_channels"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="说明" prop="notes">
              <el-input v-model="form.notes" type="textarea" placeholder="请输入说明"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="企业名录维护方式" label-width="150px" prop="isFrame">
              <el-radio-group v-model="form.isFrame">
                <el-radio label="0">Excel批量导入</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="excel导入企业名录" label-width="150px" prop="fileList">
              <el-upload
                class="upload-demo"
                :show-file-list="false"
                action=""
                :limit="1"
                accept=".xlsx,.XLSX,.xls,.XSL"
                :http-request="handleFileUpload"
                :file-list="fileList"
                v-if="fileList.length<= 0"
                >
                <el-button slot="trigger" v-if="fileList.length<= 0" size="small" type="text">上传企业名录</el-button>
              </el-upload>
              <div v-if="fileList.length > 0" style="">
                <span style="color: #409eff;margin-right: 10px;">{{ this.form.fileName }}</span><el-button type="text" style="color: #f56c6c;" @click="deleteUpload">删除</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label-width="0" prop="path">
              <el-button plain @click="frontDownload" v-if="fileList.length<= 0" style="background-color: #f1d78c; border: none;">点击下载导入模版</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm" class="btn">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 查看企业对话框 -->
    <el-dialog title="企业信息列表" :visible.sync="viewVisible" width="680px" append-to-body>
      <el-table
      v-if="refreshTable"
      v-loading="businessLoading"
      :data="businessList"
    >
      <el-table-column label="序号" align="center" width="50" fixed>
        <template slot-scope="scope">
          <span>{{(businessParams.pageNum - 1) * businessParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="enterpriseName" label="企业名称" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="creditCode" label="企业统一信用代码" :show-overflow-tooltip="true"></el-table-column>
    </el-table>
    <pagination
      v-show="businessTotal>0"
      :total="businessTotal"
      :page.sync="businessParams.pageNum"
      :limit.sync="businessParams.pageSize"
      @pagination="getBusinessList"
    />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelView">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTemplate, listBusiness, exportData, addTemplateRecord, putTemplateRecord, listTemplateInfo, getTemplateRecord, uploadFile } from "@/api/onlineDeclartion/enterpriseDirectory"
import * as XLSX from 'xlsx'

export default {
  name: "EnterpriseDirectory",
  dicts: ['sys_show_hide', 'sys_normal_disable', 'bms_responsibility_unit', 'bms_declaration_channels', 'bms_template_type', 'bms_level'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 菜单表格树数据
      contentList: [],
      // 模版数组
      templateList: [],
      templateListLock: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 重新渲染表格状态
      refreshTable: true,
      total: 10,
      // 查询参数
      queryParams: {
        enterpriseDirectory: undefined,
        templateName: undefined,
        responsibilityUnit: undefined,
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {
        enterpriseDirectoryList: []
      },
      // 表单校验
      rules: {
        responsibilityUnit: [
          { required: true, message: "请选择责任单位", trigger: "blur" }
        ],
        templateId: [
          { required: true, message: "请选择模版", trigger: "blur" }
        ],
        notes: [
          { required: true, message: "请输入说明", trigger: "blur" }
        ],
        road: [
          { required: true, message: "请选择申报途径", trigger: "blur" }
        ],
        reportTime: [
          { required: true, message: "请选择日期", trigger: "blur" }
        ],
        isFrame: [
          { required: true, message: "名录维护方式不能为空", trigger: "blur" }
        ],
        fileList: [
          { required: true, message: "请上传企业名录", trigger: "blur" }
        ]
      },
      businessLoading: false,
      viewVisible: false,
      businessList: [],
      businessTotal: 0,
      businessParams: {
        pageNum: 1,
        pageSize: 10,
      },
      fileList: [],
      excelData: [],
      tabHeader: undefined,
    };
  },
  mounted() {
    this.cancalDebounce();
    window.addEventListener('resize', this.cancalDebounce);
  },
  destroyed() {
    window.removeEventListener('resize', this.cancalDebounce);
  },
  created() {
    this.getList();
    this.getTemplateList();
  },
  methods: {
    // 屏幕尺寸变化
    cancalDebounce(){
      const element = document.getElementById('app-container'); // 通过元素的 ID 获取元素
      const header = document.getElementById('I-form'); // 通过元素的 ID 获取元素
      const headerTwo = document.getElementById('I-rowOne'); // 通过元素的 ID 获取元素
      const pagination = document.getElementById('L-pagination'); // 通过元素的 ID 获取元素
      const elementHeight = element.offsetHeight;
      const headerHeight = header.offsetHeight;
      const headerOHeight = headerTwo.offsetHeight;
      const paginationtHeight = pagination.offsetHeight;
      this.tabHeader = elementHeight - headerHeight - headerOHeight - paginationtHeight - 140;
    },
    /** 查询菜单列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then(response => {
        this.contentList = response.rows;
        this.total = response.total
        this.loading = false;
      });
    },

    // 获取模版列表
    getTemplateList() {
      listTemplateInfo({
        pageNum: 1,
        pageSize: 200,
      }).then(response => {
        this.templateList = response.rows
        this.templateListLock = response.rows
      })
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        responsibilityUnit: undefined,
        templateId: null,
        enterpriseDirectory: undefined,
        road: undefined,
        notes: undefined,
        orderNum: undefined,
        isFrame: "0",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.open = true;
      this.fileList = []
      this.title = "在线申报企业名录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getTemplateRecord({templateRecordId: row.templateRecordId}).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "在线申报企业名录";
        this.form.responsibilityUnit = this.form.responsibilityUnit + ''
        this.form.road = this.form.road + ''
        this.form.isFrame = "0"
        this.form.fileList = this.form.fileName
        this.fileList = this.form.fileName
        let arr = []
        arr.push(this.form.startTime, this.form.endTime)
        this.$set(this.form, 'reportTime', arr)
        this.templateList = this.templateListLock.filter((item) => {
          return item.responsibilityUnit == this.form.responsibilityUnit
        })
        // this.form.reportTime = [this.form.startTime, this.form.endTime]
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            putTemplateRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemplateRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.viewVisible = true
      this.businessParams.templateRecordId = row.templateRecordId
      this.getBusinessList()
    },
    /** 取消查看弹窗 */
    cancelView() {
      this.viewVisible = false
    },
    /** 查询企业列表 */
    getBusinessList() {
      this.businessLoading = true;
      listBusiness(this.businessParams).then(response => {
        this.businessList = response.rows;
        this.businessTotal = response.total
        this.businessLoading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport(row) {
      exportData({templateRecordId: row.templateRecordId}).then(response => {
        let url = window.URL.createObjectURL(new Blob([response]))
        let link = document.createElement('a')
        link.style.display = "none"
        link.href = url
        link.setAttribute("download", `${row.enterpriseDirectory}${new Date().getTime()}.xls`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      })
    },
    changeResponsibilityUnit(valid) {
      this.templateList = this.templateListLock.filter((item) => {
        return item.responsibilityUnit == valid
      })
      this.form.templateId = null
      this.form.enterpriseDirectory = null
    },
    changeTemplate(){
      this.templateList.forEach((item) => {
        if(item.id == this.form.templateId){
          this.form.enterpriseDirectory = item.templateName + '企业名录'
        }
      })

      this.$forceUpdate()
    },
    changeDateRange(val) {
      console.log('val: ', val);
      this.$forceUpdate()
      this.form.startTime = val[0]
      this.form.endTime = val[1]
    },

    //下载模版
    frontDownload() {
      var a = document.createElement("a"); //创建一个<a></a>标签
      a.href = "/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标签
    },
    // 删除上传
    deleteUpload() {
      this.fileList = []
      this.form.fileName = null
      this.form.enterpriseDirectoryList = []
    },
    handleFileUpload(params) {
      this.handle(params)
      this.form.fileName = params.file.name
      const file = params.file
      let form = new FormData()
      form.append('file', file)
      uploadFile(form).then(response => {
        this.fileList = []
        this.fileList.push(file)
        this.form.fileList = this.fileList
        console.log('this.fileList: ', this.fileList);
      })
    },

    readFile(file) {
            return new Promise(resolve => {
                let reader = new FileReader();
                reader.readAsBinaryString(file);
                reader.onload = ev => {
                    resolve(ev.target.result);
                }
            })
        },

    // 采集excel数据
    async handle(ev) {
      let character = {
        enterpriseName: {
            text: '企业名字',
            type: 'string'
        },
        creditCode: {
            text: '企业统一信用代码',
            type: 'string'
        }
      }
      let file = ev.file;
      if (!file) return;

    // 读取file中的数据(变成json格式)
    let data = await this.readFile(file); // 上传文件解析出来的二进制数据
    let workbook = XLSX.read(data, {type: 'binary'}); // xlsx.read()通过读取数据方式,创建类似excel的工作目录/表
    let worksheet = workbook.Sheets[workbook.SheetNames[0]];
    // 解析成json数据
    data = XLSX.utils.sheet_to_json(worksheet);
    let arr = []
    data.forEach(item => {
      let obj = {enterpriseName: item['企业名字'], creditCode: item['企业统一信用代码']};
      // for(let key in character) {
      //     if (!character.hasOwnproperty(key)) break;
      //     let v = character[key], // 这地方是个对象
      //         text = v.text,
      //         type = v.type;
      //     v = item[text] || ''; // 变成了一个值
      //     type === 'string' ? (v = String(v)) : null;
      //     ype === 'number' ? (v = Number(v)) : null;
      //     obj[key] = v;
      // }
      arr.push(obj);
      this.form.enterpriseDirectoryList = arr
      }); // 这样写的好处是分离, excel增加字段,我这代码不用变
    }
    }
};
</script>
<style lang="scss" scoped>
// .search_btn {
//   position: absolute;
//   top: 20px;
//   right: 18px;
//   .btn {
//     background-color: #f1d78c;
//     border: none;
//     color: #000;
//   }
// }
// .btn {
//     background-color: #f1d78c;
//     border: none;
//     color: #000;
//   }
/* 悬浮 */
// ::v-deep .el-button:hover {
//   /* background: linear-gradient(#0165eb, #018ff2, #00b7f9) !important; */
//   background: linear-gradient(100deg, #f1d78c, #f1c19d) !important;
//   font-weight: bold;
//   color: #606266;
// }
/*按钮点击*/
// ::v-deep .el-button:focus {
//   background: linear-gradient(100deg, #f1d78c, #f1c19d) !important;
//   /* background: linear-gradient(#0165eb, #018ff2, #00b7f9) !important; */
//   font-weight: bold;
//   color: #606266;
// }
</style>
