<template>
  <div class="sys-box repair-box">
    <div class="sys-operate">
      <el-button type="primary" @click="back()">{{config.cancelText}}</el-button>
      <el-button type="primary" @click="save('form')" :disabled="isDisabled">保存</el-button>
      
    </div>
    <div class="sys-form">
      <el-form label-width="120px" :model="formDetail">
        <div class="flex">
          <el-form-item label="设备编号" class="form-half">
            <el-input placeholder v-model="formDetail.deviceSerialno" readonly></el-input>
          </el-form-item>
          <el-form-item label="设备名称" class="form-half">
            <el-input placeholder v-model="formDetail.deviceName" readonly></el-input>
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item label="任务等级" class="form-half">
            <el-input placeholder v-model="formDetail.reventLevelName" readonly></el-input>
          </el-form-item>
          <el-form-item label="要求完成时间" class="form-half">
            <el-input placeholder v-model="formDetail.planTime" readonly></el-input>
          </el-form-item>
        </div>
        <el-form-item label="故障描述">
          <el-input type="textarea" :autosize="{ minRows: 4}" readonly v-model="formDetail.reventConent"></el-input>
        </el-form-item>
        <el-form-item label="现场照片">
          <el-upload
            accept=".png,.jpg,.jpeg"
            disabled
            :class="{hide:true}"
            :file-list="initFilePaths"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="责任人" class="form-half">
          <el-input placeholder v-model="formDetail.engineerUserName" readonly></el-input>
        </el-form-item>
        <el-form-item label="抄送人">
          <el-input placeholder v-model="formDetail.ccID" readonly></el-input>
        </el-form-item>
        <el-divider></el-divider>
        <div class="flex">
          <el-form-item label="设备类别" class="form-half">
            <el-input placeholder v-model="formDetail.deviceTypeName" readonly></el-input>
          </el-form-item>
          <el-form-item label="规格型号" class="form-half">
            <el-input placeholder v-model="formDetail.deviceModel" readonly></el-input>
          </el-form-item>
        </div>
        <el-form-item label="安装地点">
          <el-input placeholder v-model="formDetail.deciceSite" readonly></el-input>
        </el-form-item>
        <div class="flex">
          <el-form-item label="报修时间" class="form-half">
            <el-input placeholder v-model="formDetail.createTime" readonly></el-input>
          </el-form-item>
          <el-form-item label="报修人" class="form-half">
            <el-input placeholder v-model="formDetail.createUserName" readonly></el-input>
          </el-form-item>
        </div>
        <!-- <el-form-item label="关联单号" class="form-inline">
          <p class="form-p">0000001</p>
        </el-form-item>
        <el-form-item label="关联单据类型" class="form-inline">
          <p class="form-p">保养</p>
        </el-form-item>-->
      </el-form>
      <el-divider content-position="left">维修记录</el-divider>
      <el-form label-width="120px" :model="formData" ref="form" :rules="ruleForm">
        <div class="flex">
          <el-form-item label="实际开工时间" prop="startTime" class="form-inline form-half">
            <el-date-picker
              v-model="formData.startTime"
              type="datetime"
              placeholder="选择实际开工时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="实际完工时间" prop="endTime" class="form-inline form-half">
            <el-date-picker
              v-model="formData.endTime"
              type="datetime"
              placeholder="选择实际完工时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="故障类型" class="form-inline form-half">
            <el-select v-model="formData.type" placeholder="请选择" style="width:100%">
              <el-option
                v-for="item in hitchList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备停机时间" class="form-inline form-half">
            <el-date-picker
              v-model="formData.offTime"
              type="datetime"
              placeholder="选择停机时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
        </div>
        <el-form-item label="故障原因" prop="cause">
          <el-input type="textarea" :autosize="{ minRows: 4}" placeholder="请简要描述故障原因" v-model="formData.cause"></el-input>
        </el-form-item>
        <el-form-item label="维修方案">
          <el-input type="textarea" :autosize="{ minRows: 4}" placeholder="请简要填写维修方案" v-model="formData.solution"></el-input>
        </el-form-item>
        <el-form-item label="维修工时（小时）">
          <el-input v-model="formData.manHour" placeholder="请填写维修工时"></el-input>
        </el-form-item>
        <el-form-item label="维修费用（元）">
          <el-input v-model="formData.cost" placeholder="请填写维修费用"></el-input>
        </el-form-item>
        <el-form-item label="使用状况" prop="usage">
          <el-select
            v-model="formData.usage"
            style="width:100%"
            filterable
            clearable
            placeholder="请选择使用状况"
          >
            <el-option
              v-for="item in deviceStatusList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="完工拍照">
          <el-upload
            :action="uploadUrl"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-success="uploadSuccess"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="使用备件">
          <div class="sys-operate">
            <el-button type="primary" @click="choosePartsVisible = true">选择备件</el-button>
          </div>
          <el-table
            :data="parts"
            :header-cell-style="{fontWeight: 'normal', textAlign: 'center', backgroundColor: '#eceff4', color: '#222'}"
            border
            @selection-change="handlePartChange"
          >
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column prop="code" label="备件编号" align="center"></el-table-column>
            <el-table-column
              prop="name"
              width="200"
              align="center"
              show-overflow-tooltip
              label="备件名称"
            ></el-table-column>
            <el-table-column prop align="center" show-overflow-tooltip label="备件型号"></el-table-column>
            <el-table-column prop="num" align="center" width="120" label="使用数量">
              <template slot-scope="scope">
                <el-input
                  size="small"
                  v-model="scope.row.num"
                  controls-position="right"
                  style="width: 100%"
                  class="inputClass"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="unit" align="center" label="单位"></el-table-column>
            <!-- <el-table-column prop="price" align="center" label="单价"></el-table-column>
            <el-table-column prop="amount" align="center" label="金额"></el-table-column>
            <el-table-column prop align="center" label="库位"></el-table-column> -->
            <el-table-column prop="desc" show-overflow-tooltipalign label="备注"></el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
    </div>
    <!--大图-->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
    <!--选择配件-->
    <ChooseParts :visible.sync="choosePartsVisible" @change="getPart"></ChooseParts>
  </div>
</template>

<script>
import ChooseParts from "../../components/System/dialogChooseParts";
import { mapState, mapActions, mapGetters, mapMutations } from "vuex";
import config from "@/utils/config.js";
import base from '@/api/base.js'; // 导入接口域名列表
export default {
  components: {
    ChooseParts
  },
  data() {
    return {
      uploadUrl: base.uploadUrl,
      formDetail: {},
      formData: {
        targetList: [],
        taglocationappearanceImage: [],
        deletetag_appearanceImage: [],
        type: null,
        serialno: "",
        deviceName: "",
        deviceId:'',
        engineerId: null,
        engineerName: ''
      },
      eventId: "", //事件ID
      ruleForm: {
        startTime: [
          { required: true, message: "请选择实际开工时间", trigger: "change" }
        ],
        endTime: [
          { required: true, message: "请选择实际完工时间", trigger: "change" }
        ],
        cause: [
          { required: true, message: "请简要描述故障原因", trigger: "change" }
        ],
        usage: [
          { required: true, message: "请选择使用状况", trigger: "change" }
        ]
      },
      getUserList: [], //用户
      hitchList: [], //故障类型
      deviceStatusList: [], //使用状态
      tableData: [],
      initFilePaths: [],
      dialogVisible: false,
      choosePartsVisible: false,
      isDisabled: false,
      parts: [], //项目
      choosePartss: [],
        config:config
    };
  },
  mounted() {
    this.eventId = this.$route.query.id;
    this.updateTagNav(this.$route);
    this.initialize();
    this.getDetail();
  },
  methods: {
    ...mapMutations({
      removeTagNav: "tagNav/removeTagNav", //移除
      updateTagNav: "tagNav/updateTagNav" //更新
    }),
    /**
     * 获取明细
     */
    getDetail() {
      this.$api.repairCheckAPI.getDetail(this.eventId).then(res => {
        if (res.code === 0) {
          //res.repairEventImage
          this.formDetail = res.repairEvent;
          if (res.ccIdList) {
            let cc = "";
            res.ccIdList.forEach(p => {
              cc += p.name + ",";
            });
            cc = cc.substring(0, cc.length - 1);
            this.formDetail.ccID = cc;
          }
          if (res.repairEventImage) {
            this.initFilePaths = [];
            for (var i = 0; i < res.repairEventImage.length; i++) {
              let obj = {
                name: "pic" + i,
                url: res.repairEventImage[i].filePath
              };
              this.initFilePaths.push(obj);
            }
          }
        }
      });
    },
    /**
     * 初始化数据
     */
    initialize() {
      Promise.all([
        this.$api.commonAPI.getUsers(),
        this.$api.dictAPI.getDictsByType("device_malfunction"),
        this.$api.dictAPI.getDictsByType("device_status")
      ])
        .then(([r1, r2, r3]) => {
          if (r1.code === 0) {
            this.getUserList = r1.datas;
          }
          if (r2.code === 0) {
            this.hitchList = r2.datas;
            if (this.hitchList) {
              this.formData.type = this.hitchList[0].id;
            }
          }
          if (r3.code === 0) {
            this.deviceStatusList = r3.datas;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    /**
     * 取消方法
     */
    back() {
      this.removeTagNav({
        path: this.$route.path,
        title: this.$route.meta.name
      });
      this.$router.push({ path: "/repair/index",t: Date.now()  });
    },
    /**
     * 保存
     */
    save(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          this.formData.eventId = this.eventId;
          if(this.isDisabled) {
            return
          }
				  this.isDisabled = true
          this.$api.repairCheckAPI.addRepairRecord(this.formData).then(res => {
            this.isDisabled = false
            if (res.code === 0) {
              this.$message({
                message: res.msg,
                type: "success"
              });
              this.back();
            } else {
              this.$message({
                message: res.msg,
                type: "error"
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    /**
     * 获取选择的备件
     */
    getPart(val) {
      console.log(val);
      if (val) {
        val.forEach(p => {
          this.parts.push(p);
        });
      }
    },
    /**
     * 移除选择的项目
     */
    removePart() {
      if (this.chooseParts) {
        this.chooseParts.forEach(p => {
          var index = this.parts.findIndex(item => {
            if (item.id == p.id) {
              return true;
            }
          });
          this.parts.splice(index, 1);
        });
      }
    },
    /**
     * 处理选择
     */
    handlePartChange(val) {
      this.chooseParts = val;
    },
    /**
     * 获取部门
     */
    geyDip(v) {
      var self = this;
      this.getUserList.forEach(item => {
        if (v === item.id) {
          self.formData.deptId = item.deptId;
          self.formData.deptName = item.deptName;
          return;
        }
      });
    },
    /**
     * 删除图片
     */
    handleRemove(file, fileList) {
      if (file.status === "success") {
        this.formData.deletetag_appearanceImage.push(file.response.fileName);
        this.formData.taglocationappearanceImage.splice(
          this.formData.taglocationappearanceImage.indexOf(
            file.response.fileName
          )
        );
      }
    },
    /**
     * 上传成功
     */
    uploadSuccess(res, file) {
      if (res.msg === "操作成功") {
        this.formData.taglocationappearanceImage.push(res.fileName);
      }
    },
    /**
     * 查看大图
     */
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    }
  }
};
</script>

<style scoped>
.flex {
  display: flex;
  flex-wrap: wrap;
}
.sys-form {
  padding: 20px 20px 20px 20px;
}
.sys-form .form-inline {
  width: 33.33%;
}
.sys-form .form-line {
  width: 66.66%;
}
.sys-form .form-half {
  width: 50%;
}
.sys-form .form-inline .el-input,
.sys-form .form-inline .el-select .el-input {
  width: 100%;
}
.icon-luyin {
  color: #2589ee;
  font-size: 24px;
  cursor: pointer;
}
.form-ts {
  padding-left: 20px;
  color: #aaa;
  display: inline-block;
}
.el-form-item__content .sys-operate {
  padding: 10px 0px;
}
</style>
<style>
.hide .el-upload--picture-card {
  display: none;
}
</style>
