<template>
  <div class="hidedanger-wrapper">
    <div class="tools-wrapper">
      <el-row :gutter="12">
        <el-col :span="6">
          <el-input v-model="enterSearchInfo" placeholder="请输入企业信息" />
        </el-col>
        <el-col :span="6">
          <el-input v-model="hdSearchInfo" placeholder="请输入隐患信息" />
        </el-col>
        <el-col :span="8">
          <el-button type="success" size="medium" @click="searchLikeEnterInfo">搜索</el-button>
        </el-col>
        <el-col :span="4">
          <el-popover
            placement="bottom"
            trigger="click"
          >
            <el-date-picker
              v-model="hdAnalyzeChosenDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
            <br/>
            <div style="height: 10px;"></div>
            <el-button type="info" @click="exportStatus">隐患整改</el-button>
            <el-button type="warning" @click="exportNoStatus">隐患未整改</el-button>
            <el-button type="danger" @click="exportOvertime">超期未整改</el-button>
            <el-button type="primary" @click="exportHDAnalyze" :disabled="loadingHDAnalyzeExcel" v-loading="loadingHDAnalyzeExcel">导出隐患分析</el-button>
            <el-button slot="reference" type="primary">导出</el-button>
          </el-popover>
        </el-col>
      </el-row>
    </div>
    <el-table
      v-loading="isloading"
      :data="enterdanger"
      style="width: 100%"
      @expand-change="expandHdInfo"
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-table
            :data="props.row.hdlist"
          >
            <el-table-column
              label="序号"
              prop="hdOrder"
              width="60"
            />
            <el-table-column
              label="检查日期"
              prop="hdInspectDate"
              width="90"
            />
            <el-table-column
              label="检查专家"
              prop="hdInspectExpert"
              width="70"
            />
            <el-table-column
              label="隐患名称"
              prop="hdName"
              width="360"
            />
            <el-table-column
              label="隐患图片"
              width="80"
            >
              <template
                slot-scope="scope1"
              >
                <el-image
                  v-if="scope1.row.hdPic"
                  style="width: 50px; height: 50px"
                  :src="'data:image/jpg;base64,' + scope1.row.hdPic"
                  :preview-src-list="['data:image/jpg;base64,' + scope1.row.hdPic]"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="隐患等级"
              width="70"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.hdLevel === 1 ? '一般隐患' : '重大隐患' }}</div>
              </template>
            </el-table-column>
            <el-table-column
              label="隐患描述"
              width="140"
            >
              <template
                slot-scope="scope1"
              >
                <span>{{ scope1.row.hdDesc === 'null' ? '' : scope1.row.hdDesc }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="整改建议"
              prop="hdRectificationSug"
              width="220"
            />
            <!-- <el-table-column
              label="隐患照片"
            >
              <template slot-scope="scope">
                <img :src="scope.row.dgphoto" alt="暂未上传照片">
              </template>
            </el-table-column> -->
            <el-table-column
              label="整改日期"
              prop="hdRectificationDate"
              width="90"
            />
            <el-table-column
              label="验收人"
              width="70"
            >
              <template slot-scope="scope1">
                <span>{{ scope1.row.hdAcceptancePerson === 'null' ? '' : scope1.row.hdAcceptancePerson }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="隐患状态"
              width="90"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.hdStatus === 0 ? '整改中' : '整改完成' }}</div>
              </template>
            </el-table-column>
            <el-table-column
              label="整改图片"
              width="80"
            >
              <template
                slot-scope="scope1"
              >
                <el-image
                  v-if="scope1.row.hdRectificationPic"
                  style="width: 50px; height: 50px"
                  :src="'data:image/jpg;base64,' + scope1.row.hdRectificationPic"
                  :preview-src-list="['data:image/jpg;base64,' + scope1.row.hdRectificationPic]"
                />
              </template>

            </el-table-column>
            <!-- <el-table-column
              label="整改照片"
            >
              <template slot-scope="scope">
                <img :src="scope.row.rectphoto" alt="暂未上传照片">
              </template>
            </el-table-column> -->
            <el-table-column label="操作" width="160" fixed="right">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="warning"
                  @click="editdg($event, scope.$index, scope.row)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="deletedg($event, scope.$index, scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column
        label="企业名称"
        prop="companyName"
      />
      <el-table-column
        label="企业负责人"
        prop="companyChargePer"
      />
      <el-table-column
        label="操作"
      >
        <template slot-scope="scope1">
          <div class="operations-add-import-wrapper">
            <el-button
              size="mini"
              type="primary"
              @click="addDanger($event, scope1.$index, scope1.row)"
            >新增</el-button>
            <!-- <el-input v-model="importFile" type="file">选择文件</el-input> -->
            <div class="import-file-dg-wrapper" @click="importDanger">
              <label class="import-file-dg">
                导入
                <input :ref="`file${scope1.$index}`" multiple class="helloworld" type="file" hidden @change="realImportDanger(scope1.$index, scope1.row)">
              </label>
            </div>
          </div>
          <!-- <el-button
            size="mini"
            type="primary"
            @click="importDanger($event, scope1.$index, scope1.row)"
          >导入</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="currenetPageDegree"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalElement"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 新增窗口 -->
    <el-dialog
      title="新增隐患清单"
      :visible.sync="adddialogform"
      :close-on-click-modal="false"
    >
      <el-form :model="formInfo">
        <el-form-item label="序号">
          <el-input v-model="formInfo.hdOrder" :disabled="true" />
        </el-form-item>
        <el-form-item label="检查日期">
          <el-date-picker
            v-model="formInfo.hdInspectDate"
            type="datetime"
            placeholder="选择日期时间"
          />
        </el-form-item>
        <el-form-item label="检查专家">
          <el-input v-model="formInfo.hdInspectExpert" />
        </el-form-item>
        <el-form-item label="隐患名称">
          <el-input v-model="formInfo.hdName" />
        </el-form-item>
        <el-form-item label="隐患等级">
          <el-select v-model="formInfo.hdLevel" placeholder="隐患等级">
            <el-option label="一般隐患" value="1" />
            <el-option label="重大隐患" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="隐患描述">
          <el-input v-model="formInfo.hdDesc" type="textarea" />
        </el-form-item>
        <el-form-item label="整改建议">
          <el-input v-model="formInfo.hdRectificationSug" type="textarea" />
        </el-form-item>
        <el-form-item label="">
          <img :src="uploadHdUrl" alt="暂未选择图片" style="width: 60%;">
        </el-form-item>
        <el-form-item label="">
          <label class="import-file-dg" style="color: #1890ff;display:inline-block;border: 1px solid #1890ff;">
            导入隐患图片
            <input :ref="`addhdpic`" class="helloworld" type="file" hidden accept="image/jpeg" @change="addhdPicChange">
          </label>
        </el-form-item>
        <el-form-item label="">
          <div v-for="(item, index) in addEnterhdPics" :key="item.name + index">{{ item.name }}</div>
        </el-form-item>
        <el-form-item label="整改日期">
          <el-date-picker
            v-model="formInfo.hdRectificationDate"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="验收人">
          <el-input v-model="formInfo.hdAcceptancePerson" />
        </el-form-item>
        <el-form-item label="隐患状态">
          <el-select v-model="formInfo.hdStatus" placeholder="请选择隐患状态">
            <el-option label="正在整改" value="0" />
            <el-option label="整改完毕" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <img :src="uploadRectUrl" alt="暂未选择图片" style="width: 60%">
        </el-form-item>
        <el-form-item label="">
          <label class="import-file-dg" style="color: #1890ff;display:inline-block;border: 1px solid #1890ff;">
            导入整改图片
            <input :ref="`addrectpic`" class="helloworld" type="file" hidden accept="image/jpeg" @change="addrectpicChange">
          </label>
        </el-form-item>
        <el-form-item label="">
          <div v-for="(item, index) in adEnterrectPics" :key="item.name + index">{{ item.name }}</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clearAllFormInfo">清空全部</el-button>
        <el-button @click="clearPics">清空图片</el-button>
        <el-button @click="adddialogform = false">取消</el-button>
        <el-button type="primary" @click="confirmadddg">确定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑窗口 -->
    <el-dialog
      title="编辑隐患清单"
      :visible.sync="editdialogform"
      :close-on-click-modal="false"
    >
      <el-form :model="formInfo">
        <el-form-item label="序号">
          <el-input v-model="formInfo.hdOrder" :disabled="true" />
        </el-form-item>
        <el-form-item label="检查日期">
          <el-date-picker
            v-model="formInfo.hdInspectDate"
            type="datetime"
            placeholder="选择日期时间"
          />
        </el-form-item>
        <el-form-item label="检查专家">
          <el-input v-model="formInfo.hdInspectExpert" />
        </el-form-item>
        <el-form-item label="隐患名称">
          <el-input v-model="formInfo.hdName" />
        </el-form-item>
        <el-form-item label="隐患等级">
          <el-select v-model="formInfo.hdLevel" placeholder="隐患等级">
            <el-option label="一般隐患" value="1" />
            <el-option label="重大隐患" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="隐患描述">
          <el-input v-model="formInfo.hdDesc" type="textarea" />
        </el-form-item>
        <el-form-item label="整改建议">
          <el-input v-model="formInfo.hdRectificationSug" type="textarea" />
        </el-form-item>
        <el-form-item label="隐患图片">
          <img v-for="(item, index) in editEnterhdPics" v-show="typeof item === 'string'" :key="index" style="width: 60%;" :src="'data:image/jpg;base64,' + item" alt="alt">
        </el-form-item>
        <el-form-item label="">
          <label class="import-file-dg" style="color: #1890ff;display:inline-block;border: 1px solid #1890ff;">
            导入隐患图片
            <input :ref="`edithdpic`" class="helloworld" type="file" hidden accept="image/jpeg" @change="edithdPicChange">
          </label>
        </el-form-item>
        <el-form-item label="">
          <img v-show="editEnterhdPics.length > 0 && typeof editEnterhdPics[0] !== 'string'" :src="uploadEditHdUrl" alt="整改图片" style="width: 60%">
        </el-form-item>
        <el-form-item label="">
          <div v-for="(item, index) in editEnterhdPics" :key="item.name + index">{{ item.name }}</div>
        </el-form-item>
        <el-form-item label="整改日期">
          <el-date-picker
            v-model="formInfo.hdRectificationDate"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="验收人">
          <el-input v-model="formInfo.hdAcceptancePerson" />
        </el-form-item>
        <el-form-item label="隐患状态">
          <el-select v-model="formInfo.hdStatus" placeholder="请选择隐患状态">
            <el-option label="正在整改" value="0" />
            <el-option label="整改完毕" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="整改图片">
          <img v-for="(item, index) in editEnterrectPics" v-show="typeof item === 'string'" :key="index" style="width: 60%;" :src="'data:image/jpg;base64,' + item" alt="alt">
        </el-form-item>
        <el-form-item label="">
          <label class="import-file-dg" style="color: #1890ff;display:inline-block;border: 1px solid #1890ff;">
            导入整改图片
            <input :ref="`editrectpic`" class="helloworld" type="file" hidden accept="image/jpeg" @change="editrectpicChange">
          </label>
        </el-form-item>
        <el-form-item label="">
          <img v-show="editEnterrectPics.length > 0 && typeof editEnterrectPics[0] !== 'string'" :src="uploadEditRectUrl" alt="整改图片" style="width: 60%">
        </el-form-item>
        <el-form-item label="">
          <div v-for="(item, index) in editEnterrectPics" :key="item.name + index">{{ item.name }}</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editdialogform = false">取消</el-button>
        <el-button type="primary" @click="confirmeditdg">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axiosFile from '@/utils/requestfile.js'
import { getAllCompanyInfo, getHideDangeById, deletedgById, getHideDangerBychIds, getAllCompanyInfoByhdName, getHdByName } from '../../api/industry.js'
import axios from 'axios'
import { parseTime } from '@/utils/index.js'
// import { Form } from 'element-ui'
export default {
  data() {
    return {
      // 企业模糊搜索信息
      enterSearchInfo: '',
      // 搜索隐患信息
      hdSearchInfo: '',
      // 总的个数
      totalElement: 0,
      // 当前页的条数
      currenetPageDegree: 10,
      // 当前页码
      currentPage: 1,
      // 企业信息
      enterinfo: '',
      formInfo: {
        // 企业id
        companyId: 12,
        // 验收人
        hdAcceptancePerson: '',
        // 隐患描述
        hdDesc: '',
        // 序号
        hdOrder: 1,
        // 隐患id
        hdId: 1,
        // 检查日期
        hdInspectDate: '',
        // 检查专家
        hdInspectExpert: '',
        // 隐患等级
        hdLevel: '1',
        // 检查名称
        hdName: '',
        // 整改日期
        hdRectificationDate: '',
        // 整改建议
        hdRectificationSug: '',
        // 隐患状态
        hdStatus: '0'
      },
      // 企业隐患总和
      enterdanger: [
      ],
      // 新增隐患清单
      adddialogform: false,
      // 编辑隐患清单
      editdialogform: false,
      // 导入的文件
      importFile: '',
      // 实现模态对话框的开关
      dialogonoff: false,
      // 新增企业信息隐患照片的名称数组
      addEnterhdPics: [],
      // 新增企业信息整改照片的名称数组
      adEnterrectPics: [],
      // 编辑企业信息隐患照片的名称数组
      editEnterhdPics: [],
      // 编辑企业信息整改照片的名称数组
      editEnterrectPics: [],
      // 是否正在加载
      isloading: true,
      // 开关
      onoff: false,
      // 生成上传隐患图片的url
      uploadHdUrl: '',
      // 生成上传整改图片的url
      uploadRectUrl: '',
      // 生成编辑隐患图片的url
      uploadEditHdUrl: '',
      // 生成编辑整改图片的url
      uploadEditRectUrl: '',
      // 导出选择的隐患分析日期区间
      hdAnalyzeChosenDateRange: '',
      // 正在加载 loading
      loadingHDAnalyzeExcel: false
    }
  },
  mounted() {
    this.initDangerInfo()
  },
  methods: {
    // 初始化所有隐患信息
    async initDangerInfo(toPagination) {
      let replaceArray = []
      await getAllCompanyInfo({
        page: toPagination === undefined ? (Number(this.currentPage) - 1) : 0,
        size: this.currenetPageDegree,
        companyName: this.enterSearchInfo
      }).then(res => {
        this.totalElement = res.totalElements
        // this.enterdanger = [...res.content]
        replaceArray = [...res.content]
        replaceArray = replaceArray.sort((a, b) => a.companyId - b.companyId)
        for (let i = 0; i < replaceArray.length; i++) {
          replaceArray[i].hdlist = []
        }
        this.enterdanger = [...replaceArray]
      })
      this.isloading = false
    },
    async initDangerInfo2(toPagination) {
      let replaceArray = []
      await getAllCompanyInfoByhdName(this.enterSearchInfo, this.hdSearchInfo, toPagination === undefined ? (Number(this.currentPage) - 1) : 0, this.currenetPageDegree).then(res => {
        // console.log(res, 'woqunimalegebi')
        console.log(res, '什么鬼啊')
        this.totalElement = res.totalElements
        replaceArray = [...res.content]
        replaceArray = replaceArray.sort((a, b) => a.companyId - b.companyId)
        for (let i = 0; i < replaceArray.length; i++) {
          replaceArray[i].hdlist = []
        }
        this.enterdanger = [...replaceArray]
      })
      this.isloading = false
    },
    // 新增隐患清单
    addDanger($event, index, scope1) {
      // 唤起dialog
      console.log($event, index, scope1)
      // 设置this.form中的companyId
      this.formInfo.companyId = scope1.companyId
      this.formInfo.hdOrder = scope1.hdlist.length + 1
      this.adddialogform = true
    },
    // 导入隐患清单
    importDanger($event, index, row) {
      console.log($event, index, row, 'fsdfdsfsfdsfsdfdsfdsfds')
      // this.$message.error('helloworld')
      // 模态对话框
      if (this.dialogonoff === false) {
        $event.stopPropagation()
        $event.preventDefault()
        this.$alert('请先将文件另存为97-2003(xls)格式', '请注意', {
          confirmButtonText: '确定',
          callback: action => {
            console.log(action, 'helloworld')
            // this.onoff = true
            this.dialogonoff = true
            $event.target.click()
            setTimeout(() => {
              this.dialogonoff = false
            }, 0)
          }
        })
      }
    },
    // 格式化时间
    toolformatTime(date1) {
      let year = 0
      let month = 0
      let day = 0
      let hour = 0
      let minute = 0
      let second = 0
      year = date1.getFullYear()
      month = (date1.getMonth() + 1) < 10 ? '0' + (date1.getMonth() + 1) : (date1.getMonth() + 1)
      day = date1.getDate() < 10 ? '0' + date1.getDate() : date1.getDate()
      hour = date1.getHours() < 10 ? ('0' + date1.getHours()) : date1.getHours()
      minute = date1.getMinutes() < 10 ? ('0' + date1.getMinutes()) : date1.getMinutes()
      second = date1.getSeconds() < 10 ? ('0' + date1.getSeconds()) : date1.getSeconds()
      return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
    },
    // 新增隐患清单确定提交
    confirmadddg($event) {
      console.log($event, '新增隐患清单确认提交')
      console.log(this.formInfo.hdInspectDate, '检查日期')
      console.log(this.formInfo.hdRectificationDate, '整改日期')

      let isToDeleteFormDate = false
      if (!this.formInfo.hdInspectDate) {
        isToDeleteFormDate = true
        this.$confirm('没有添加检查日期', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      }
      if (this.formInfo.hdInspectDate) {
        this.formInfo.hdInspectDate = this.toolformatTime(new Date(this.formInfo.hdInspectDate))
      }
      let isToDeleteDate = false
      if (!this.formInfo.hdRectificationDate) {
        isToDeleteDate = true
      }
      if (this.formInfo.hdRectificationDate) {
        this.formInfo.hdRectificationDate = this.toolformatTime(new Date(this.formInfo.hdRectificationDate))
      }
      const formData = new FormData()
      for (const key of Object.keys(this.formInfo)) {
        formData.append(key, this.formInfo[key])
      }
      if (isToDeleteDate) {
        formData.delete('hdRectificationDate')
      }
      if (isToDeleteFormDate) {
        formData.delete('hdInspectDate')
      }
      for (let i = 0; i < this.addEnterhdPics.length; i++) {
        formData.append('hdPic', this.addEnterhdPics[i])
      }
      for (let i = 0; i < this.adEnterrectPics.length; i++) {
        formData.append('hdRectificationPic', this.adEnterrectPics[i])
      }
      if (this.addEnterhdPics.length === 0) {
        formData.delete('hdPic')
      }
      if (this.adEnterrectPics.length === 0) {
        formData.delete('hdRectificationPic')
      }
      formData.delete('hdId')
      axiosFile({
        url: '/api/thHiddenDanger',
        method: 'POST',
        data: formData
      }).then(res => {
        console.log(res)
        this.$message({
          message: '添加成功',
          type: 'success'
        })
        this.adddialogform = false
        this.isloading = true
        this.initDangerInfo()
        this.clearPics()
      }, () => {
        this.$message.error('添加失败')
      })
    },
    // 编辑隐患清单
    editdg($event, index, row) {
      // 编辑隐患清单
      console.log($event, '编辑隐患清单', index, row)
      this.formInfo = { ...row }
      this.formInfo.hdLevel = this.formInfo.hdLevel + ''
      this.formInfo.hdStatus = this.formInfo.hdStatus + ''
      if (this.formInfo.hdDesc === 'null') {
        this.formInfo.hdDesc = ''
      }
      if (this.formInfo.hdAcceptancePerson === 'null') {
        this.formInfo.hdAcceptancePerson = ''
      }
      getHideDangerBychIds(row.companyId, row.hdId).then(res => {
        if (res && res.content && res.content.length > 0) {
          this.formInfo = { ... res.content[0] }
          if (this.formInfo.hdDesc === 'null') {
            this.formInfo.hdDesc = ''
          }
          if (this.formInfo.hdAcceptancePerson === 'null') {
            this.formInfo.hdAcceptancePerson = ''
          }
          this.formInfo.hdLevel = this.formInfo.hdLevel + ''
          this.formInfo.hdStatus = this.formInfo.hdStatus + ''
          if (res.content[0].hdPic && res.content[0].hdPic.length && res.content[0].hdPic.length > 0) {
            this.editEnterhdPics = [...res.content[0].hdPic]
          } else {
            this.editEnterhdPics = []
          }
          if (res.content[0].hdRectificationPic && res.content[0].hdRectificationPic.length && res.content[0].hdRectificationPic.length > 0) {
            this.editEnterrectPics = [...res.content[0].hdRectificationPic]
          } else {
            this.editEnterrectPics = []
          }
        }
      })
      this.editdialogform = true
    },
    // 编辑隐患清单确认提交
    confirmeditdg($event) {
      console.log($event, '编辑隐患清单确认提交')
      this.formInfo.hdInspectDate = this.toolformatTime(new Date(this.formInfo.hdInspectDate))
      let isToDeleteDate = false
      if (!this.formInfo.hdRectificationDate) {
        isToDeleteDate = true
      }
      if (this.formInfo.hdRectificationDate) {
        this.formInfo.hdRectificationDate = this.toolformatTime(new Date(this.formInfo.hdRectificationDate))
      }
      const formData = new FormData()
      console.log(this.formInfo.hdStatus, '12332323323232113221321312321321')
      for (const key of Object.keys(this.formInfo)) {
        formData.append(key, this.formInfo[key])
      }
      for (let i = 0; i < this.editEnterhdPics.length; i++) {
        console.log(typeof this.editEnterhdPics[i], 'helloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworld')

        if (typeof this.editEnterhdPics[i] === 'string') {
          const bstr = atob(this.editEnterhdPics[i])
          let l = bstr.length
          const u8Arr = new Uint8Array(l)
          while (l--) {
            u8Arr[l] = bstr.charCodeAt(l)
          }
          // const curBlob = new Blob([u8Arr], {
          //   type: 'image/jpg;'
          // })
          const name1 = '' + (Math.random() * 10) + (Math.random() * 10) + (Math.random() * 10) + (Math.random() * 10) + '.jpg'
          const curFile = new File([u8Arr], name1, { type: 'image/jpg' })
          formData.append('hdPic', curFile)
        } else {
          formData.append('hdPic', this.editEnterhdPics[i])
        }
      }
      for (let i = 0; i < this.editEnterrectPics.length; i++) {
        if (typeof this.editEnterrectPics[i] === 'string') {
          const bstr = atob(this.editEnterrectPics[i])
          let l = bstr.length
          const u8Arr = new Uint8Array(l)
          while (l--) {
            u8Arr[l] = bstr.charCodeAt(l)
          }
          // const curBlob = new Blob([u8Arr], {
          //   type: 'image/jpg;'
          // })
          const name1 = '' + (Math.random() * 10) + (Math.random() * 10) + (Math.random() * 10) + (Math.random() * 10) + '.jpg'
          const curFile = new File([u8Arr], name1, { type: 'image/jpg' })
          formData.append('hdRectificationPic', curFile)
        } else {
          formData.append('hdRectificationPic', this.editEnterrectPics[i])
        }
      }
      // if (this.formInfo.hdPic && this.formInfo.hdPic.length && this.formInfo.hdPic.length > 0) {
      //   if (this.edit)
      // }
      if (isToDeleteDate) {
        formData.delete('hdRectificationDate')
      }
      if (this.editEnterhdPics.length === 0) {
        formData.delete('hdPic')
      }
      if (this.editEnterrectPics.length === 0) {
        formData.delete('hdRectificationPic')
      }
      axiosFile({
        url: '/api/thHiddenDanger/update',
        method: 'POST',
        data: formData
      }).then(res => {
        console.log(res)
        this.$message({
          message: '编辑成功',
          type: 'success'
        })
        this.isloading = true
        this.initDangerInfo()
        this.editdialogform = false
      }, () => {
        this.$message.error('编辑失败')
      })
    },
    // 删除隐患清单
    deletedg($event, index, row) {
      this.$confirm('此操作不可逆, 确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(
        () => {
          deletedgById(row.hdId).then(res => {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.isloading = true
            this.initDangerInfo()
          }, () => {
            this.$message.error('删除失败')
          })
        }
      )
    },
    // 导入文件
    realImportDanger(index, row) {
      // this.dialogonoff = false
      console.log(index, row, 'fuck the world')
      // 调用提交按钮
      const formdata = new FormData()
      formdata.append('companyId', row.companyId)
      for (let i = 0; i < this.$refs['file' + index].files.length; i++) {
        formdata.append('files', this.$refs['file' + index].files[i])
      }
      if (this.$refs['file' + index].files.length === 0) {
        return
      }
      axiosFile({
        url: '/api/thHiddenDanger/importExcel',
        method: 'POST',
        data: formdata
      }).then(res => {
        this.$message({
          message: '上传成功',
          type: 'success'
        })
      }, () => {
        this.$message.error('上传失败')
      })
    },
    // 当前页的条数变化
    handleSizeChange(val) {
      this.currenetPageDegree = val
      this.initDangerInfo2()
    },
    // 当前第几页
    handleCurrentChange(val) {
      this.currentPage = val
      this.initDangerInfo2()
    },
    // 模糊搜索
    searchLikeEnterInfo() {
      this.initDangerInfo2('a')
    },
    // 新增隐患照片事件
    addhdPicChange() {
      this.addEnterhdPics = this.$refs['addhdpic'].files
      if (this.addEnterhdPics && this.addEnterhdPics.length && this.addEnterhdPics.length > 0) {
        this.uploadHdUrl = URL.createObjectURL(this.addEnterhdPics[0])
      }
    },
    // 新增导入照片事件
    addrectpicChange() {
      this.adEnterrectPics = this.$refs['addrectpic'].files
      if (this.adEnterrectPics && this.adEnterrectPics.length && this.adEnterrectPics.length > 0) {
        this.uploadRectUrl = URL.createObjectURL(this.adEnterrectPics[0])
      }
    },
    // 生成URL
    generaetUrlForImg(item) {
      // const myarrayBuffer = new ArrayBuffer(item.length)
      // for (let i = 0; i < item.length; i++) {
      //   myarrayBuffer[i] = item[i]
      // }
      return URL.createObjectURL(new Blob([item], { type: 'image/jpeg' }))
    },
    // 编辑隐患照片事件
    edithdPicChange() {
      this.editEnterhdPics = this.$refs['edithdpic'].files
      // console.log(this.editEnterhdPics, 'helloworldhelloworldhelloworldhelloworldhelloworld')
      // if (this.editEnterhdPics && this.editEnterhdPics.length && this.editEnterhdPics.length > 0) {
      //   console.log('进来了吗, 1111111')
      //   // uploadHdUrl 被设置
      //   this.uploadHdUrl = URL.createObjectURL(this.editEnterhdPics[0])
      // }
      if (this.editEnterhdPics && this.editEnterhdPics.length && this.editEnterhdPics.length > 0) {
        this.uploadEditHdUrl = URL.createObjectURL(this.editEnterhdPics[0])
        console.log('这边进来了吗,' + this.uploadEditHdUrl)
      }
    },
    // 编辑整改照片事件
    editrectpicChange() {
      this.editEnterrectPics = this.$refs['editrectpic'].files
      // console.log(this.editEnterrectPics, '')
      // if (this.editEnterrectPics && this.editEnterrectPics.length && this.editEnterrectPics.length > 0) {
      //   console.log('进来了吗, 222222222')
      //   // upload\
      //   this.uploadRectUrl = URL.createObjectURL(this.editEnterrectPics[0])
      // }
      if (this.editEnterrectPics && this.editEnterrectPics.length && this.editEnterrectPics.length > 0) {
        this.uploadEditRectUrl = URL.createObjectURL(this.editEnterrectPics[0])
      }
    },
    // 清空全部
    clearAllFormInfo() {
      // 除了companyId 剩下的都置零
      this.formInfo.hdAcceptancePerson = ''
      // 隐患描述
      this.formInfo.hdDesc = ''
      // 序号
      this.formInfo.hdOrder = this.formInfo.hdOrder++
      // 隐患id
      this.formInfo.hdId = this.formInfo.hdId
      // 检查日期
      this.formInfo.hdInspectDate = ''
      // 检查专家
      this.formInfo.hdInspectExpert = ''
      // 隐患等级
      this.formInfo.hdLevel = '1'
      // 检查名称
      this.formInfo.hdName = ''
      // 整改日期
      this.formInfo.hdRectificationDate = ''
      // 整改建议
      this.formInfo.hdRectificationSug = ''
      // 隐患状态
      this.formInfo.hdStatus = '0'
    },
    // 清空图片
    clearPics() {
      this.addEnterhdPics = []
      this.adEnterrectPics = []
      this.uploadHdUrl = ''
      this.uploadRectUrl = ''
    },
    // 展开事件
    expandHdInfo(row, expanded) {
      console.log(row, expanded, '展开事件被触发')
      let isNotFount = false
      if (expanded && expanded.length && expanded.length > 0) {
        expanded.forEach(item => {
          if (Number(item.companyId) === Number(row.companyId)) {
            isNotFount = true
          }
        })
      }
      // 如果是展开事件并且hdlist不存在
      if (isNotFount === true && row.hdlist.length === 0) {
        this.isloading = true
        // getHideDangeById(Number(row.companyId)).then(resdg => {
        //   row.hdlist = [...resdg.content]
        //   row.hdlist = row.hdlist.sort((a, b) => a.hdId - b.hdId)
        //   for (let j = 0; j < row.hdlist.length; j++) {
        //     row.hdlist[j].hdOrder = j + 1
        //     row.hdlist[j].companyId = Number(row.companyId)
        //     getHideDangerBychIds(row.companyId, row.hdlist[j].hdId).then(res => {
        //       //
        //       if (res && res.content && res.content.length > 0) {
        //         row.hdlist[j].hdPic = res.content[0].hdPic
        //         row.hdlist[j].hdRectificationPic = res.content[0].hdRectificationPic
        //       }
        //     })
        //   }
        //   this.isloading = false
        // }, () => {
        //   this.isloading = false
        // })
        getHdByName(Number(row.companyId), undefined, this.hdSearchInfo, 0, 9999, 'hdId,desc').then(res => {
          row.hdlist = [...res.content]
          row.hdlist = row.hdlist.sort((a, b) => a.hdId - b.hdId)
          for (let j = 0; j < row.hdlist.length; j++) {
            row.hdlist[j].hdOrder = j + 1
            row.hdlist[j].companyId = Number(row.companyId)
            getHdByName(row.companyId, row.hdlist[j].hdId, this.hdSearchInfo, 0, 9999, 'hdId,desc').then(res1 => {
              if (res1 && res1.content && res1.content.length > 0) {
                row.hdlist[j].hdPic = res1.content[0].hdPic
                row.hdlist[j].hdRectificationPic = res1.content[0].hdRectificationPic
              }
            })
          }
          this.isloading = false
        }, () => {
          this.isloading = false
        })
      }
      // if (expanded) {}
      // if (row.hdlist.length > 0) {
      //   return
      // } else {
      //   this.isloading = true
      //   getHideDangeById(Number(row.companyId)).then(resdg => {
      //     row.hdlist = [...resdg.content]
      //     row.hdlist = row.hdlist.sort((a, b) => a.hdId - b.hdId)
      //     for (let j = 0; j < row.hdlist.length; j++) {
      //       row.hdlist[j].hdOrder = j
      //       row.hdlist[j].companyId = Number(row.companyId)
      //     }
      //     this.isloading = false
      //   }, () => {
      //     this.isloading = false
      //   })
      // }
    },
    exportStatus() {
      axios({
        url: process.env.VUE_APP_BASE_API + '/api/thHiddenDanger/export',
        method: 'get',
        responseType: 'blob',
        params: {
          hdStatus: 1
        }
      }).then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', 'export.xls')
        document.body.appendChild(link)
        link.click()
        link.remove()
        window.URL.revokeObjectURL(link.href)
      })
    },
    exportNoStatus() {
      axios({
        url: process.env.VUE_APP_BASE_API + '/api/thHiddenDanger/export',
        method: 'get',
        responseType: 'blob',
        params: {
          hdStatus: 0
        }
      }).then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', 'export.xls')
        document.body.appendChild(link)
        link.click()
        link.remove()
        window.URL.revokeObjectURL(link.href)
      })
    },
    exportOvertime() {
      axios({
        url: process.env.VUE_APP_BASE_API + '/api/thHiddenDanger/export',
        method: 'get',
        responseType: 'blob',
        params: {
          hdStatus: 2
        }
      }).then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', 'export.xls')
        document.body.appendChild(link)
        link.click()
        link.remove()
        window.URL.revokeObjectURL(link.href)
      })
    },
    exportHDAnalyze() {
      if (this.hdAnalyzeChosenDateRange instanceof Array) {
        this.loadingHDAnalyzeExcel = true
        axios({
          url: process.env.VUE_APP_BASE_API + '/api/thHiddenDanger/exportExcel',
          method: 'get',
          responseType: 'blob',
          onDownloadProgress: (ProgressEvent) => {
            console.log(ProgressEvent, 'exportHDAnalyze exportHDAnalyze exportHDAnalyze')
            this.loadingHDAnalyzeExcel = true
            if (this.timerLoadingHDAnalyzeExcel) {
              clearTimeout(this.timerLoadingHDAnalyzeExcel)
            } else {
              this.timerLoadingHDAnalyzeExcel = setTimeout(() => {
                this.loadingHDAnalyzeExcel = false
              }, 500)
            }
          },
          params: {
            startTime: parseTime(new Date(this.hdAnalyzeChosenDateRange[0]), '{y}-{m}-{d}'),
            endTime: parseTime(new Date(this.hdAnalyzeChosenDateRange[1]), '{y}-{m}-{d}')
          }
        }).then(res => {
          console.dir(res, 'console')
          console.log(res, 'this.hdAnalyzeChosenDateRange  this.hdAnalyzeChosenDateRange')
          const url = window.URL.createObjectURL(new Blob([res.data]))
          const link = document.createElement('a')
          link.href = url
          link.setAttribute('download', decodeURI(res.headers['content-disposition'].split("''")[1]))
          document.body.appendChild(link)
          link.click()
          link.remove()
          window.URL.revokeObjectURL(link.href)
        })
      } else {
        this.$message.error('请选择日期')
      }
      
    }
  }

}
</script>

<style lang="scss">
  .hidedanger-wrapper {
    padding: 20px;
  }
  /* input[type="file"] {
    color: lightblue;
  } */
  /* input {
    color: lightblue !important;
    font-size: 16px;
  } */
  /* label {
    margin: 0 10px;
  } */
  .operations-add-import-wrapper {
    display: flex;
    align-items: center;
      .import-file-dg-wrapper {
      display: inline-block;
      margin: 0 20px;
      .import-file-dg {
        color: white;
        border-radius: 3px;
        background-color: #1890ff;
        /* display: inline-block; */
        text-align: center;
        width: 56px;
        height: 28px;
        display: flex;
        align-items: center;
        justify-content: center;
        &:hover {
          /* color: #46a6ff; */
          /* border-color: #badeff; */
          background-color: #46a6ff;
        }
      }
    }
  }
</style>
