<template>
  <div class="fullHeight">
    <div class="searchBox whiteBlock">
      <!-- 工作票管理系统——工作票 -->
      <el-form :inline="true" ref="searchForm" :model="searchForm" size="medium">
        <el-form-item label="工作票编号">
          <el-input clearable v-model="searchForm.workTicketSn" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="施工地理位置">
          <el-input clearable v-model="searchForm.geographicalLocation" placeholder="请输入"></el-input>
        </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="getList">{{ $t('message.energyManage.waybill.query') }}</el-button>
          <el-button type="warning" plain @click="refresh">{{ $t('message.deviceManage.refresh') }}</el-button>
          <el-button type="primary" size="medium" @click="add">新增</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table_wrap whiteBlock">
      <el-table class="tables" :data="List">
        <!-- <el-table-column prop="image" label="照片" align="center">
            <template slot-scope="scope">
              <img
                :preview="scope.row.image[0] ? scope.row.image[0].url : []"
                :src="scope.row.image[0] ? scope.row.image[0].url : []"
                alt=""
                width="50px"
              />
            </template>
          </el-table-column> -->
        <el-table-column prop="workTicketSn" align="center" label="工作票编号"></el-table-column>
        <el-table-column prop="projectName" align="center" label="工程名称"></el-table-column>
        <el-table-column prop="constructionTeam" align="center" label="施工班组"></el-table-column>
        <el-table-column prop="initialSurveyRiskLevel" align="center" label="初勘风险等级"></el-table-column>
        <el-table-column prop="riskLevelAfterRetest" align="center" label="复测后风险"></el-table-column>
        <el-table-column prop="rtRiskSecurityLibraryTypeStr" align="center" label="作业类型、工序及部位"></el-table-column>
        <el-table-column prop="startTime" align="center" label="开始时间"></el-table-column>
        <el-table-column prop="endTime" align="center" label="结束时间"></el-table-column>

        <!-- <el-table-column prop="joinPartyDeclaration" align="center" label="入党誓言">
            <template slot-scope="scope"
              ><div class="textStyle" :title="scope.row.joinPartyDeclaration">
                {{ scope.row.joinPartyDeclaration }}
              </div></template
            >
          </el-table-column> -->
        <el-table-column label="操作" align="center" width="250px">
          <template slot-scope="scope">
            <div class="tableBtns">
              <div class="operationText" @click.stop="openDetail(scope.row)">
                <i class="el-icon-tickets" style="color: #8dacfa; font-size: 16px; margin-right: 2px"></i>
                <span style="white-space: nowrap;">详情</span>
              </div>
              <div @click="edit(scope.row)" class="operationText">
                <img src="@/assets/images/icon-edit.png" width="15px" height="15px" />
                <span style="white-space: nowrap;">编辑</span>
              </div>
              <div @click="deleteDev(scope.row)" class="operationText">
                <img src="@/assets/images/icon-delete.png" width="15px" height="15px" />
                <span style="white-space: nowrap;">删除</span>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagerBox"
        @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" @close="close" :title="title" :visible.sync="dialogShow" width="1167px">
      <div class="dialog_content">
        <el-form :inline="true" size="medium" ref="addEditForm" :model="addEditForm" :rules="addEditRules" label-width="180px">
          <el-form-item label="工程名称" prop="projectName">
            <el-input :disabled="isDetail" v-model="addEditForm.projectName" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="工作票编号" prop="workTicketSn">
            <el-input :disabled="isDetail" v-model="addEditForm.workTicketSn" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              :disabled="isDetail"
              value-format="yyyy-MM-dd HH:mm:ss"
              v-model="addEditForm.startTime"
              type="datetime"
              placeholder="请选择时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="施工班组" prop="constructionTeam">
            <el-input :disabled="isDetail" v-model="addEditForm.constructionTeam" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              :disabled="isDetail"
              value-format="yyyy-MM-dd HH:mm:ss"
              v-model="addEditForm.endTime"
              type="datetime"
              placeholder="请选择时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="初勘风险等级" prop="initialSurveyRiskLevel">
            <el-input :disabled="isDetail" v-model="addEditForm.initialSurveyRiskLevel" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="执行方案名称" prop="executionPlanName">
            <el-input :disabled="isDetail" v-model="addEditForm.executionPlanName" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="复测后风险等级" prop="riskLevelAfterRetest">
            <el-input :disabled="isDetail" v-model="addEditForm.riskLevelAfterRetest" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="施工人数" prop="constructionWorkerNumber">
            <el-input :disabled="isDetail" v-model="addEditForm.constructionWorkerNumber" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="作业类型、工序及部位" prop="rtRiskSecurityLibraryTypeIdList">
            <el-cascader
              style="width: 260px;"
              ref="cascaderRef"
              :disabled="isDetail"
              v-model="cascaderSelect"
              @change="safeSelectChange"
              :options="safeLibraryOptions"
              :props="propsCascader"
              clearable
            ></el-cascader>
          </el-form-item>

          <el-form-item label="作业部位" prop="workPart">
            <el-input
              style="width: 700px"
              type="textarea"
              :disabled="isDetail"
              v-model="addEditForm.workPart"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="地理位置" prop="geographicalLocation">
            <el-input
              style="width: 700px"
              type="textarea"
              :disabled="isDetail"
              v-model="addEditForm.geographicalLocation"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="班组负责人" prop="teamLeader">
            <el-input :disabled="isDetail" v-model="addEditForm.teamLeader" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="一般作业人员" prop="generalOperatePersonnel">
            <el-input :disabled="isDetail" v-model="addEditForm.generalOperatePersonnel" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="班组安全员" prop="teamSafetyOfficer">
            <el-input :disabled="isDetail" v-model="addEditForm.teamSafetyOfficer" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="班组技术人员" prop="teamTechnicalStaff">
            <el-input :disabled="isDetail" v-model="addEditForm.teamTechnicalStaff" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="主要风险" prop="mainRisk">
            <el-input
              style="width: 700px"
              type="textarea"
              :disabled="isDetail"
              v-model="addEditForm.mainRisk"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="作业必备条件" prop="jobPrerequisite">
            <el-input style="width: 700px" type="textarea" :disabled="isDetail" v-model="addEditForm.jobPrerequisite" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="作业过程风险控制措施" prop="operationProcessRiskControlMeasure">
            <el-input style="width: 700px" type="textarea" :disabled="isDetail" v-model="addEditForm.operationProcessRiskControlMeasure" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="现场风险复测变化情况及补充控制措施" prop="riskRetestChangesAndSupplementaryControlMeasure">
            <el-input
              style="width: 700px"
              type="textarea"
              :disabled="isDetail"
              v-model="addEditForm.riskRetestChangesAndSupplementaryControlMeasure"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="签发日期" prop="issueDate">
            <el-date-picker
              :disabled="isDetail"
              value-format="yyyy-MM-dd HH:mm:ss"
              v-model="addEditForm.issueDate"
              type="datetime"
              placeholder="请选择时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item :label="$t('message.alarmValueSet.dialog_edit.camera')">
            <el-select
              @change="selectVideo"
              :disabled="isDetail"
              v-model="videoSelect"
              multiple
              :placeholder="$t('message.alarmValueSet.placeholder_select')"
            >
              <el-option v-for="item in videoList" :key="item.itemId" :label="item.videoName" :value="item.itemId"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工作票" style="width:700px">
            <el-upload
              :disabled="isDetail"
              :action="$store.state.UPLOADURL"
              name="files"
              :limit="1"
              :file-list="fileUplodList"
              :on-exceed="(file, fileList) => handleExceed(file, fileList)"
              :on-success="(res, file) => handleSuccess(res, file)"
              :on-remove="(file, fileList) => handleRemove(file, fileList)"
              :on-preview="file => handlePreview(file)"
            >
              <el-button size="small" type="primary">请选择文件</el-button>
            </el-upload>
          </el-form-item>
          <div class="dialog-footer" v-if="!isDetail">
            <el-button class="cancleBtn" @click="dialogShow = false" icon="el-icon-circle-close" size="medium"
              >{{ $t('message.deviceManage.cancel') }}
            </el-button>
            <el-button type="primary" icon="el-icon-circle-check" @click="submit" size="medium"
              >{{ $t('message.deviceManage.save') }}
            </el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  rtRiskSecurityLibraryList,
  rtWorkTicketAdd,
  rtWorkTicketEdit,
  rtWorkTicketDelete,
  rtWorkTicketPage,
  getWorkTickDetailText
} from '@/assets/js/api/workTicketManage'
import { getVideoItemListApi } from '@/assets/js/api/lifter'
import { checkPhone } from '@/assets/js/util.js'
export default {
  mounted() {},
  created() {
    this.getList()
    this.getVideoItemList()
    this.getDutyPerson()
  },
  data() {
    return {
      safeLibraryOptions: [], //风险安全库下拉
      cascaderIds: [],
      cascaderSelect: [],
      daterange: '',
      propsCascader: { multiple: true, children: 'list', label: 'name', value: 'id', checkStrictly: true },
      isDetail: false, //是否详情
      dutyList: [], // 负责人
      fileUplodList: [],
      title: '',
      dialogShow: false,
      pagInfo: {
        pageNo: 1, //页数
        pageSize: 10, //条数
        total: 0 //总条数
      },
      List: [],
      addEditForm: {
        constructionTeam: '',
        constructionWorkerNumber: '',
        createTime: '',
        endTime: '',
        executionPlanName: '',
        generalOperatePersonnel: '',
        geographicalLocation: '',
        id: 0,
        initialSurveyRiskLevel: '',
        issueDate: '',
        jobPrerequisite: '',
        mainRisk: '',
        operationProcessRiskControlMeasure: '',
        projectName: '',
        projectSn: '',
        riskLevelAfterRetest: '',
        riskRetestChangesAndSupplementaryControlMeasure: '',
        rtRiskSecurityLibraryTypeIdList: [],
        startTime: '',
        teamLeader: '',
        teamSafetyOfficer: '',
        teamTechnicalStaff: '',
        updateTime: '',
        workPart: '',
        workTicket: '',
        workTicketSn: '',
        videoList: []
      },
      addEditRules: {
        projectName: [
          {
            required: true,
            message: '必填',
            trigger: 'blur'
          }
        ],
        workTicketSn: [
          {
            required: true,
            message: '必填',
            trigger: 'blur'
          }
        ]
      },
      searchForm: {
        workTicketSn: '',
        geographicalLocation: '',
        actualStartDate: '',
        actualFinishDate: ''
      },
      videoList: [],
      videoSelect: ''
    }
  },
  methods: {
    selectVideo(e) {
      if(e.length == 0) {return}
      // console.log('下拉选择', e)
      let foundObjects = this.videoList.filter(function(item) {
        return e.includes(item.itemId)
      })
      // console.log('处理中的值', foundObjects)
      let sortedObjects = foundObjects.map((item)=> {
        return {
          itemId: item.itemId
        }
      })
      // console.log('处理后的值',sortedObjects)
      this.addEditForm.videoList = sortedObjects
    },
    //获取摄像机列表
    getVideoItemList() {
      let data = {
        projectSn: this.$store.state.projectSn
      }
      console.log(data)
      getVideoItemListApi(data).then(res => {
        if (res.code == 200) {
          console.log(res)
          this.videoList = res.result.list
        }
      })
    },
    safeSelectChange(e) {
      console.log('级联下拉', e)
      this.$nextTick(() => {
        const idList = []
        //获取选中的node
        const checkList = this.$refs.cascaderRef ? this.$refs.cascaderRef.getCheckedNodes() : []
        console.log('筛选前数据', checkList)
        //转换成"1;2;3" 后端需要的数据
        let value = checkList.length > 0 ? checkList.map(x => idList.push(x.data.id)).join(',') : ''
        this.cascaderIds = idList
        this.getRiskSafeDetail()
        // this.addEditForm.rtRiskSecurityLibraryTypeIdList.push(value)
        console.log('筛选后数据', this.cascaderIds)
      })
    },

    //  级联选择器下拉联动查询风险安全库
    getRiskSafeDetail() {
      let data = {
        projectSn: this.$store.state.projectSn,
        rtRiskSecurityLibraryTypeIdList: this.cascaderIds
      }
      getWorkTickDetailText(data).then(res => {
        if (res.code == 200) {
          console.log('风险安全库详情', res.result)
          this.addEditForm.jobPrerequisite = res.result.jobPrerequisite
          this.addEditForm.operationProcessRiskControlMeasure = res.result.operationProcessRiskControlMeasure
          this.$forceUpdate()
        } else {
          this.$message.error(res.message)
        }
      })
    },

    // 查询级联选择器下拉
    getDutyPerson() {
      let data = {
        projectSn: this.$store.state.projectSn
      }
      rtRiskSecurityLibraryList(data).then(res => {
        if (res.code == 200) {
          this.safeLibraryOptions = this.getTypeList(res.result)
          console.log('风险安全库', this.safeLibraryOptions)
        } else {
          this.$message.error(res.message)
        }
      })
    },
     // 处理数据，判断数据children是否有数据
     getTypeList(listData) {
       listData.forEach((items) => {
          if (items.list.length > 0) {
            this.getTypeList(items.list)
          } else {
            items.list = undefined
          }
       })
       return listData
     },

    //查询列表
    getList() {
      rtWorkTicketPage({
        pageNo: this.pagInfo.pageNo,
        pageSize: this.pagInfo.pageSize,
        projectSn: this.$store.state.projectSn,
        geographicalLocation: this.searchForm.geographicalLocation,
        workTicketSn: this.searchForm.workTicketSn,
        startTime_begin: this.searchForm.actualStartDate,
        startTime_end: this.searchForm.actualFinishDate
      }).then(result => {
        if (result.success) {
          this.List = result.result.records
          this.pagInfo.total = result.result.total
        }
      })
    },

    add() {
      this.title = '新增'
      this.dialogShow = true
      this.fileUplodList = []
      this.close()
    },

    edit(obj) {
      console.log('打开编辑', obj)
      this.title = '编辑'
      this.dialogShow = true
      this.addEditForm = JSON.parse(JSON.stringify(obj))
      this.fileUplodList = JSON.parse(obj.workTicket)
      this.cascaderSelect = JSON.parse(obj.rtRiskSecurityLibraryTypeJson)
      if (obj.videoList) {
        this.videoSelect = obj.videoList.map(item => item.itemId);
      }
      
    },
    openDetail(obj) {
      console.log('打开详情', obj)
      this.title = '详情'
      this.dialogShow = true
      this.isDetail = true
      this.addEditForm = JSON.parse(JSON.stringify(obj))
      this.fileUplodList = JSON.parse(obj.workTicket)
      this.cascaderSelect = JSON.parse(obj.rtRiskSecurityLibraryTypeJson)
      if (obj.videoList) {
        this.videoSelect = obj.videoList.map(item => item.itemId);
      }
    },
    submit() {
      let params = JSON.parse(JSON.stringify(this.addEditForm))
      params.projectSn = this.$store.state.projectSn
      params.workTicket = JSON.stringify(this.fileUplodList)
      if (this.cascaderIds.length > 0) {
        params.rtRiskSecurityLibraryTypeIdList = this.cascaderIds
      }
      params.rtRiskSecurityLibraryTypeJson = JSON.stringify(this.cascaderSelect)
      this.$refs.addEditForm.validate(valid => {
        if (valid) {
          if (this.title == '新增') {
            rtWorkTicketAdd(params).then(result => {
              if (result.success) {
                this.$message.success(result.message)
                this.getList()
              }
            })
          } else if (this.title == '编辑') {
            rtWorkTicketEdit(params).then(result => {
              if (result.success) {
                this.$message.success(result.message)
                this.getList()
              }
            })
          }
          this.dialogShow = false
        } else {
          return false
        }
      })
    },
    deleteDev(obj) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          rtWorkTicketDelete({ id: obj.id }).then(res => {
            if (res.success) {
              this.getList()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 删除
    handleRemove(file, fileList) {
      this.fileUplodList = fileList
    },
    handleExceed(file, fileList) {
      console.log('超出限制', file)
      this.$message.warning('只能上传一个文件')
    },
    handleSuccess(res, file, type) {
      if (res.status == 'SUCCESS') {
        this.fileUplodList.push({
          name: file.name,
          url: this.$store.state.FILEURL + file.response.data[0].imageUrl
        })
      }
    },
    close() {
      this.isDetail = false
      this.addEditForm = {}
      this.cascaderSelect = []
      this.videoSelect = []
      this.fileUplodList = []
      this.$nextTick(() => {
        this.$refs.addEditForm.clearValidate()
      })
    },
    SizeChange(val) {
      this.pagInfo.pageSize = val
      this.getList()
    },
    CurrentChange(val) {
      this.pagInfo.pageNo = val
      this.getList()
    },
    refresh() {
      this.searchForm = {}
      this.daterange = []
      this.pagInfo.pageNo = 1 //页数
      this.pagInfo.pageSize = 10 //条数
      this.getList()
    },
    changeDate() {
      if (this.daterange) {
        this.searchForm.actualStartDate = this.daterange[0]
        this.searchForm.actualFinishDate = this.daterange[1]
      } else {
        this.searchForm.actualStartDate = ''
        this.searchForm.actualFinishDate = ''
      }
    },
    handlePreview(file) {
      console.log('点击下载', file)
      let x = new XMLHttpRequest()
      console.log(file.url)
      x.open('GET', file.url, true)
      x.responseType = 'blob'
      x.onload = function(e) {
        let url = window.URL.createObjectURL(x.response)
        let a = document.createElement('a')
        console.log(url)
        a.href = url
        a.download = file.name
        a.click()
        document.removeChild(a)
      }
      x.send()
    }
  }
}
</script>
<style lang="less" scoped>
.tables2 {
  min-height: auto;
}
.textStyle {
  width: 140px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.dialog_content {
  .el-input {
    width: 260px;
  }
  .el-select {
    width: 260px;
  }
}
</style>
