<template>
  <!-- 风险清册 -->
  <div class="fullHeight">
    <div v-if="type != 'detail'">
      <div class="searchBox whiteBlock">
        <el-form :inline="true" size="medium" :model="queryInfo" class="demo-form-inline">
          <el-form-item label="风险编号">
            <el-input clearable v-model="queryInfo.code" placeholder="请输入"></el-input>
          </el-form-item>
          <!-- <el-form-item label="状态">
            <el-select v-model="queryInfo.status" placeholder="请选择">
              <el-option v-for="(item, index) in options" :key="index" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="实际完成日期">
            <el-date-picker
              v-model="daterange"
              @change="changeDate"
              type="daterange"
              :range-separator="$t('message.energyManage.to')"
              :start-placeholder="$t('message.energyManage.start')"
              :end-placeholder="$t('message.energyManage.end')"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" plain @click="getProgressListData">查询</el-button>
            <el-button type="warning" plain @click="refreshBtn">刷新</el-button>
            <el-button class="expintBtn" size="medium" type="primary" @click="addBefore(1, null)">
              新增
            </el-button>
            <el-button type="primary" size="medium"  @click="downloadFn">
              下载导入模板
            </el-button>
            <el-upload
              ref="upload"
              :before-upload="beforeAvatarUpload"
              :action="$http.defaults.baseURL + 'xmgl/rtRiskInventoryType/importExcelTemplate'"
              :limit="1"
              :show-file-list="false"
              :data="{ projectSn: $store.state.projectSn }"
              name="excelFile"
              style="float: right; margin: 0px 0px 0 30px"
              :on-success="handleSuccess"
              :headers="headers"
            >
              <el-button size="medium" type="primary" v-loading.fullscreen.lock="fullscreenLoading">
                导入库
              </el-button>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <div class="table_wrap whiteBlock">
        <vue-scroll>
          <el-table
            height="650"
            class="tables"
            :data="listData"
            lazy
            row-key="id"
            :tree-props="{ children: 'children' }"
            :header-cell-style="{'text-align':'center'}"
          >
            <el-table-column prop="processName" label="工序名称">
              <template slot-scope="scope">
                <span
                  v-if="scope.row.children.length == 0 && scope.row.parentId == '0'"
                  :title="scope.row.processName"
                  style="overflow: hidden;white-space: nowrap;text-overflow: ellipsis;width: 150px;"
                >
                  {{ scope.row.processName }}
                </span>
                <span
                  v-else
                  :title="scope.row.processName"
                  style="overflow: hidden;white-space: nowrap;text-overflow: ellipsis;width: 150px;position: absolute;"
                >
                  {{ scope.row.processName }}
                </span>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="code" label="风险编号"> </el-table-column>
            <el-table-column align="center" prop="riskPossibleConsequence" label="风险可能导致的后果"> </el-table-column>
            <el-table-column align="center" prop="riskAssessmentValueD" label="风险评定值D"> </el-table-column>
            <el-table-column align="center" prop="riskLevel" label="风险级别"> </el-table-column>
            <el-table-column align="center" prop="keyFactorsInRiskControl" label="风险控制关键因素"></el-table-column>
            <el-table-column align="center" prop="precaution" label="预防措施">
              <template slot-scope="scope">
                <div :title="scope.row.precaution" class="name-wrapper">
                  {{ scope.row.precaution }}
                </div>
              </template>
            </el-table-column>
            <el-table-column width="300" label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  @click.native.stop="addBefore(2, scope.row)"
                  size="mini"
                  type="text"
                  icon="el-icon-circle-plus-outline"
                >
                  子分项
                </el-button>
                <el-button size="mini" type="text" icon="el-icon-document" @click.native.stop="showDetail(scope.row)">
                  详情
                </el-button>
                <el-button size="mini" type="text" icon="el-icon-edit" @click.native.stop="editBefore(scope.row)">
                  编辑
                </el-button>
                <el-button size="mini" type="text" class="delete-btn" icon="el-icon-delete" @click.native.stop="deleteBefore(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </vue-scroll>
        <el-pagination
          class="pagerBox"
          style="position: absolute; top: 85%; left: 40%"
          @size-change="SizeChange"
          @current-change="CurrentChange"
          :current-page="pagInfo.pageNo"
          :page-sizes="$store.state.PAGESIZRS"
          :page-size="pagInfo.pageSize"
          layout="total, sizes, prev, pager, next"
          :total="Number(pagInfo.total)"
          background
        ></el-pagination>
      </div>
      <!-- '新增父子级工程弹框' -->
      <el-dialog :modal-append-to-body="false" :title="title" :visible.sync="dialogVisible" width="667px" @close="close">
        <div class="dialog_content">
          <el-form ref="addEditForm" label-width="145px" size="medium" class="dialogFormBox" :rules="addEditRules" :model="workerInfo">
            <el-form-item label="工序名称" prop="processName" v-if="dialogType == 3">
              <el-input v-model="parentTaskName" placeholder="请输入" :disabled="dialogType == 3 || title == '详情'"></el-input>
            </el-form-item>
            <el-form-item v-else label="工序名称" prop="processName">
              <el-input :disabled="title == '详情'" v-model="workerInfo.processName" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item v-if="dialogType == 3" label="子工序名称" prop="processName">
              <el-input :disabled="title == '详情'" v-model="workerInfo.processName" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="风险编号" prop="code">
              <el-input :disabled="title == '详情'" v-model="workerInfo.code" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="风险可能导致的后果" prop="riskPossibleConsequence">
              <el-input :disabled="title == '详情'" v-model="workerInfo.riskPossibleConsequence" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="风险评定值D" prop="riskAssessmentValueD">
              <el-input :disabled="title == '详情'" v-model="workerInfo.riskAssessmentValueD" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="风险级别" prop="riskLevel">
              <el-input :disabled="title == '详情'" v-model="workerInfo.riskLevel" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="风险控制关键因素" prop="keyFactorsInRiskControl">
              <el-input :disabled="title == '详情'" v-model="workerInfo.keyFactorsInRiskControl" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="预防措施" prop="precaution">
              <el-input type="textarea" :disabled="title == '详情'" v-model="workerInfo.precaution" placeholder="请输入"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="dialog-footer">
          <el-button class="cancleBtn" @click="dialogVisible = false" icon="el-icon-circle-close" size="medium">取消 </el-button>
          <el-button type="primary" icon="el-icon-circle-check" @click="submitBtn" size="medium">确定 </el-button>
        </div>
      </el-dialog>
      <!-- //查看大图 -->
      <el-dialog :modal-append-to-body="false" :visible.sync="showBigImg">
        <img width="100%" :src="dialogImageUrl" alt="" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  rtRiskInventoryTypeAdd,rtRiskInventoryTypeEdit,rtRiskInventoryTypeDelete,rtRiskInventoryTypePage
} from '@/assets/js/api/workTicketManage'

// import { getCrewListDataApi } from '@/assets/js/api/dailyCheck'
export default {
  mounted() {},
  data() {
    return {
      fullscreenLoading: false,
      rowData: {},
      parentTaskName: '', // 用于存储父级processName
      options: [
        {
          label: '未开始',
          value: 0
        },
        {
          label: '进行中',
          value: 1
        },
        {
          label: '已完成',
          value: 2
        }
        // {
        //   label: '已逾期',
        //   value: 3
        // },
      ],
      pagInfo: {
        pageNo: 1, //页数
        pageSize: 10, //条数
        total: 0 //总条数
      },
      radio: 1,
      uploadShow: false, //导入弹框
      dialogType: 1,
      title: '',
      daterange: [],
      fileList: [], //上传文件
      downUrl: '', //下载文件地址
      projectSn: '',
      createUserId: '',
      listData: [],
      uploadUrl: '',
      fileUrl: '',
      dialogVisible: false, //新增弹窗
      workerInfo: {
        code: "",
        keyFactorsInRiskControl: "",
        level: 0,
        name: "",
        parentId: 0,
        precaution: "",
        processName: "",
        projectSn: "",
        riskAssessmentValueD: "",
        riskLevel: "",
        riskPossibleConsequence: ""
      },
      principalLsit: [], //负责人
      seedId: '',
      showTime: false, //工期
      queryInfo: {
        code: '',

      },
      type: 'add',
      addEditRules: {
        processName: [
          {
            required: true,
            message: this.$t('message.personnelPosition.required'),
            trigger: 'blur'
          }
        ],
      },
      dialogImageUrl: '',
      showBigImg: false,
      times: '',
      // 时间限制
      pickerOptions: {
        // 对象
        disabledDate: time => {
          let nowData = this.times
          nowData = new Date(nowData.setDate(nowData.getDate() - 1))
          return time > nowData
          // return time.getTime() < Date.now()- 1 * 24 * 3600 * 1000;
        }
      },
      fileName: ''
    }
  },
  computed: {
    headers() {
      return { Authorization: this.$store.state.userInfo.token }
    },
    dateAfter() {
      // 动态起始时间
      const startTimestamp = Date.now() * 1 - 24 * 60 * 60 * 1000
      const endTimestamp = Date.parse(this.workerInfo.finishDate) * 1 - 24 * 60 * 60 * 1000
      return {
        disabledDate(time) {
          const timestamp = time.getTime()
          if (endTimestamp) {
            if (timestamp >= startTimestamp && timestamp <= endTimestamp) {
              return false
            } else {
              return true
            }
          } else {
            return timestamp <= startTimestamp
          }
        }
      }
    },
    dateBefore() {
      // 动态起始时间
      // const startTimestamp = Date.parse(this.workerInfo.startDate)
      const specifiedDate = new Date(this.workerInfo.startDate) // 指定的日期
      const prevDay = new Date(specifiedDate) // 创建一个新的 Date 对象，使用同样的日期
      prevDay.setDate(specifiedDate.getDate() - 1) // 将日期设置为前一天的日期

      const lastTime = prevDay.getTime() // 获取前一天的时间戳
      // const startTimestamp = new Date(this.workerInfo.startDate)
      return {
        disabledDate(time) {
          const timestamp = time.getTime()
          if (timestamp > lastTime) {
            // console.log("计划结束时间",startTimestamp,timestamp)
            return false
          }
          return true
        }
      }
    },
    actualDateBefore() {
      // 动态起始时间
      // const startTimestamp = Date.parse(this.workerInfo.startDate)
      const specifiedDate = new Date(this.workerInfo.actualStartDate) // 指定的日期
      const prevDay = new Date(specifiedDate) // 创建一个新的 Date 对象，使用同样的日期
      prevDay.setDate(specifiedDate.getDate() - 1) // 将日期设置为前一天的日期

      const lastTime = prevDay.getTime() // 获取前一天的时间戳
      // const startTimestamp = new Date(this.workerInfo.startDate)
      return {
        disabledDate(time) {
          const timestamp = time.getTime()
          if (timestamp > lastTime) {
            // console.log("计划结束时间",startTimestamp,timestamp)
            return false
          }
          return true
        }
      }
    }
  },

  created() {
    this.projectSn = this.$store.state.projectSn
    this.createUserId = this.$store.state.userInfo.userId
    this.uploadUrl = this.$store.state.UPLOADURL
    this.fileUrl = this.$store.state.FILEURL
    this.downUrl = this.$http.defaults.baseURL + 'xmgl/progressTask/downloadTemplate'
    this.getProgressListData()
    // this.getCrewListData()
  },
  methods: {
    //导入确定提交
    handleUploadConfirm() {
      if (this.fileName == '') {
        this.$message.warning('请先上传文件')
        return
      } else {
        this.uploadShow = false
        this.$message.success('操作成功')
        this.getProgressListData()
      }
    },
    handleRadioChange(val) {
      this.radio = val
    },
    //获取列表数据
    getProgressListData() {
      let data = {
        projectSn: this.projectSn,
        pageNo: this.pagInfo.pageNo,
        pageSize: this.pagInfo.pageSize,
        code: this.queryInfo.code,
        // processName: this.queryInfo.processName,
        // status: this.queryInfo.status,
        // actualFinishDate_begin: this.queryInfo.actualStartDate,
        // actualFinishDate_end: this.queryInfo.actualFinishDate
      }
      rtRiskInventoryTypePage(data).then(res => {
        if (res.code == 200) {
          this.listData = res.result.records
          this.pagInfo.total = res.result.total
        }
      })
    },
    //获取选中作业类型、工序及部位
    // getCrewListData() {
    //   let data = {
    //     projectSn: this.projectSn
    //   }
    //   getWorkTickDetailText(data).then(res => {
    //     if (res.code == 200) {
    //       this.principalLsit = res.result
    //       console.log('获取负责人下拉', this.principalLsit)
    //     } else {
    //       this.$message.error(res.message)
    //     }
    //   })
    // },
    //新增
    addBefore(addType, value) {
      if (addType == 1) {
        this.title = '新增分项'
        this.dialogType = 1
      } else {
        console.log('新增子分项点击', value)
        this.title = '新增子分项'
        this.dialogType = 3
        this.workerInfo.parentId = value.id
        this.parentTaskName = value.processName
      }
      this.dialogVisible = true
    },
    // 编辑按钮
    editBefore(val) {
      this.dialogType = 2
      this.title = '编辑分项'
      console.log('当前点击的行', val)
      this.workerInfo = JSON.parse(JSON.stringify(val))
      this.workerInfo.id = val.id
      this.workerInfo.status = val.status
      this.dialogVisible = true
    },
    //编辑
    submitBtn() {
      this.$refs.addEditForm.validate(valid => {
        if (valid) {
          let data = JSON.parse(JSON.stringify(this.workerInfo))
          data.projectSn = this.$store.state.projectSn
          if (this.dialogType == 1) {
            rtRiskInventoryTypeAdd(data).then(res => {
              if (res.code == 200) {
                this.$message.success(res.message)
                this.dialogVisible = false
                this.getProgressListData()
              }
            })
          } else if (this.dialogType == 2) {
            data.id = this.workerInfo.id
            rtRiskInventoryTypeEdit(data).then(res => {
              if (res.code == 200) {
                this.$message.success(res.message)
                this.dialogVisible = false
                this.getProgressListData()
              }
            })
          } else if (this.dialogType == 3) {
            data.parentId = this.workerInfo.parentId
            data.level = 2
            rtRiskInventoryTypeAdd(data).then(res => {
              if (res.code == 200) {
                this.$message.success(res.message)
                this.dialogVisible = false
                this.getProgressListData()
              }
            })
          }
        } else {
          return false
        }
      })
    },
    //删除
    deleteBefore(value) {
      this.$confirm(this.$t('message.quality.deleteHint'), this.$t('message.quality.hint'), {
        confirmButtonText: this.$t('message.quality.confirm'),
        cancelButtonText: this.$t('message.quality.cancel'),
        type: 'warning'
      })
        .then(() => {
          let data = {
            id: value.id
          }
          rtRiskInventoryTypeDelete(data).then(res => {
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: this.$t('message.quality.successfullyDelete') + '!'
              })
              this.getProgressListData()
            }
          })
        })
        .catch(() => {})
    },
    close() {
      this.workerInfo = {}
      this.workerInfo.parentId = 0
      this.$nextTick(() => {
        this.$refs.addEditForm.clearValidate()
      })
    },
    close2() {
      this.fileName = ''
      this.radio = 1
    },
    //刷新
    refreshBtn() {
      this.daterange = []
      this.pagInfo.pageNo = 1
      this.pagInfo.pageSize = 10
      this.queryInfo = {
        status: '',
        actualStartDate: '',
        actualFinishDate: '',
        processName: ''
      }
      this.getProgressListData()
    },
    SizeChange(val) {
      this.pagInfo.pageSize = val
      this.getProgressListData()
    },
    CurrentChange(val) {
      this.pagInfo.pageNo = val
      this.getProgressListData()
    },
    //---------------
    // 点击行查看详情
    showDetail(val) {
      this.dialogType = 2
      this.title = '详情'
      console.log('当前点击的行', val)
      this.workerInfo = JSON.parse(JSON.stringify(val))
      this.workerInfo.id = val.id
      this.workerInfo.status = val.status
      this.dialogVisible = true
    },
    //关闭详请组件
    closeDetailFn(val) {
      this.type = val
      this.getProgressListData()
    },
    changeDate() {
      if (this.daterange) {
        this.queryInfo.actualStartDate = this.daterange[0]
        this.queryInfo.actualFinishDate = this.daterange[1]
      } else {
        this.queryInfo.actualStartDate = ''
        this.queryInfo.actualFinishDate = ''
      }
    },
    validateInput() {
      let value = parseInt(this.workerInfo.progressRatio, 10)
      if (isNaN(value) || value < 0 || value > 100 || Math.floor(value) !== value) {
        this.workerInfo.progressRatio = ''
      }
    },
    time1(val) {
      console.log('开始时间', val)
      this.times = val
    },
    time2(val) {
      console.log('结束时间', val)
    },
    // 下载模板
    handleSuccess(res, file) {
      console.log(res)
      this.$refs.upload.clearFiles()
      this.fullscreenLoading = false
      if (res.code == 200 || res.code == 0) {
        this.$message.success(this.$t('message.safeMangeCheck.toLeadSuccess') + '!')
        this.getProgressListData()
      } else {
        this.$message.error(this.$t('message.safeMangeCheck.toLeadFail') + '!')
      }
    },
    beforeAvatarUpload() {
      this.fullscreenLoading = true
    },
    downloadFn() {
      fetch(this.$http.defaults.baseURL + 'xmgl/rtRiskInventoryType/downloadExcelTemplate', {
        headers: {
          Authorization: this.$store.state.userInfo.token
        }
      })
        .then(response => {
          // 处理响应
          if (!response.ok) {
            throw new Error('导出失败')
          }
          return response.blob()
        })
        .then(blob => {
          console.log('导出成功')
          // 创建一个下载链接
          const url = window.URL.createObjectURL(blob)
          // 创建一个<a>元素
          const link = document.createElement('a')
          link.href = url
          link.download = '风险清册导入模板.xlsx' // 指定下载文件的文件名
          // 模拟点击下载链接
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          // 释放URL对象
          window.URL.revokeObjectURL(url)
          // 处理导出的文件
          // 这里可以使用blob对象来获取导出的文件内容或者将其保存到本地
        })
        .catch(error => {
          // 处理错误
          console.error(error)
        })
    },
    //
    beforeUpload(file) {
      console.log('=========', file)
      this.fileName = file.name
    },
    // 上传mpp文件触发
    handleImportChange(file, fileList) {
      console.log('=[====]')
      // console.log((file, fileList))
    }
  }
}
</script>
<style lang="less" scoped>
.down {
  text-decoration: none;
  color: #fff;
}
.expintBtn {
  display: inline-block !important;
  margin-right: 10px;
}
.table_wrap {
  height: 800px;
  overflow: auto;
}
.delete-btn {
  color: #fe6565;
}
.dialogUplod {
  height: 100px;
  margin-left: 70px;
  margin-top: 40px;
  div {
    margin-bottom: 20px;
  }
}
.name-wrapper {
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}
</style>
