<template>
  <div>
    <!-- 违章弹框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%">
      <el-form ref="dialogForm" :model="dialogForm" label-width="120px" :rules="dialogRules">
        <!-- 违章原因 -->
        <el-row :gutter="20">
            <el-form-item label="违章原因" prop="violationReasonReply">
              <el-input
                type="textarea"
                v-model="dialogForm.violationReasonReply"
                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="improvementContent">
              <el-input
                type="textarea"
                v-model="dialogForm.improvementContent"
                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="improvedPhotoList">
              <el-upload
                action="#"
                accept="image/*"
                :auto-upload="false"
                list-type="picture-card"
                :file-list="dialogForm.improvedPhotoList"
                :limit="9"
                :multiple="true"
                :on-change="handleUpImg"
                :on-remove="handleRemoveImg"
                :on-exceed="handleExceedImg"
                :class="{disabled: dialogForm.improvedPhotoList.length >= 9}"
                :style="uploadImprovedStyle"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="罚款上交凭证" prop="receiptOfFinePhotoList">
              <el-upload
                action="#"
                accept="image/*"
                :auto-upload="false"
                list-type="picture-card"
                :file-list="dialogForm.receiptOfFinePhotoList"
                :limit="9"
                :multiple="true"
                :on-change="handleUpImg2"
                :on-remove="handleRemoveImg2"
                :on-exceed="handleExceedImg"
                :class="{disabled: dialogForm.receiptOfFinePhotoList.length >= 9}"
                :style="uploadReceiptStyle"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="dialogConfirm(1)" v-preventReClick="5000">提 交</el-button>
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="dialogConfirm(2)" v-preventReClick="5000">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getViolationPunishDetails, violationBackKickback } from '@/api/violation/violation'
import { submitApproval } from '@/api/pro/admissionRequest'
import { getParams, lookFaceFile } from '@/utils/bonus'
export default {
  data() {
    return {
      row: {},
      dialogTitle: '回传',
      dialogVisible: false,
      dialogForm: {
        violationReasonReply: '', // 违章依据
        improvementContent: '', // 改进方法
        improvedPhotoList: [], // 改进照片
        receiptOfFinePhotoList: [], // 罚款上交凭证
      },
      dialogRules: {
        violationReasonReply: [{ required: true, message: '请输入违章原因', trigger: 'blur' }],
        improvementContent: [{ required: true, message: '请输入改进方法', trigger: 'blur' }],
        improvedPhotoList: [{ required: true, message: '请上传改进照片', trigger: 'change' }],
        receiptOfFinePhotoList: [
          { required: true, message: '请上传罚款上交凭证', trigger: 'change' }
        ],
      },
      delIds:[],
      lookFacePath:''
    }
  },
  computed: {
    uploadReceiptStyle() {
      return {
        marginLeft: this.dialogForm.receiptOfFinePhotoList.length > 6 ? '0' : '0'
      };
    },
    uploadImprovedStyle() {
      return {
        marginLeft: this.dialogForm.improvedPhotoList.length > 6 ? '0' : '0'
      };
    }
  },
  methods: {
    // 打开违章弹框
    openDialog(row) {
      this.lookFacePath = lookFaceFile()
      console.log('🚀 ~ openDialog ~ row:', row)
      this.row = row
      this.dialogRules.receiptOfFinePhotoList[0].required = Number(row.money) > 0
      this.dialogVisible = true
      this.dialogForm.improvedPhotoList = []
      this.dialogForm.receiptOfFinePhotoList = []
      setTimeout(() => {
        this.$refs.dialogForm.resetFields()
        getViolationPunishDetails({violationId : row.violationId}).then(res => {
          this.dialogForm = res.data
          console.log('🚀 ~ openDialog ~ this.data:', res.data)
          if (res.data.improvedPhotoList && res.data.improvedPhotoList.length > 0){
            this.dialogForm.improvedPhotoList = res.data.improvedPhotoList.map(item => {
              return {
                name: item.fileName,
                url: this.lookFacePath + item.filePath,
                fileId: item.fileId
              }
            })
          }else{
            this.dialogForm.improvedPhotoList = []
          }
          if (res.data.receiptOfFinePhotoList && res.data.receiptOfFinePhotoList.length > 0) {
            this.dialogForm.receiptOfFinePhotoList = res.data.receiptOfFinePhotoList.map(item => {
              return {
                name: item.fileName,
                url: this.lookFacePath + item.filePath,
                fileId: item.fileId
              }
            })
          }else {
            this.dialogForm.receiptOfFinePhotoList = []
          }
        })
      }, 100)
    },
    // 上传图片
    handleUpImg(file, fileList) {
      if (file.size > 1024 * 1024 * 10) {
        fileList.pop()
        this.$message.warning('图片大小不能超过10M')
        return false
      }
      console.log('上传图片', file, fileList)
      // 超过9张图片 提示
      if (fileList.length > 9) {
        this.$message.error('最多上传9张图片')
        return
      }
      this.dialogForm.improvedPhotoList = fileList
      // 单独校验
      this.$refs.dialogForm.validateField('improvedPhotoList')
    },
    handleUpImg2(file, fileList) {
      if (file.size > 1024 * 1024 * 10) {
        fileList.pop()
        this.$message.warning('图片大小不能超过10M')
        return false
      }
      console.log('上传图片', file, fileList)
      // 超过9张图片 提示
      if (fileList.length > 9) {
        this.$message.error('最多上传9张图片')
        return
      }
      this.dialogForm.receiptOfFinePhotoList = fileList
      // 单独校验
      this.$refs.dialogForm.validateField('receiptOfFinePhotoList')
    },
    // 移除图片
    handleRemoveImg(file, fileList) {
      if (file.fileId){
        this.delIds.push(file.fileId)
      }
      this.dialogForm.improvedPhotoList = fileList
      // 单独校验
      this.$refs.dialogForm.validateField('improvedPhotoList')
    },
    handleRemoveImg2(file, fileList) {
      if (file.fileId){
        this.delIds.push(file.fileId)
      }
      this.dialogForm.receiptOfFinePhotoList = fileList
      // 单独校验
      this.$refs.dialogForm.validateField('receiptOfFinePhotoList')
    },
    // 超过9张图片 提示
    handleExceedImg() {
      this.$message.error('最多上传9张图片')
    },
    // 违章弹框确定
    dialogConfirm(type) {
      let formData = new FormData()
      const param = {
        violationId: this.row.violationId,
        violationReasonReply: this.dialogForm.violationReasonReply,
        improvementContent: this.dialogForm.improvementContent,
        money: this.row.money,
        delIds: this.delIds.join(','),
      }
      console.log('🚀 ~ dialogConfirm ~ param', this.dialogForm.improvedPhotoList)
      this.dialogForm.improvedPhotoList.forEach((file) => {
        if (file.raw) {
          formData.append('improvedPhotoList[]', file.raw)
        } else {
          formData.append('improvedPhotoList[]', new Blob())
        }
      })
      this.dialogForm.receiptOfFinePhotoList.forEach((file) => {
        if (file.raw) {
          formData.append('receiptOfFinePhotoList[]', file.raw)
        } else {
          formData.append('receiptOfFinePhotoList[]', new Blob())
        }
      })
      if (type === 2) {
        param.type = '2'
        formData.append('params', JSON.stringify(param))
        violationBackKickback(formData).then(res => {
          this.$message.success('保存成功')
          this.dialogVisible = false
          this.$emit('getList')
        })
      }else{
        param.type = '1'
        formData.append('params', JSON.stringify(param))
        this.$refs.dialogForm.validate(valid => {
          if (valid) {
            violationBackKickback(formData).then(res => {
              this.submitApply()
            })
          }
        })
      }
    },
    getParams,
    submitApply(){
      console.log(this.getParams())
      const param = {
        ...this.getParams(),
        userType: '02',
        taskType: '13',
        taskId: this.row.taskId,
        uuid:this.row.violationId
      }
      console.log("param="+JSON.stringify(param))
      submitApproval(param).then(response => {
        if (response.code === 200) {
          if (response.msg === '此审核类型未配置相对应的审核流，请联系管理员配置后再次提交'){
            this.$modal.msgError(response.msg)
          }else{
            this.$message.success('回传成功')
            this.dialogVisible = false
            this.$emit('getList')
          }
        } else {
          this.$modal.msgError('回传失败，请联系管理员查询具体情况，再次进行提交！')
        }
      })
    },
  },
}
</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>
