<!--suppress ALL -->
<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" append-to-body :close-on-click-modal="false">
    <el-form ref="dataForm" :rules="rules" :model="qualityForm" label-well-code="right" label-width="120px" >
      <el-row :gutter="20">
        <el-col :span="12" >
          <el-form-item label="设备编号" prop="devcode">
            <el-input v-model.trim="qualityForm.devcode" :disabled="isEditMode" type="text" placeholder="设备编号" />
          </el-form-item>
        </el-col>
        <el-col :span="12" >
          <el-form-item label="返修日期" prop="returntimeFmt">
            <el-date-picker
              v-model="qualityForm.returntimeFmt"
              :disabled="isEditMode"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12" >
          <el-form-item label="检查人员" prop="checkmanId">
            <el-select v-model="qualityForm.checkmanId" :disabled="isEditMode" filterable placeholder="检查人员" clearable value="">
              <el-option
                v-for="item in principalList"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" >
          <el-form-item label="是否替换设备">
            <el-radio-group :disabled="isEditMode" v-model="qualityForm.ischange"  @change="changeshow()">
              <el-radio label="1" >是</el-radio>
              <el-radio label="0" >否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12" >
          <el-form-item label="选择任务单">
            <el-select v-model="qualityForm.taskid" :disabled="!(!isEditMode && canselect)" filterable placeholder="备货任务单" clearable value="">
              <el-option
                v-for="item in taskList"
                :key="item.id"
                :label="item.projectName"
                :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" >
          <el-form-item label="故障定位" prop="deviceProblemLocation">
            <!--<el-input v-model.trim="qualityForm.deviceProblemLocation" :disabled="isEditMode" type="textarea" rows = "3" placeholder="故障定位" />-->
            <el-select v-model="qualityForm.deviceProblemLocation" :disabled="isEditMode" filterable placeholder="故障定位" clearable value="">
              <el-option
                v-for="item in locationList"
                :key="item.label"
                :label="item.label"
                :value="item.label"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12" >
          <el-form-item label="故障现象" prop="deviceProblem">
            <el-input v-model.trim="qualityForm.deviceProblem" :disabled="isEditMode" type="textarea" rows = "3" placeholder="必填" />
          </el-form-item>
        </el-col>
        <el-col :span="12" >
          <el-form-item label="原因分析" >
            <el-input v-model.trim="qualityForm.analysis" :disabled="isEditMode" type="textarea" rows = "3" placeholder="原因分析" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12" >
          <el-form-item label="归零措施" >
            <el-input v-model.trim="qualityForm.zeroMeasures" :disabled="isEditMode" type="textarea" rows = "3" placeholder="归零措施" />
          </el-form-item>
        </el-col>
        <el-col :span="12" >
        <el-form-item label="维修人员" prop="repairmenId">
        <el-select v-model="qualityForm.repairmenId" :disabled="isEditMode" filterable placeholder="人员列表" clearable value="">
        <el-option
          v-for="item in principalList"
          :key="item.id"
          :label="item.name"
          :value="item.id"/>
        </el-select>
        </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12" >
          <el-form-item label="完成时间">
            <el-date-picker
              v-model="qualityForm.finishtimeFmt"
              :disabled="isEditMode"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" >
        <el-col :span="24">
          <el-form-item label="上传图片" >
            <el-upload
              :disabled="isEditMode"
              ref="upload"
              :before-upload="handleBeforeUpload"
              :on-preview="handlePictureCardPreview"
              :before-remove="befReomve"
              :on-remove="handleRemove"
              :on-exceed="handleExceed"
              :on-change="handleChange"
              :http-request="uploadFile"
              :file-list="imageList"
              :limit="3"
              :class="{hide:hideUpload}"
              multiple
              action="string"
              accept=".jpg,.jpeg,.png "
              list-type="picture-card">
              <i class="el-icon-plus"/>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible" title="图片预览" append-to-body>
              <div class="imgBox">
                <img :src="dialogImageUrl" max-height="400px;" alt="" style="margin: 0 auto;">
              </div>
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="saveData">{{btnNames}}</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>

import { addQuality,updateQuality,getTaskDownList,getDeviceList } from '@/api/batch'
import { getPrincipalList} from '@/api/devicetype'
import { getFactory } from '@/api/factory'
import { Uploadimg } from '@/api/common'
export default {
  name: 'EditQuality',
  data() {
    return {
      btnNames:'',
      isSubmit:false,
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update
      qualityForm: {
        id:'',
        devcode:'',
        returntimeFmt:'',
        deviceProblem:'',
        checkmanId:'',
        ischange:'',
        taskid:'',
        deviceProblemLocation:'',
        analysis:'',
        zeroMeasures:'',
        repairmenId:'',
        finishtimeFmt:''
      }, // 表单
      canselect: true,
      equipmentFile: null,
      photopath1:null,
      photopath2:null,
      photopath3:null,
      defaultPhoto: require('../../assets/global_images/white.png'), // 默认图片路径
      textMap: {
        update: '质量履历单信息',
        update: '质量履历单信息',
        create: '质量履历单新增',
        detail: '详情'
      }, // 表头显示标题
      deviceTypeList: null, // 设备类型列表
      rules: {
        devcode: [{ required: true, message: '设备编号不能为空', trigger: ['blur', 'change'] }],
        returntimeFmt: [{ required: true, message: '请选择返修日期', trigger: ['blur', 'change'] }],
        deviceProblem: [{ required: true, message: '故障现象不能为空', trigger: ['blur', 'change'] }],
        checkmanId: [{ required: true, message: '请选择检查人员', trigger: ['blur', 'change'] }],
        deviceProblemLocation: [{ required: true, message: '故障定位不能为空', trigger: ['blur', 'change'] }],
        repairmenId: [{ required: true, message: '请选择维修人员', trigger: ['blur', 'change'] }],
      }, // 前端校验规则
      isEditMode: false,
      isPicMode: false,
      principalList: null, // 批产负责人列表
      locationList:[
        {
          label: '设计问题'
        }, {
          label: '工艺问题'
        }, {
          label: '其他'
        }
      ],
      deviceList:null,
      taskList:null,
      rowInfo:{},
      hideUpload: false,
      imageList: [],
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  watch: {
  },
  mounted() {
  },
  created() {
    this.fetchPrincipalList()
    this.fetchDeviceList()
    this.fetchTaskList()
  },
  methods: {
    uploadFile(file) {
      console.log('uploadFile:' + file.file.name)
      const base_url = process.env.BASE_API + '/static/'
      Uploadimg(file).then(res => {
        if (res.code === 200) {
          this.imageList.push({ name: file.file.name, url: base_url + res.data })
        }
      })
    },
    getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        let fileResult = ''
        reader.readAsDataURL(file)
        // 开始转
        reader.onload = function() {
          fileResult = reader.result
        }
        // 转 失败
        reader.onerror = function(error) {
          reject(error)
        }
        // 转 结束  咱就 resolve 出去
        reader.onloadend = function() {
          resolve(fileResult)
        }
      })
    },
    handleExceed(files, fileList) {
      this.$message.warning(`限制选择 3 张图片`)
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePictureCardPreview(file) {
      console.log('handlePictureCardPreview')
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    befReomve(file) {
      if (file.status === "success") {
        return this.$confirm(`确认删除该图片吗`, "确认删除");
      }
    },

    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      console.log('handleRemove')
      console.log(this.imageList)
      console.log(file.name)
      for (const i in this.imageList) {
        if (this.imageList[i].name === file.name) {
          this.imageList.splice(i, 1)
          this.hideUpload = this.imageList.length >= 3
          return
        }
      }
    },
    handleChange(file, fileList) {
      console.log('handleChange')
      if (fileList) {
        this.hideUpload = fileList.length >= 3
      } else {
        this.hideUpload = false
      }
    },
    // 上传前判断文件格式及大小
    handleBeforeUpload(file) {
      const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png')
      let res = true
      console.log(file.size)
      const isLt2M = file.size / 1024/1024 < 7
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
        res = false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 7MB!')
        res = false
      }
      return res
    },
    changeshow(){
      if(this.qualityForm.ischange === '0')
      {
        this.canselect = false
        this.qualityForm.taskid =''
      }else {
        this.canselect = true
      }
    },
    // 初始化对话框
    initDialog: function(dialogStatus, dialogFormVisible, row = null) {
      this.dialogStatus = dialogStatus
      this.dialogFormVisible = dialogFormVisible
      if (dialogStatus === 'create') { // 如果是新增，清除验证
        this.btnNames = '提交'
        this.resetForm()
        this.isEditMode = false
        this.isPicMode = false
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      } else if (dialogStatus === 'update') { // 如果是修改，将row中数据填写到输入框中
        this.isSubmit = false
        this.btnNames = '开始编辑'
        console.log(row)
        this.qualityForm = {
          id: row.id,
          devcode: row.devcode,
          returntimeFmt: row.returntime,
          deviceProblem: row.deviceProblem,
          checkmanId: row.checkmanId,
          ischange: row.ischange,
          taskid: row.taskid,
          deviceProblemLocation: row.deviceProblemLocation,
          analysis: row.analysis,
          zeroMeasures: row.zeroMeasures,
          repairmenId: row.repairmenId,
          finishtimeFmt: row.finishtime
        }
        this.imageList = []
        if(row.photopath1.length>0)  this.imageList.push({ name: row.photopath1,  url:process.env.BASE_API + '/static/'+ row.photopath1 })
        if(row.photopath2.length>0)  this.imageList.push({ name: row.photopath2,  url:process.env.BASE_API + '/static/'+ row.photopath2 })
        if(row.photopath3.length>0)  this.imageList.push({ name: row.photopath3,  url:process.env.BASE_API + '/static/'+ row.photopath3 })

        if(this.qualityForm.ischange === '0')
        {
          this.canselect = false
        }else {
          this.canselect = true
        }
        this.isEditMode = true
        this.isPicMode = true
        this.rowInfo = row
      }
    },
    moneyChange(e){
      this.qualityForm.money = e.target.value
    },
    // 重置表单
    resetForm() {
      this.equipmentFile = null
      this.qualityForm = {
          id: '',
          devcode: '',
          returntimeFmt: '',
          deviceProblem: '',
          checkmanId: '',
          ischange: '',
          taskid: '',
          deviceProblemLocation: '',
          analysis: '',
          zeroMeasures: '',
          repairmenId: '',
          finishtimeFmt: ''
      }
      this.photopath1 = ''
      this.photopath2 = ''
      this.photopath3 = ''
      this.canselect = true
      this.imageList = []
    },
    // 保存数据
    saveData: function() {
      console.log(this.imageList)
      if (this.dialogStatus === 'update') {
        this.updateData()
      } else if (this.dialogStatus === 'create') {
        this.createData()
      }
    },

    // 新增数据
    createData: function() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if(this.imageList.length===0){
            this.qualityForm.photopath1 = ''
            this.qualityForm.photopath2 = ''
            this.qualityForm.photopath3 = ''
          }
          else if(this.imageList.length===1){
            this.qualityForm.photopath1 = this.imageList[0].url.split('/static/')[1]
            this.qualityForm.photopath2 = ''
            this.qualityForm.photopath3 = ''
          }else if(this.imageList.length===2){
            this.qualityForm.photopath1 = this.imageList[0].url.split('/static/')[1]
            this.qualityForm.photopath2 = this.imageList[1].url.split('/static/')[1]
            this.qualityForm.photopath3 = ''
          }else if(this.imageList.length===3){
            this.qualityForm.photopath1 = this.imageList[0].url.split('/static/')[1]
            this.qualityForm.photopath2 = this.imageList[1].url.split('/static/')[1]
            this.qualityForm.photopath3 = this.imageList[2].url.split('/static/')[1]
          }
          console.log(this.qualityForm)
          addQuality(this.qualityForm).then(response => {
            if (response.code === 200) {
              this.$confirm('新增成功，是否继续新增?', '提示', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'info'
              }).then(() => {
                this.resetForm()
                this.$nextTick(() => {
                  this.$refs['dataForm'].clearValidate()
                })
              }).catch(() => {
                this.$emit('watchChild')
                this.dialogFormVisible = false
              })
            }else if(response.code === 400){
              this.$message.error('设备编号不存在')
            }
          })
        }
      })
    },
    getBase64Image(img){
      var canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, img.width, img.height);
      var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
      var dataURL = canvas.toDataURL("image/" + ext);
      return dataURL;
    },
    btof(data, fileName) {
      const dataArr = data.split(",");
      const byteString = atob(dataArr[1]);

      const options = {
        type: "image/jpeg",
        endings: "native"
      };
      const u8Arr = new Uint8Array(byteString.length);
      for (let i = 0; i < byteString.length; i++) {
        u8Arr[i] = byteString.charCodeAt(i);
      }
      return new File([u8Arr], fileName + ".jpg", options);
    },
    // 修改数据
    updateData: function() {
      if(this.isSubmit) {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if(this.imageList.length===0){
              this.qualityForm.photopath1 = ''
              this.qualityForm.photopath2 = ''
              this.qualityForm.photopath3 = ''
            }
            else if(this.imageList.length===1){
              this.qualityForm.photopath1 = this.imageList[0].url.split('/static/')[1]
              this.qualityForm.photopath2 = ''
              this.qualityForm.photopath3 = ''
            }else if(this.imageList.length===2){
              this.qualityForm.photopath1 = this.imageList[0].url.split('/static/')[1]
              this.qualityForm.photopath2 = this.imageList[1].url.split('/static/')[1]
              this.qualityForm.photopath3 = ''
            }else if(this.imageList.length===3){
              this.qualityForm.photopath1 = this.imageList[0].url.split('/static/')[1]
              this.qualityForm.photopath2 = this.imageList[1].url.split('/static/')[1]
              this.qualityForm.photopath3 = this.imageList[2].url.split('/static/')[1]
            }
            updateQuality(this.qualityForm).then(response => {
              if (response.code === 200) {
                this.$message.success('修改成功')
                this.$emit('watchChild')
                this.dialogFormVisible = false
              }else if(response.code === 400){
                this.$message.error('设备编号不存在')
              }
            })
          }
        })
      }else {
        this.btnNames = '提交'
        this.isSubmit = true
        this.isEditMode = false
        this.isPicMode = false
      }
    },
    // 获取批产负责人
    fetchPrincipalList() {
      getPrincipalList('operator,producer').then(response => {
        this.principalList = response.data
      })
    },
    // 获取设备下拉
    fetchDeviceList() {
      getDeviceList().then(response => {
        this.deviceList = response.data
        console.log(this.deviceList)
      })
    },
    // 获取任务下拉
    fetchTaskList() {
      getTaskDownList().then(response => {
        this.taskList = response.data
      })
    },
    cancel: function() {
      this.dialogFormVisible = false
      this.$emit('watchChild')
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .el-select{
    width: 100%;
  }
  .el-date-editor{
    width: 100%;
  }
  .labeltext{
    vertical-align: -webkit-baseline-middle;
  }
</style>
