<template>
  <div class="risk-detail-wrapper">
    <div class="enter-name-wrapper">
      <!-- <div class="enter-name">{{ '企业: ' + enterRiskDetail.entername }}</div> -->
      <h2 class="enter-name">{{ '企业: ' + enterRiskDetail.entername }}</h2>
    </div>
    <div class="risk-degree-wrapper">
      <!-- <div class="risk-degree-title">风险点数量</div> -->
      <h3 class="risk-degree-title">风险点数量</h3>
      <div class="risk-degree-num">
        <el-row :gutter="12">
          <el-col :span="5">
            <div class="significant-degree-wrapper">
              <div class="singficant-title">重大风险数量：&nbsp;&nbsp;</div>
              <div class="singficant-degree"><el-input v-model="enterRiskDetail.significantSum" /></div>
              <!-- <div class="singficant-subtitle">个</div> -->
            </div>
          </el-col>
          <el-col :span="5">
            <div class="large-degree-wrapper">
              <div class="large-title">较大风险数量：&nbsp;&nbsp;</div>
              <div class="large-degree"><el-input v-model="enterRiskDetail.largeSum" /></div>
              <!-- <div class="large-subtitle">个</div> -->
            </div>
          </el-col>
          <el-col :span="5">
            <div class="general-degree-wrapper">
              <div class="general-title">一般风险数量：&nbsp;&nbsp;</div>
              <div class="general-degree"><el-input v-model="enterRiskDetail.generalSum" /></div>
            </div>
          </el-col>
          <el-col :span="5">
            <div class="low-degree-wrapper">
              <div class="low-title">低风险数量：&nbsp;&nbsp;</div>
              <div class="low-degree"><el-input v-model="enterRiskDetail.lowSum" /></div>
            </div>
          </el-col>
          <div class="tool-btn-wrapper">
            <el-button type="success" size="mini" @click="saveToRiskNums">保存</el-button>
          </div>
        </el-row>
      </div>
    </div>
    <div class="sorlrisk-total-wrapper">
      <div class="sorlrisk-wrapper">
        <h3 class="sorlrisk-title">企业重大/较大风险情况</h3>
        <div class="tool-btn">
          <el-button type="primary" @click="addriskdetail">新增</el-button>
          <div class="import-file-risk-wrapper" @click="imortRisk">
            <label class="import-file-risk">
              导入
              <input ref="riskimportfile" multiple type="file" hidden @change="realImportRisk">
            </label>
          </div>
          <!--<el-button type="success" size="mini" @click="exportRiskseFile">导出</el-button>-->
        </div>
      </div>
      <div class="sorrisk-table-wrapper">
        <el-table
          v-loading="isLoadingAllRisk"
          :data="enterRiskDetail.riskList"
          style="width: 100%"
          border
        >
          <el-table-column
            prop="riskorder"
            label="序号"
            width="60"
          />
          <el-table-column
            prop="riskPoint"
            label="风险点"
            width="80"
          />
          <el-table-column
            prop="riskType"
            label="类型"
            width="80"
          />
          <el-table-column
            prop="riskArea"
            label="区域位置"
            width="80"
          />
          <el-table-column
            prop="riskPossibleCase"
            label="可能发生的事故类型及后果"
            width="240"
          />
          <el-table-column
            prop="riskMeasure"
            label="风险管控措施"
            width="380"
          />
          <el-table-column
            prop="riskControlLevel"
            label="管控层级"
            width="80"
          />
          <el-table-column
            prop="riskChargeDepartment"
            label="责任单位"
            width="120"
          />
          <el-table-column
            prop="riskChargePer"
            label="责任人"
            width="120"
          />
          <el-table-column
            label="是否有视频或监控"
            width="160"
          >
            <template slot-scope="scope">
              {{ (scope.row.riskId === 1225 || scope.row.riskId === 63 || scope.row.riskId === 53 || scope.row.riskId === 58 || scope.row.riskId === 108) ? '有' : (scope.row.riskVideoPath ? '有' : '无') }}
            </template>
          </el-table-column>
          <el-table-column
            prop="riskRemark"
            label="备注"
            width="120"
          />
          <el-table-column
            label="操作"
            width="160"
          >
            <template
              slot-scope="scope"
            >
              <el-button
                size="mini"
                type="warning"
                @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :current-page="currentComRiskPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="currentComRiskNum"
          :total="totalComRiskNum"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleCOMRisksSizeChange"
          @current-change="handleCOMRisksPageChange"
        />
      </div>
    </div>

    <el-dialog
      title="添加风险管控详情"
      :visible.sync="adddialogform"
      :close-on-click-modal="false"
    >
      <el-form :model="riskDetail">
        <el-form-item label="序号" :label-width="'120px'">
          <el-input v-model="riskDetail.riskorder" :disabled="true" />
        </el-form-item>
        <el-form-item label="风险点" :label-width="'120px'">
          <el-input v-model="riskDetail.riskPoint" />
        </el-form-item>
        <el-form-item label="类型" :label-width="'120px'">
          <el-input v-model="riskDetail.riskType" />
        </el-form-item>
        <el-form-item label="区域位置" :label-width="'120px'">
          <el-input v-model="riskDetail.riskArea" />
        </el-form-item>
        <el-form-item label="可能发生的事故类型及后果" :label-width="'120px'">
          <el-input v-model="riskDetail.riskPossibleCase" autosize type="textarea" />
        </el-form-item>
        <el-form-item label="风险管控措施" :label-width="'120px'">
          <el-input v-model="riskDetail.riskMeasure" autosize type="textarea" />
        </el-form-item>
        <el-form-item label="管控层级" :label-width="'120px'">
          <el-input v-model="riskDetail.riskControlLevel" />
        </el-form-item>
        <el-form-item label="责任单位" :label-width="'120px'">
          <el-input v-model="riskDetail.riskChargeDepartment" />
        </el-form-item>
        <el-form-item label="责任人" :label-width="'120px'">
          <el-input v-model="riskDetail.riskChargePer" />
        </el-form-item>
        <el-form-item label="备注" :label-width="'120px'">
          <el-input v-model="riskDetail.riskRemark" />
        </el-form-item>
      </el-form>
      <div class="upload-risk-video">
        <el-row :gutter="30">
          <el-col :span="8">
            <div style="text-align:right;background:#3884CC;font-size: 20px;line-height: 30px;height: 34px;text-align: center;color: #eee;">
              <label style="width: 100%;height: 100%;">
                导入风险点视频
                <input ref="uploadRiskVideo" type="file" hidden>
              </label>
            </div>
          </el-col>
          <el-col :span="16">
            <el-progress :percentage="curUploadProgress" />
          </el-col>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="adddialogcancel">取消</el-button>
        <el-button type="primary" @click="confirmadddialog">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="编辑风险管控详情"
      :visible.sync="editdialogform"
      :close-on-click-modal="false"
    >
      <el-form :model="riskDetail">
        <el-form-item label="序号">
          <el-input v-model="riskDetail.riskorder" :disabled="true" />
        </el-form-item>
        <el-form-item label="风险点">
          <el-input v-model="riskDetail.riskPoint" />
        </el-form-item>
        <el-form-item label="类型">
          <el-input v-model="riskDetail.riskType" />
        </el-form-item>
        <el-form-item label="区域位置">
          <el-input v-model="riskDetail.riskArea" />
        </el-form-item>
        <el-form-item label="可能发生的事故类型及后果">
          <el-input v-model="riskDetail.riskPossibleCase" autosize type="textarea" />
        </el-form-item>
        <el-form-item label="风险管控措施">
          <el-input v-model="riskDetail.riskMeasure" autosize type="textarea" />
        </el-form-item>
        <el-form-item label="管控层级">
          <el-input v-model="riskDetail.riskControlLevel" />
        </el-form-item>
        <el-form-item label="责任单位">
          <el-input v-model="riskDetail.riskChargeDepartment" />
        </el-form-item>
        <el-form-item label="责任人">
          <el-input v-model="riskDetail.riskChargePer" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="riskDetail.riskRemark" />
        </el-form-item>
      </el-form>
      <div class="upload-risk-video">
        <el-row :gutter="30">
          <el-col :span="8">
            <div style="text-align:right;background:#3884CC;font-size: 20px;line-height: 30px;height: 34px;text-align: center;color: #eee;">
              <label style="width: 100%;height: 100%;">
                更改风险点视频
                <input ref="updateRiskVideo" type="file" hidden>
              </label>
            </div>
          </el-col>
          <el-col :span="16">
            <el-progress :percentage="curUploadProgress" />
          </el-col>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editdialogcancel">取消</el-button>
        <el-button type="primary" @click="confirmeditdialog">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axiosFile from '@/utils/requestfile.js'
// 获取企业风险 新增企业风险 修改企业风险 删除企业风险 导出数据
import { getthRisk, addthRisk, editthRisk, deletethRisk, downloadRiskData, getriskNumAnalysis, postriskNumAnalysis, putriskNumAnalysis } from '../../../api/industry.js'
export default {
  data() {
    return {
      riskDetail: {
        // 序号
        riskorder: 1,
        // 区域位置
        riskArea: '',
        // 责任单位
        riskChargeDepartment: '',
        // 责任人
        riskChargePer: '',
        // 管控层级
        riskControlLevel: '',
        // 风险id
        riskId: 0,
        // 风险管控措施
        riskMeasure: '',
        // 风险点
        riskPoint: '',
        // 可能发生的事故类型及后果
        riskPossibleCase: '',
        // 备注
        riskRemark: '',
        // 类型
        riskType: ''
      },
      // 新增对话框
      adddialogform: false,
      // 编辑对话框
      editdialogform: false,
      enterRiskDetail: {
        // 企业名称
        entername: '永和大王',
        // 重大风险数量
        significantSum: 0,
        significantId: 0,
        largeSum: 0,
        largeId: 0,
        generalSum: 0,
        generalId: 0,
        lowSum: 0,
        lowId: 0,
        riskList: [
        ]
      },
      // 是否加载所有风险
      isLoadingAllRisk: false,
      // 当前第几页
      currentComRiskPage: 1,
      // 当前页内的个数
      currentComRiskNum: 10,
      // 总共的风险的个数
      totalComRiskNum: 0,
      // 是否显示alert
      isShowRiskAlert: false,
      // 当前上传进度
      curUploadProgress: 0
    }
  },
  async created() {
    this.enterRiskDetail.entername = this.$route.params.name.split('&')[1]
    this.riskDetail.companyId = Number(this.$route.params.name.split('&')[0])
    await this.initAllRisk()
    await this.getAllRiskNumAnalisis()
    console.log(new Date())
  },
  async mounted() {
    console.log(new Date())
  },
  methods: {
    // 获取所有风险管控数量信息
    async getAllRiskNumAnalisis() {
      await getriskNumAnalysis(this.riskDetail.companyId).then(async(res) => {
        if (res.totalElements === 0) {
          // 调用接口增加四个风险数量
          const p1 = postriskNumAnalysis(this.riskDetail.companyId, '重大风险', 0)
          const p2 = postriskNumAnalysis(this.riskDetail.companyId, '较大风险', 0)
          const p3 = postriskNumAnalysis(this.riskDetail.companyId, '一般风险', 0)
          const p4 = postriskNumAnalysis(this.riskDetail.companyId, '低风险', 0)
          await Promise.all([p1, p2, p3, p4]).then(res => {
            this.getAllRiskNumAnalisis(this.riskDetail.companyId)
          }, () => {
            this.$message.error('初始化失败')
          })
        } else if (res.totalElements > 3) {
          for (let i = 0; i < res.content.length; i++) {
            if (res.content[i].rnaLevel === '重大风险') {
              this.enterRiskDetail.significantSum = res.content[i].rnaNum
              this.enterRiskDetail.significantId = res.content[i].rnaId
              break
            }
          }
          for (let i = 0; i < res.content.length; i++) {
            if (res.content[i].rnaLevel === '较大风险') {
              this.enterRiskDetail.largeSum = res.content[i].rnaNum
              this.enterRiskDetail.largeId = res.content[i].rnaId
              break
            }
          }
          for (let i = 0; i < res.content.length; i++) {
            if (res.content[i].rnaLevel === '一般风险') {
              this.enterRiskDetail.generalSum = res.content[i].rnaNum
              this.enterRiskDetail.generalId = res.content[i].rnaId
              break
            }
          }
          for (let i = 0; i < res.content.length; i++) {
            if (res.content[i].rnaLevel === '低风险') {
              this.enterRiskDetail.lowSum = res.content[i].rnaNum
              this.enterRiskDetail.lowId = res.content[i].rnaId
              break
            }
          }
        }
      })
    },
    // 获取所有的风险管控
    async initAllRisk() {
      // 获取当前风险
      this.isLoadingAllRisk = true
      await getthRisk(this.riskDetail.companyId, this.currentComRiskPage - 1, this.currentComRiskNum).then(res => {
        this.totalComRiskNum = res.totalElements
        this.enterRiskDetail.riskList = [...res.content]
        for (let i = 0; i < this.enterRiskDetail.riskList.length; i++) {
          this.enterRiskDetail.riskList[i].riskorder = i + 1
        }
        this.isLoadingAllRisk = false
      }, () => {
        this.isLoadingAllRisk = false
      })
    },
    // 点击风险管控的编辑按钮
    handleEdit(index, row) {
      console.log(index, row, '难道没有id吗')
      this.riskDetail = { ...row }
      this.editdialogform = true
    },
    // 点击风险管控的删除按钮
    handleDelete(index, row) {
      this.$confirm('确定要删除此项', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        deletethRisk(Number(row.riskId)).then(res => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.initAllRisk()
        }, () => {
          this.$message.error('删除失败')
        })
      }, () => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 增加风险管控详情对话框的显示
    addriskdetail() {
      // 设置序号
      this.riskDetail.riskorder = this.enterRiskDetail.riskList.length + 1
      this.adddialogform = true
    },
    // 取消增加风险管控详情对话框的显示
    adddialogcancel() {
      this.adddialogform = false
    },
    // 确定增加风险管控详情对话框
    confirmadddialog() {
      // 传送数据
      /**
       * 注意*****
       */
      // 要把riskId处理掉
      const replaceRiskDetail = { ...this.riskDetail }
      delete replaceRiskDetail.riskId
      const mForm = new FormData()
      for (const key in replaceRiskDetail) {
        mForm.append(key, replaceRiskDetail[key])
      }
      if (this.$refs.uploadRiskVideo.files.length > 0) {
        console.log('file', this.$refs.uploadRiskVideo.files[0])
        mForm.append('file', this.$refs.uploadRiskVideo.files[0])
      }
      axiosFile({
        url: '/api/thRisk/create',
        method: 'POST',
        data: mForm,
        onUploadProgress: progressEvent => {
          // progressEvent.loaded
          // progressEvent.total
          this.curUploadProgress = ((progressEvent.loaded / progressEvent.total) * 100).toFixed(0)
        }
      }).then(res => {
        this.adddialogform = false
        this.$message({
          type: 'success',
          message: '上传成功'
        })
      })
    },
    // 编辑对话框取消
    editdialogcancel() {
      this.editdialogform = false
    },
    // 确定编辑对话框
    confirmeditdialog() {
      //
      const mFormData = new FormData()
      for (const key in this.riskDetail) {
        mFormData.append(key, this.riskDetail[key])
      }
      if (this.$refs.updateRiskVideo.files.length > 0) {
        mFormData.append('file', this.$refs.updateRiskVideo.files[0])
      }
      axiosFile({
        url: '/api/thRisk/update',
        method: 'POST',
        data: mFormData,
        onUploadProgress: progressEvent => {
          this.curUploadProgress = ((progressEvent.loaded / progressEvent.total) * 100).toFixed(0)
        }
      }).then(res => {
        this.editdialogform = false
        this.$message({
          type: 'success',
          message: '上传成功'
        })
      })
    },
    // 风险分页 页内个数的限制
    handleCOMRisksSizeChange(val) {
      this.currentComRiskNum = val
      console.log(val, '选择页内页数大小变化')
    },
    // 风险换页
    handleCOMRisksPageChange(val) {
      this.currentComRiskPage = val
      // 去请求数据
      this.initAllRisk()
    },
    // 导入风险 对话框控制
    imortRisk($event) {
      if (this.isShowRiskAlert === false) {
        $event.preventDefault()
        $event.stopPropagation()
        this.$alert('请先将文件另存为97-2003(xls)格式', '请注意', {
          confirmButtonText: '确定',
          callback: action => {
            console.log(action, 'helloworld')
            this.isShowRiskAlert = true
            $event.target.click()
            setTimeout(() => {
              this.isShowRiskAlert = false
            }, 0)
          }
        })
      }
    },
    // 选中文件导入风险
    realImportRisk() {
      const formdata = new FormData()
      formdata.append('companyId', this.riskDetail.companyId)
      for (let i = 0; i < this.$refs['riskimportfile'].files.length; i++) {
        formdata.append('files', this.$refs['riskimportfile'].files[i])
      }
      if (this.$refs['riskimportfile'].files.length === 0) {
        return
      }
      axiosFile({
        url: '/api/thRisk/importExcel',
        method: 'POST',
        data: formdata
      }).then(res => {
        this.$message({
          message: '导入成功',
          type: 'success'
        })
        this.initAllRisk()
      }, () => {
        this.$message.error('导入失败')
      })
    },
    // 导出文件
    exportRiskseFile() {
      downloadRiskData(Number(this.riskDetail.companyId)).then(res => {
        const downLoadURL = URL.createObjectURL(new Blob([res]))
        const toa = document.createElement('a')
        document.body.appendChild(toa)
        toa.href = downLoadURL
        toa.download = '' + Math.floor((Math.random() * 10)) + Math.floor((Math.random() * 10)) + Math.floor((Math.random() * 10)) + Math.floor((Math.random() * 10)) + Math.floor((Math.random() * 10)) + '.xls'
        toa.click()
        toa.remove()
      }, () => {
        this.$message.error('导出失败')
      })
    },
    // 保存数量
    saveToRiskNums() {
      const p1 = putriskNumAnalysis({
        companyId: this.riskDetail.companyId,
        rnaId: this.enterRiskDetail.significantId,
        rnaNum: this.enterRiskDetail.significantSum,
        rnaLevel: '重大风险'
      })
      const p2 = putriskNumAnalysis({
        companyId: this.riskDetail.companyId,
        rnaId: this.enterRiskDetail.largeId,
        rnaNum: this.enterRiskDetail.largeSum,
        rnaLevel: '较大风险'
      })
      const p3 = putriskNumAnalysis({
        companyId: this.riskDetail.companyId,
        rnaId: this.enterRiskDetail.generalId,
        rnaNum: this.enterRiskDetail.generalSum,
        rnaLevel: '一般风险'
      })
      const p4 = putriskNumAnalysis({
        companyId: this.riskDetail.companyId,
        rnaId: this.enterRiskDetail.lowId,
        rnaNum: this.enterRiskDetail.lowSum,
        rnaLevel: '低风险'
      })
      Promise.all([p1, p2, p3, p4]).then(res => {
        this.$message({
          message: '修改成功',
          type: 'success'
        })
      }, () => {
        this.$message.error('修改失败')
      })
    }
  }
}
</script>

<style lang="scss">
  .risk-detail-wrapper {
    padding: 20px;
    .enter-name-wrapper {
      font-size: 16px;
    }
    .risk-degree-wrapper {
      border: 1px solid #eee;
      padding: 12px;
      margin: 20px;
      box-shadow: -1px 1px 5px 1px rgba(204, 204, 204, 0.3);
      .risk-degree-title {
        font-size: 16px;
        margin-left: 16px;
      }
      .risk-degree-num {
        font-size: 16px;
        .significant-degree-wrapper {
          display: flex;
          flex-direction: row;
          justify-content: flex-end;
          align-items: center;
          .singficant-degree {
            width: 80px;
          }
        }
        .large-degree-wrapper {
          display: flex;
          flex-direction: row;
          justify-content: flex-end;
          align-items: center;
          .large-degree {
            width: 80px;
          }
        }
        .general-degree-wrapper {
          display: flex;
          flex-direction: row;
          justify-content: flex-end;
          align-items: center;
          .general-degree {
            width: 80px;
          }
        }
        .low-degree-wrapper {
          display: flex;
          flex-direction: row;
          justify-content: flex-end;
          align-items: center;
          .low-degree {
            width: 80px;
          }
        }
        .tool-btn-wrapper {
          position: absolute;
          top: 50%;
          right: 10%;
          transform: translateY(-50%);
          display: flex;
          flex-direction: row;
          justify-content: center;
        }
      }
    }
    .sorlrisk-wrapper {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-content: center;
      .sorlrisk-title {
        margin-left: 50%;
        position: relative;
        transform: translateX(-50%);
      }
      .tool-btn {
        position: relative;
        right: 10%;
        transform: translateX(4px);
        .import-file-risk-wrapper {
          display: inline-block;
          margin: 0 20px;
          .import-file-risk {
            color: white;
            border-radius: 3px;
            background-color: #1890ff;
            text-align: center;
            width: 56px;
            height: 28px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            font-weight: 600;
            &:hover {
              background-color: #46a6ff;
            }
          }
        }
      }
    }
  }
  .sorlrisk-total-wrapper {
    border: 1px solid #eee;
    margin: 20px;
    padding: 12px;
    box-shadow: -2px 2px 5px 1px rgba(204, 204, 204, 0.3);
  }
</style>
