<template>
  <div class="app-container" id="app-container">
    <el-form id="I-form" :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <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="type">
        <el-select v-model="queryParams.type" placeholder="请选择申报类型" clearable>
          <el-option
            v-for="dict in dict.type.bms_declaration_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </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 :gutter="10" id="I-rowOne" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="handleAdd"
          v-if="userType == '01'"
          class="btn"
        >在线申报</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="routerGo"
          v-if="userType == '01'"
          class="btn"
        >补录</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          icon="el-icon-user-solid"
          @click="handleOpenCity"
          v-if="userType == '02'"
          :disabled="deptId != '104' || cityList.length == 0"
          class="btn"
        >市级评定结果确认</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          size="mini"
          @click="handleExport"
          class="btn"
        >导出申报记录清单</el-button>
      </el-col>
    </el-row>
    <el-row id="I-rowTwo" v-if="userType == '02'">
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          size="mini"
          @click="toggleOptions('')"
        >全部</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          size="mini"
          @click="toggleOptions('1', '8')"
        >初审</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          size="mini"
          @click="toggleOptions('2', '7')"
        >复审</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          size="mini"
          @click="toggleOptions('3', '6')"
        >专家评审</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          size="mini"
          @click="toggleOptions('4')"
        >市级评定</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          size="mini"
          @click="toggleOptions('5')"
        >评定通过</el-button>
      </el-col>
    </el-row>
    <!-- :header-cell-style="{
      background:'#cfcccc',color:'#000000'}" -->
    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="menuList"
      :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="projectName" label="项目名称" :show-overflow-tooltip="true" min-width="160"></el-table-column>
      <el-table-column prop="enterpriseName" label="申报单位" :show-overflow-tooltip="true" min-width="180"></el-table-column>
      <el-table-column label="级别" 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="year" label="年份" :show-overflow-tooltip="true"  min-width="80"></el-table-column>
      <el-table-column prop="component" label="申报类型" min-width="110">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bms_declaration_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="责任单位" 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 label="申报表单" :show-overflow-tooltip="true" min-width="130">
        <template slot-scope="scope">
          <div>
            {{ scope.row.projectName.slice(0, scope.row.projectName.length - 2) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="申报途径" min-width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bms_declaration_channels" :value="scope.row.road"/>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="审批状态" min-width="110">
        <template slot-scope="scope">
          <span v-if="scope.row.status == 5" class="approval_status5">评审通过</span>
          <span v-if="scope.row.status == 4" class="approval_status3">市级评定中</span>
          <span v-if="scope.row.status == 3" class="approval_status3">专家评审中</span>
          <span v-if="scope.row.status == 2" class="approval_status1">复审中</span>
          <span v-if="scope.row.status == 1" class="approval_status1">初审中</span>
          <span v-if="scope.row.status == 0" class="approval_status0">草稿</span>
          <span v-if="scope.row.status == 8" class="approval_status8">初审-拒绝</span>
          <span v-if="scope.row.status == 7" class="approval_status9">复审-拒绝</span>
          <span v-if="scope.row.status == 6" class="approval_status9">专家评审-拒绝</span>
          <span v-if="scope.row.status == 9" class="approval_status9">评定不通过</span>
        </template>
      </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="updateTime" label="更新时间" min-width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="140" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleEdit(scope.row)"
            v-if="userType == '01' && (scope.row.status == 0 || scope.row.status == 8||scope.row.status == 7||scope.row.status == 6||scope.row.status == 9)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDetail(scope.row)"
          >查看详情</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="userType == '02' && scope.row.status == 4 && deptId == '104'"
            @click="handleOpenCity(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="请选择申报表单" :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="getTemplateList" clearable>
                <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="changeTemplateId" :disabled="!this.form.responsibilityUnit" clearable>
                <el-option
                  v-for="dict in templateDataList"
                  :key="dict.templateId"
                  :label="dict.templateName"
                  :value="dict.templateId"
                ></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="请输入说明" disabled></el-input>
            </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="openCity" width="600px" append-to-body>
      <el-form ref="cityFormRef" :model="cityForm" :rules="cityRules" label-width="100px">
        <el-row>
          <el-col :span="14">
            <el-form-item label="评定附件" label-width="100px" prop="fileList">
              <el-upload
                class="upload-demo"
                :show-file-list="true"
                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.cityForm.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">
              <el-button plain @click="frontDownload" v-if="fileList.length<= 0" style="background-color: #f1d78c;">下载需要评定数据</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelCity">取 消</el-button>
        <el-button type="primary" @click="submitCityForm" class="btn">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRecords, exportData, templateList, downloadData, uploadFile, putMunicipalBureauReview } from "@/api/onlineDeclartion/records"
import * as XLSX from 'xlsx'
export default {
  name: "Records",
  dicts: ['sys_show_hide', 'sys_normal_disable', 'bms_declaration_type', 'bms_responsibility_unit', 'bms_level', 'bms_template_type', 'bms_declaration_channels'],
  data() {
    return {
      userType: this.$store.state.user.userType,
      deptId: this.$store.state.user.deptId,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 菜单表格树数据
      menuList: [],
      // 菜单树选项
      menuOptions: [],
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      total: 5,
      // 查询参数
      queryParams: {
        templateName: undefined,
        responsibilityUnit: undefined,
        type: undefined,
        pageNum: 1,
        pageSize: 10,
      },
      enterpriseId: '',
      templateDataList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        responsibilityUnit: [
          { required: true, message: "请选择责任单位", trigger: "blur" }
        ],
        templateId: [
          { required: true, message: "请选择申报表单模版", trigger: "blur" }
        ]
      },
      openCity: false,
      fileList: [],
      cityList: [],
      cityForm: {},
      cityRules:{
        fileList: [
          { required: true, message: "请选择申报表单模版", trigger: "blur" }
        ]
      },
      tabHeader: undefined,
    };
  },
  mounted() {
    this.cancalDebounce();
    window.addEventListener('resize', this.cancalDebounce);
  },
  destroyed() {
    window.removeEventListener('resize', this.cancalDebounce);
  },
  created() {
    console.log(this.$store.state.user.enterpriseId);
    this.getList();
  },
  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;
      if(this.userType == '02') {
        const headerThree = document.getElementById('I-rowTwo'); // 通过元素的 ID 获取元素
        const headerTHeight = headerThree.offsetHeight;
        this.tabHeader = elementHeight - headerHeight - headerOHeight - headerTHeight - paginationtHeight - 140;
      } else {
        this.tabHeader = elementHeight - headerHeight - headerOHeight - paginationtHeight - 140;
      }
      
    },
    routerGo() {
      this.$router.push({ name: 'supplementaryNew' }).catch(()=>{});
    },
    /** 查询菜单列表 */
    getList() {
      this.loading = true;
      if(this.userType == '01'){
        this.queryParams.enterpriseId = this.$store.state.user.enterpriseId
      }
      /** 获取市级需评定数量 */
      listRecords({
        pageNum: 1,
        pageSize: 10,
        ['statusStr[0]']:4,
      }).then(response => {
        this.cityList = response.rows;
      });
      listRecords(this.queryParams).then(response => {
        this.menuList = response.rows;
        this.total = response.total
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        menuId: undefined,
        parentId: 0,
        menuName: undefined,
        icon: undefined,
        menuType: "M",
        orderNum: undefined,
        isFrame: "1",
        isCache: "0",
        visible: "0",
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 切换审批项 */
    toggleOptions(value1,value2) {
      this.queryParams['statusStr[0]'] = value1
      this.queryParams['statusStr[1]'] = value2
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.open = true;
    },
    /** 查看审核详情操作 */
    handleDetail(row){
      this.$router.push({name: 'declareDetailContent',query: {
        templateId: row.templateId,
        templateRecordId: row.templateRecordId,
        pageType: "detail",
        detailId: row.id
      }})
    },
    /** 修改按钮操作 */
    getTemplateList(val) {
      if(val){
        let params = {
          responsibilityUnit: val,
          enterpriseId: this.$store.state.user.enterpriseId,
          pageNum: 1,
          pageSize: 10,
        }
        templateList(params).then(response => {
          console.log(response);
          this.templateDataList = response.rows
        })
      } else {
        this.form.templateId = ''
      }

    },
    changeTemplateId(val) {
      this.templateDataList.forEach(item => {
        if(item.templateId == val) {
          this.form.notes = item.notes
          this.form.templateRecordId = item.templateRecordId
        }
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$router.push({name: 'declareAddContent',query: {
            templateId: this.form.templateId,
            templateRecordId: this.form.templateRecordId,
            pageType: "add",
          }})
        }
      });
    },
    /** 编辑按钮 */
    handleEdit(row) {
      this.$router.push({name: 'declareDetailContent',query: {
        templateId: row.templateId,
        templateRecordId: row.templateRecordId,
        pageType: "edit",
        detailId: row.id,
      }})
    },
    /** 导出按钮操作 */
    handleExport(row) {
      exportData({enterpriseId: row.enterpriseId}).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", `在线申报记录${new Date().getTime()}.xls`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      })
    },
    handleOpenCity() {
      this.openCity = true
    },
    cancelCity() {
      this.openCity = false
      this.fileList= []
      this.cityForm.reviewList = []
      this.cityForm.fileList = []
    },
    //下载模版
    frontDownload() {
      downloadData({ }).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", `评定数据${new Date().getTime()}.xls`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      })
    },
    handleFileUpload(params) {
      this.handle(params)
      const file = params.file
      let cityForm = new FormData()
      cityForm.append('file', file)
      uploadFile(cityForm).then(response => {
        this.fileList = []
        this.fileList.push(file)
        // this.cityForm.fileList = this.fileList
        this.$set(this.cityForm, 'fileList', this.fileList)
        this.cityForm.fileName = params.file.name
      })
    },
    deleteUpload() {
      this.fileList= []
      this.cityForm.reviewList = []
      this.cityForm.fileList = []
    },
    /** 提交审核按钮 */
    submitCityForm: function() {
      // if(this.cityForm.fileName){
      //   console.log('this.cityForm.fileList', this.cityForm.fileName);

      // } else {
        this.$refs["cityFormRef"].validate(valid => {
          if (valid) {
            console.log('this.form.reviewList',this.cityForm.reviewList);
            putMunicipalBureauReview(this.cityForm).then(response => {
              this.$modal.msgSuccess("评审成功");
              this.openCity = false;
              this.getList();
            });
          }
        });
      // }

    },
    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 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['统一信用代码'],
          id: item['对应id'],
          declarationTypeStr: item['申报类型'],
          opinion: item['市级评定结果意见'],
          result: item['市级评定结果，0：通过，1：不通过'],
          year: item['年份'],
        };
        arr.push(obj);
        this.cityForm.reviewList = 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;
// }
.approval_status5 {
  color: #24d3a9;
  position: relative;
  padding-left: 15px;
}
.approval_status5::after {
  position: absolute;
  content: '';
  width: 7px;
  height: 7px;
  border-radius: 50%;
  background-color: #24d3a9;
  left: 5px;
  top: 50%;
  transform: translate(-50%, -50%);
}
.approval_status3 {
  color: #134ee6;
  position: relative;
  padding-left: 15px;
}
.approval_status3::after {
  position: absolute;
  content: '';
  width: 7px;
  height: 7px;
  border-radius: 50%;
  background-color: #134ee6;
  left: 5px;
  top: 50%;
  transform: translate(-50%, -50%);
}
.approval_status1 {
  color: #1890ff;
  position: relative;
  padding-left: 15px;
}
.approval_status1::after {
  position: absolute;
  content: '';
  width: 7px;
  height: 7px;
  border-radius: 50%;
  background-color: #1890ff;
  left: 5px;
  top: 50%;
  transform: translate(-50%, -50%);
}
.approval_status0 {
  color: #cdcccc;
  position: relative;
  padding-left: 15px;
}
.approval_status0::after {
  position: absolute;
  content: '';
  width: 7px;
  height: 7px;
  border-radius: 50%;
  background-color: #cdcccc;
  left: 5px;
  top: 50%;
  transform: translate(-50%, -50%);
}
.approval_status8 {
  color: #f39801;
  position: relative;
  padding-left: 15px;
}
.approval_status8::after {
  position: absolute;
  content: '';
  width: 7px;
  height: 7px;
  border-radius: 50%;
  background-color: #f39801;
  left: 5px;
  top: 50%;
  transform: translate(-50%, -50%);
}
.approval_status9 {
  color: red;
  position: relative;
  padding-left: 15px;
}
.approval_status9::after {
  position: absolute;
  content: '';
  width: 7px;
  height: 7px;
  border-radius: 50%;
  background-color: red;
  left: 5px;
  top: 50%;
  transform: translate(-50%, -50%);
}
</style>
