<template>
  <div>
    <!-- 违章弹框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%">
      <el-card class="box-card">
        <div slot="header" class="card-header">
          <span>违章信息</span>
        </div>
        <el-form
          ref="dialogForm"
          :model="dialogForm"
          label-width="120px"
          :rules="dialogRules"
          :disabled="isDialogDetail"
          v-if="dialogVisible"
        >
          <el-row style="display: flex;flex-direction: row">
            <el-form-item label="违章工程" prop="proId">
              <el-select v-model="dialogForm.proId" placeholder="请选择违章工程" clearable @change="changePro"
                         filterable
              >
                <el-option v-for="item in violationProOpts" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="责任承包商" prop="consId">
              <el-select v-model="dialogForm.consId" placeholder="请选择责任承包商" clearable @change="changCons"
                         filterable :disabled="dialogForm.proId ? false : true"
              >
                <el-option
                  v-for="item in responsibilityContractorOpts"
                  :key="item.valueUuid"
                  :label="item.label"
                  :value="item.valueUuid"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="承包商负责人" prop="personId">
              <el-input v-model="dialogForm.personName" placeholder="请输入承包商负责人" disabled />
            </el-form-item>
          </el-row>
          <el-row style="display: flex;flex-direction: row">
            <el-form-item label="违章类型" prop="violationType">
              <el-select v-model="dialogForm.violationType" placeholder="请选择违章类型" clearable filterable
                         @change="changeViolationType"
              >
                <el-option v-for="item in violationTypeOpts" :key="item.value" :label="item.label"
                           :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="负责人" prop="directorId">
              <el-select v-model="dialogForm.directorId" placeholder="请选择负责人" clearable filterable
                         @change="changePerson" :disabled="dialogForm.consId ? false : true"
              >
                <el-option v-for="item in leaderOpts" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="违章时间" prop="violationTime">
              <el-date-picker
                v-model="dialogForm.violationTime"
                type="date"
                placeholder="请选择违章时间"
                clearable
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                :picker-options="{ disabledDate: time => time.getTime() > Date.now() }"
              />
            </el-form-item>
          </el-row>
          <!-- 违章依据 -->
          <el-row :gutter="20">
            <el-form-item label="违章依据" prop="violationContent">
              <el-input
                type="textarea"
                v-model="dialogForm.violationContent"
                placeholder="请输入违章依据"
                clearable v-no-whitespace
                :autosize="{ minRows: 4, maxRows: 6 }"
                maxlength="1000"
                show-word-limit
                style="width: 515px"
              />
            </el-form-item>
            <el-form-item label="上传图片" prop="violationPhoto">
              <el-upload
                v-model="dialogForm.violationPhoto"
                action="#"
                accept="image/*"
                :auto-upload="false"
                list-type="picture-card"
                :file-list="dialogForm.violationPhoto"
                :on-change="handleUpFile"
                :on-exceed="handleExceedFile"
                :on-remove="handleDelete"
                :limit="9"
                :class="{ disabled: isDialogDetail || dialogForm.violationPhoto.length >= 9 }"
                :disabled="isDialogDetail"
                :multiple="true"
                :style="uploadStyle"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-row>
        </el-form>
      </el-card>
      <el-card class="box-card" v-if="isDialogDetail">
        <div slot="header" class="card-header">
          <span>违章采集信息</span>
        </div>
        <el-form :model="dialogForm2" ref="dialogForm2" label-width="120px" inline disabled>
          <div v-if="sourceType == '1'">
            <el-form-item label="违章采集来源" prop="violationSource">
              <el-input v-model="dialogForm2.violationSource" placeholder="请输入违章采集来源"  v-no-whitespace/>
            </el-form-item>
            <el-form-item label="新增人员" prop="createUserName">
              <el-input v-model="dialogForm2.createUserName" placeholder="请输入新增人员"  v-no-whitespace/>
            </el-form-item>
            <el-form-item label="新增时间" prop="createTime">
              <el-input v-model="dialogForm2.createTime" placeholder="请输入新增时间"  v-no-whitespace/>
            </el-form-item>
          </div>
          <div v-else-if="sourceType == '2'">
            <el-form-item label="违章采集来源" prop="violationCollectionSource">
              <el-input v-model="dialogForm2.violationCollectionSource" placeholder="请输入违章采集来源" />
            </el-form-item>
            <el-form-item label="设备名称" prop="devicename">
              <el-input v-model="dialogForm2.devicename" placeholder="请输入设备名称" v-no-whitespace />
            </el-form-item>
            <el-form-item label="设备编号" prop="deviceNumber">
              <el-input v-model="dialogForm2.deviceNumber" placeholder="请输入设备编号"  v-no-whitespace/>
            </el-form-item>
            <el-form-item label="设备负责人" prop="deviceLeader">
              <el-input v-model="dialogForm2.deviceLeader" placeholder="请输入设备负责人"  v-no-whitespace/>
            </el-form-item>
            <el-form-item label="设备负责人电话" prop="deviceLeaderPhone">
              <el-input v-model="dialogForm2.deviceLeaderPhone" placeholder="请输入设备负责人电话" v-no-whitespace />
            </el-form-item>
            <el-form-item label="采集时间" prop="collectionTime">
              <el-input v-model="dialogForm2.collectionTime" placeholder="请输入采集时间" v-no-whitespace />
            </el-form-item>
          </div>
          <div v-else-if="sourceType == '3'">
            <el-form-item label="违章采集来源" prop="violationCollectionSource">
              <el-input v-model="dialogForm2.violationSource" placeholder="请输入违章采集来源"  v-no-whitespace/>
            </el-form-item>
            <el-form-item label="发现人" prop="discoverer">
              <el-input v-model="dialogForm2.createUserName" placeholder="请输入发现人"  v-no-whitespace/>
            </el-form-item>
            <el-form-item label="采集时间" prop="collectionTime">
              <el-input v-model="dialogForm2.createTime" placeholder="请输入采集时间"  v-no-whitespace/>
            </el-form-item>
          </div>
        </el-form>
      </el-card>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="isDialogDetail" size="small" @click="dialogVisible = false">关 闭</el-button>
        <el-button v-if="!isDialogDetail" size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!isDialogDetail" size="small" type="primary" @click="dialogConfirm" v-preventReClick="5000">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

import {
  addViolation,
  getConsByProIdSelect, getPersonByConsIdSelect,
  getTypeOfViolationSelect,
  getUnderConstructionProSelect, getViolationDetail
} from '@/api/violation/violation'
import uploadFile from '@/views/pro/admissionRequest/uploadFile.vue'
import { lookFaceFile } from '@/utils/bonus'

export default {
  components: { uploadFile },
  data() {
    return {
      row: {},
      dialogTitle: '新增',
      dialogVisible: false,
      isDialogDetail: false,
      dialogForm: {
        proId: '',
        proName: '', // 违章工程
        consId: '',
        consName: '', // 责任承包商
        supUuid: '',
        personId: '',
        personName: '', // 承包商负责人
        violationType: '', // 违章类型
        violationTypeName: '',
        directorId: '',
        directorName: '', // 负责人
        violationTime: '', // 违章时间
        violationContent: '', // 违章内容
        violationPhoto: [] // 违章照片
      },
      // 违章工程-下拉框
      violationProOpts: [],
      // 责任承包商-下拉框
      responsibilityContractorOpts: [],
      // 承包商负责人-下拉框
      contractorLeaderOpts: [],
      // 违章类型-下拉框
      violationTypeOpts: [],
      // 负责人-下拉框
      leaderOpts: [],
      sourceType: '1',
      dialogForm2: {
        // 来源1
        violationCollectionSource: '', // 违章采集来源
        addPerson: '', // 新增人员
        addTime: '', // 新增时间
        // 来源2
        devicename: '', // 设备名称
        deviceNumber: '', // 设备编号
        deviceLeader: '', // 设备负责人
        deviceLeaderPhone: '', // 设备负责人电话
        collectionTime: '', // 采集时间
        // 来源3
        discoverer: '' // 发现人
      },
      dialogRules: {
        proId: [{ required: true, message: '请选择违章工程', trigger: 'change' }],
        consId: [{ required: true, message: '请选择责任承包商', trigger: 'change' }],
        personName: [{ required: true, message: '请选择承包商负责人', trigger: 'blur' }],
        violationType: [{ required: true, message: '请选择违章类型', trigger: 'change' }],
        directorId: [{ required: true, message: '请选择负责人', trigger: 'change' }],
        violationTime: [{ required: true, message: '请选择违章时间', trigger: 'blur' }],
        violationContent: [{ required: true, message: '请填写违章依据', trigger: 'blur' }],
        violationPhoto: [{ required: true, message: '请上传违章照片', trigger: 'change' }]
      },
      delIds: [],
      lookFacePath: ''
    }
  },
  computed: {
    uploadStyle() {
      return {
        marginLeft: this.dialogForm.violationPhoto.length > 6 ? '0' : '0'
      }
    }
  },
  methods: {
    getTypeOfViolationSelect() {
      getTypeOfViolationSelect({ type: 2 }).then(response => {
        this.violationTypeOpts = response.data
        console.log('🚀 ~ getTypeOfViolationSelect ~ this.violationTypeOpts:', this.violationTypeOpts)
      })
    },
    getUnderConstructionProSelect() {
      getUnderConstructionProSelect({ type: 2 }).then(response => {
        this.violationProOpts = response.data
      })
    },
    getConsByProIdSelect(params) {
      getConsByProIdSelect(params).then(response => {
        this.responsibilityContractorOpts = response.data
      })
    },
    getPersonByConsIdSelect(params) {
      getPersonByConsIdSelect(params).then(response => {
        this.leaderOpts = response.data
        console.log('🚀 ~ 负责人 ~ this.leaderOpts:', this.leaderOpts)
      })
    },
    // 打开违章弹框
    openDialog(row) {
      this.lookFacePath = lookFaceFile()
      this.getTypeOfViolationSelect()
      this.getUnderConstructionProSelect()
      this.getPersonByConsIdSelect({ consUuid: row.consId, proId: row.proId })
      this.row = row
      this.isDialogDetail = row.isDialogDetail
      this.dialogTitle = row.dialogTitle
      this.dialogForm = {
        proId: '',
        proName: '', // 违章工程
        consId: '',
        consName: '', // 责任承包商
        supUuid: '',
        personId: '',
        personName: '', // 承包商负责人
        violationType: '', // 违章类型
        violationTypeName: '',
        directorId: '',
        directorName: '', // 负责人
        violationTime: '', // 违章时间
        violationContent: '', // 违章内容
        violationPhoto: [] // 违章照片
      }
      this.dialogVisible = true
      setTimeout(() => {
        this.dialogForm.personName = ''
        if (row.dialogTitle === '编辑违章' || row.dialogTitle === '查看详情') {
          console.log('🚀 ~当前行 row:', row)
          this.getConsByProIdSelect({ proId: row.proId })
          getViolationDetail({ violationId: row.violationId }).then(res => {
            console.log('🚀 ~ getViolationDetail ~ 详情:', res)

            this.dialogForm = res.data
            this.dialogForm.violationPhoto = res.data.photoList
            this.dialogForm.violationPhoto.forEach((item) => {
              console.log('🚀 ~ this.dialogForm.图片 ~ item:', item)
              item.url = this.lookFacePath + item.url
            })
            this.dialogForm2 = {
              violationSource: res.data.violationSource,
              createUserName: res.data.createUserName,
              createTime: res.data.createTime
            }
            if (res.data.violationSource === '检查新增') {
              this.sourceType = '1'
            } else if (res.data.violationSource === '设备采集') {
              this.sourceType = '2'
            } else if (res.data.violationSource === '随手拍') {
              this.sourceType = '3'
            }
          })
        }
      }, 500)
    },
    // 违章弹框确定
    dialogConfirm() {
      this.$refs.dialogForm.validate(valid => {
        if (valid) {
          let formData = new FormData()
          this.dialogForm.violationPhoto.forEach((file) => {
            if (file.raw) {
              formData.append('files[]', file.raw)
            } else {
              formData.append('files[]', new Blob())
            }
          })
          let code = '新增'
          this.dialogForm.violationId = ''
          this.dialogForm.id = ''
          if (this.dialogTitle === '编辑违章') {
            this.dialogForm.violationId = this.row.violationId
            this.dialogForm.id = this.row.violationId
            code = '修改'
          }
          this.dialogForm.delIds = this.delIds.join(',')
          formData.append('params', JSON.stringify(this.dialogForm))
          addViolation(formData).then(response => {
            if (response.code === 200) {
              this.$message.success(code + '成功')
              this.dialogVisible = false
              this.$emit('getList')
            }
          })
        } else {
          return false
        }
      })
    },
    changePro(val) {
      this.dialogForm.proName = this.violationProOpts.find(item => item.value === val).label
      this.dialogForm.consId = ''
      this.dialogForm.consName = ''
      this.dialogForm.directorId = ''
      this.dialogForm.directorName = ''
      this.getConsByProIdSelect({ proId: val })
    },
    changCons(val) {
      const selectedContractor = this.responsibilityContractorOpts.find(item => item.valueUuid === val)
      this.dialogForm.consName = selectedContractor.label
      this.dialogForm.personName = selectedContractor.name
      this.dialogForm.personId = selectedContractor.userId
      this.dialogForm.directorId = ''
      this.dialogForm.directorName = ''
      this.getPersonByConsIdSelect({ consUuid: val, proId: this.dialogForm.proId })
    },
    changePerson(val) {
      this.dialogForm.directorName = this.leaderOpts.find(item => item.value === val).label
      this.dialogForm.directorId = val
      console.log('🚀 ~ 违章.directorId:', this.dialogForm.directorId)
    },
    changeViolationType(val) {
      this.dialogForm.violationTypeName = this.violationTypeOpts.find(item => item.value === val).label
      this.dialogForm.violationType = val

    },
    handleUpFile(file, fileList) {
      console.log('🚀 ~ file:', file)
      if (file.size > 1024 * 1024 * 10) {
        // 删除文件最后一个
        fileList.pop()
        this.$message.warning('图片大小不能超过10M')
        return false
      }
      // 超过9个文件 提示
      if (fileList.length > 9) {
        this.$message.warning('最多上传9张图片')
      } else {
        this.dialogForm.violationPhoto = fileList
      }
    },
    handleExceedFile(files, fileList) {
      this.$message.warning('最多上传9张图片')
    },
    handleDelete(file, fileList) {
      if (file.fileId) {
        this.delIds.push(file.fileId)
      }
      this.dialogForm.violationPhoto = fileList
    }
  }
}
</script>

<style lang="scss" scoped>
.box-card {
  margin-bottom: 20px;

  .card-header {
    font-size: 16px;
    font-weight: 700;
  }
}

::v-deep.disabled {
  .el-upload--picture-card {
    display: none;
  }
}
</style>
