<template>
  <div>
    <el-card style="margin: 5px;margin-top: -20px">
      <el-form :model="repairOrder" ref="dataForm" label-width="100px" style="margin-bottom: -15px">
        <el-button-group style="display: flex;margin: 0px 0 10px 80%; height: 35px">
          <el-button
            v-if="formName == 'start'"
            type="primary"
            @click.native="stareTask()"
          >开始任务
          </el-button>
          <el-button
            v-if="formName == 'end'"
            type="primary"
            @click.native="overTask()"
          >结束任务
          </el-button>
        </el-button-group>

        <el-row>
          <el-col :span="10">
            <el-form-item class="query-form-item" label="部门:">
              <el-select v-model="repairOrder.deptCode"
                         placeholder="请选择部门"
                         clearable="true"
                         @change="deptChange"
                         style="width: 90%"
                         disabled
              >
                <el-option
                  v-for="item in deptList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.code">
                  <span style="float: left">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item class="query-form-item" label="仓库:">
              <el-select v-model="repairOrder.invCode"
                         placeholder="请选择仓库"
                         clearable="true"
                         style="width: 90%"
                         disabled
              >
                <el-option
                  v-for="item in invList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.code">
                  <span style="float: left">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="设备名称:">
              <el-input v-model="repairOrder.deviceName" placeholder="请输入设备名称" style="width: 90%"
                        disabled
                        clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="物资编码:">
              <el-input v-model="repairOrder.code" placeholder="请输入编码" style="width: 90%" clearable
                        disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="维修类型:">
              <el-select v-model="repairOrder.repairType" placeholder="请选择维修类型" style="width: 90%" disabled clearable>
                <el-option label="自行维修" :value=1></el-option>
                <el-option label="外部维修" :value=2></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="紧急程度:">
              <el-select v-model="repairOrder.urgencyType" placeholder="请选择紧急程度" style="width: 90%" disabled clearable>
                <el-option label="正常" :value=1></el-option>
                <el-option label="较急" :value=2></el-option>
                <el-option label="特急" :value=3></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="计划完成日期:" prop="planTime">
              <el-date-picker
                v-model="repairOrder.planTime"
                type="datetime"
                placeholder="选择日期"
                style="width: 90%"
                clearable
                disabled
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="报修说明:">
              <el-input v-model="repairOrder.msg" placeholder="请输入报修信息" style="width: 90%"
                    disabled    clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item class="query-form-item" label="维修人:">
            <el-select v-model="repairOrder.repariName"
                       placeholder="请选择维修人"
                       clearable="true"
                       style="width: 90%"
                        disabled
            >
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.employeeName"
                :value="item.userid">
                <span style="float: left">{{ item.employeeName }}</span>
              </el-option>
            </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item class="query-form-item" label="审核人:">
              <el-input v-model="repairOrder.auditUserName" placeholder="请输入审核人" style="width: 90%"
                        disabled    clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10"  v-if="formName == 'end'">
            <el-form-item label="维修开始时间:" prop="repariStartTime">
              <el-date-picker
                v-model="repairOrder.repariStartTime"
                type="datetime"
                placeholder="选择日期"
                style="width: 90%"
                clearable
                disabled
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10"  v-if="formName == 'end'">
            <el-form-item label="维修结束时间:" prop="repariEndTime">
              <el-date-picker
                v-model="repairOrder.repariEndTime"
                type="datetime"
                placeholder="选择日期"
                style="width: 90%"
                clearable
                disabled
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="10">
          <el-form-item label="维修说明:"  v-if="formName == 'end'">
            <el-input v-model="repairOrder.repariRemark" placeholder="请输入报修信息" style="width: 90%"
                          clearable></el-input>
          </el-form-item>
          </el-col>

        </el-row>

      <el-row>
          <el-col :span="11"  v-if="formName == 'end'">
            <el-form-item label="维修图片:">
              <el-upload
                class="upload-demo"
                ref="upload"
                :action="this.uploadUrl"
                :on-preview="uploadHandlePreview"
                :on-remove="uploadHandleRemove"
                :headers="headers"
                :on-exceed="uploadHandleExceed"
                accept=".jpg,.png,.pdf,.doc"
                :on-change="uploadOnchange"
                :on-success="uploadHandleSuccess"
                :on-error="uploadHandleError"
                :file-list="fileList"
                :data="{ type: 'image2' }"
                :auto-upload="true"
              >
                <el-button
                  slot="trigger"
                  size="small"
                  type="primary"
                >
                  {{ choiceFile }}
                </el-button>
                <div>只能上传 jpg,png,pdf,doc 文件，且不超过 10 MB</div>
              </el-upload>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
    </el-card>

  </div>

</template>

<script>
import {isBlank} from "@/utils/strUtil";
import {getDeptListByUser} from "@/api/auth/authDept";
import {getInvListByUser} from "@/api/system/invWarehouse";
import {updateStatusAndTime, updateStatusAndImg} from "@/api/dev/deviceRepairOrder";
import {getDeptDeviceList} from "@/api/dev/deptDevice";
import store from "@/store";
import {warehouseUserList} from "@/api/system/invWarehouse"


export default {
  props: {
    repairOrder: {
      type: Object,
      required: true
    },
    closeDialog: {
      type: Function,
      required: true
    },
    formName: {
      type: Function,
      required: true
    },


  },
  name: "DeviceRepairOrderStart",
  data() {
    return {
      deptList: [],
      invList: [],
      deviceDialogVisible: false,
      deviceLoading: false,
      filterQuery: {
        code: null,
        deptCode: null,
        invCode: null,
        page: 1,
        limit: 10
      },
      deviceList: [],
      deviceTotal: 0,
      deptName: null,
      invName: null,
      selectRow: null,
      choiceFile:"选取维修图片",
      uploadUrl: "",
      BASE_URL: process.env.VUE_APP_BASE_API,
      headers: {},
      fileList: [],
      userList:[],
    };
  },
  methods: {
    deptChange() {
      this.repairOrder.invCode = null;
      this.invList = [];
      this.getInvList();
    },
    getDeptList() {
      getDeptListByUser().then((res) => {
        this.deptList = res.data || [];
        this.getInvList();
      });
    },
    getInvList() {
      let params = {deptCode: this.repairOrder.deptCode};
      getInvListByUser(params)
        .then((response) => {
          this.invList = response.data || [];
          this.getList();
        })
        .catch(() => {
        });
    },
    getuserList(){
      let param ={code :this.repairOrder.invCode}
      warehouseUserList(param).then((res) =>{
        this.userList = res.data.list || [];
      })
    },

    getDeviceList() {
      this.deviceLoading = true;
      this.deviceList = [];
      getDeptDeviceList(this.filterQuery).then((res) => {
        this.deviceLoading = false;
        if (res.code === 20000) {
          this.deviceList = res.data.list || [];
          this.deviceTotal = res.data.total || 0;
        } else {
          this.$message.error(res.message);
          this.deviceList = [];
          this.deviceTotal = 0;
        }
      }).catch((error) => {
        this.deviceLoading = false;
        this.deviceList = [];
        this.deviceTotal = 0;
      });
    },
    setDeptAnInvName() {
      this.deptList.forEach((item) => {
        if (item.code === this.repairOrder.deptCode) {
          this.deptName = item.name;
        }
      });

      this.invList.forEach((item) => {
        if (item.code === this.repairOrder.invCode) {
          this.invName = item.name;
        }
      })
    },
    onReset() {
      this.filterQuery.code = null;
      this.filterQuery.page = 1;
      this.getDeviceList();
    },
    queryDevice() {
      this.filterQuery.page = 1;
      this.getDeviceList();
    },
    handleCurrentChange(row) {
      this.selectRow = row;
    },
    combine() {
      this.deviceDialogVisible = false;
      this.repairOrder.code = this.selectRow.code;
      this.repairOrder.deviceName = this.selectRow.deviceName;
    },
    stareTask(){
      this.$confirm('是否开始任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        let param ={
          orderId : this.repairOrder.orderId,
          status:4,
        }

        updateStatusAndTime(param).then((res) =>{
          if(res.code == 20000){
            this.$message.success("任务确认成功!");
            this.closeDialog();
          }else{
            this.$message.error(res.message);
          }

        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    overTask(){
      this.$confirm('是否结束任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        let param ={
          orderId : this.repairOrder.orderId,
          status:5,
          repariRemark:this.repairOrder.repariRemark,
          repariImage:this.repairOrder.repariImage
        }
        updateStatusAndImg(param).then((res)=>{
          if(res.code == 20000){
            this.$message.success("任务已结束!");
            this.closeDialog();
          }else{
            this.$message.error(res.message);
          }

        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });

    },




    uploadHandlePreview(file) {},
    uploadHandleRemove(file, fileList) {
      this.repairOrder.repariImage = null;
      console.log(file, fileList);
    },
    uploadHandleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    uploadOnchange(file, fileList) {
      let fileName = file.name;
      let uid = file.uid;
      let pos = fileName.lastIndexOf(".");
      let lastName = fileName.substring(pos, fileName.length);
      if (
        lastName.toLowerCase() !== ".jpg" &&
        lastName.toLowerCase() !== ".png" &&
        lastName.toLowerCase() !== ".doc" &&
        lastName.toLowerCase() !== ".pdf"
      ) {
        this.$message.error("上传文件只能是 jpg,png,doc,pdf 格式");
        for (let i = 0; i < fileList.length; i++) {
          //从list删除
          if (fileList[i].uid === uid) {
            fileList.splice(i, 1);
          }
        }
        return;
      }
      // 限制上传文件的大小
      const isLt = file.size / 1024 / 1024 / 30 <= 1;
      if (!isLt) {
        this.$message.error("上传文件大小不能超过 30MB");
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].uid === uid) {
            fileList.splice(i, 1);
          }
        }
      }
      return isLt;
    },
    uploadHandleSuccess(response, file, fileList) {
      if (response.code === 20000) {
          if(this.repairOrder.repariImage == null){
            this.repairOrder.repariImage = response.data.name+",";
          }else{
            this.repairOrder.repariImage += response.data.name+",";
          }
      } else {
        this.$message.error("文件上传失败：" + response.message);
      }
      console.log(this.repairOrder.repariImage)
    },
    uploadHandleError() {
    },



  },
  created() {
    this.uploadUrl = this.BASE_URL + "/udiwms/upload/register/file";
    this.headers = {
      ADMIN_ID: store.getters.adminId,
      ADMIN_TOKEN: store.getters.token,
    };
    this.repairOrder.repariImage = null;
    this.getDeptList();
    this.getuserList();
  },
}
</script>

<style scoped>

</style>
