<template>
  <div>
    <el-card style="margin-top: -10px">
      <el-form :model="repairOrder" ref="dataForm" label-width="120px" style="margin-bottom: -15px" :rules="formRules">
        <el-button-group style="display: flex;margin: 0px 0 10px 80%; height: 35px">
          <el-button
              type="primary"
              @click.native="selectDevice()"
          >选择设备
          </el-button>
          <el-button
              type="primary"
              @click.native="submit()"
          >保存
          </el-button>
        </el-button-group>

        <el-row>
          <el-col :span="10">
            <el-form-item class="query-form-item" label="部门:" prop="deptCode">
              <el-select v-model="repairOrder.deptCode"
                         placeholder="请选择部门"
                         clearable="true"
                         disabled
                         @change="deptChange"
                         style="width: 90%"
              >
                <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="仓库:" prop="invCode">
              <el-select v-model="repairOrder.invCode"
                         placeholder="请选择仓库"
                         clearable="true"
                         disabled
                         style="width: 90%"
              >
                <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 class="query-form-item" label="设备名称:" prop="deviceName">
              <el-input v-model="repairOrder.deviceName" placeholder="请输入设备名称" style="width: 90%"
                        clearable disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item class="query-form-item" label="物资编码:" prop="code">
              <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 class="query-form-item" label="维修类型:" prop="repairType">-->
<!--              <el-select v-model="repairOrder.repairType" placeholder="请选择维修类型" style="width: 90%" 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 class="query-form-item" label="规格型号:" prop="code">
              <el-input v-model="repairOrder.ggxh" placeholder="请输入规格型号" style="width: 90%" clearable
                        disabled></el-input>
            </el-form-item>
          </el-col>



          <el-col :span="10">
            <el-form-item class="query-form-item" label="紧急程度:" prop="urgencyType">
              <el-select v-model="repairOrder.urgencyType" placeholder="请选择紧急程度" style="width: 90%" 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="inspectUser">
              <el-select v-model="repairOrder.inspectUser"
                         placeholder="请选择负责人" clearable
                         style="width: 90%">
                <el-option
                    v-for="item in userList"
                    :key="item.userid"
                    :label="item.employeeName"
                    :value="item.userid">
                  <span style="float: left">{{ item.employeeName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="19">
            <el-form-item label="备注:" prop="remark">
              <el-input type="textarea" :rows="3" v-model="repairOrder.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <el-row type="flex" justify="end">
<!--        <el-button-group style="display: flex;margin-bottom: 15px; margin-right: 10px">-->
<!--          <el-button type="primary" @click.native.stop="selectPlanFunction(null)" :loading="loading">选入</el-button>-->
<!--        </el-button-group>-->
        <el-button-group style="display: flex;margin-bottom: 15px; margin-right: 50px">
          <el-button type="primary" @click.native.stop="setPlanFunction(null)" :loading="loading">新增问题</el-button>
        </el-button-group>
      </el-row>

      <el-table :data="detailList" style="width: 100%;" border highlight-current-row max-height="300" height="500"
                ref="multipleTable">
        <el-table-column label="序号" type="index" width="60"></el-table-column>
        <el-table-column label="项目内容" prop="content" width="300"></el-table-column>
        <el-table-column label="备注" prop="remark" show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click.stop="true" @click.native="setPlanFunction(scope.row)">编辑
            </el-button>
            <el-button type="text" size="small" @click.stop="true"
                       @click.native="delectPlanFunction(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
        title="设备巡检设置"
        :visible.sync="repairOrderSetVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        width="40%"
        append-to-body
        v-if="repairOrderSetVisible"
    >
      <deviceInspectPlanProjectSet
          :inputQuery="inputQuery"
          type="repair"
          :closeDialog="repairOrderSetCloseDialog"
      ></deviceInspectPlanProjectSet>
    </el-dialog>

    <el-dialog
        title="设备巡检选入"
        :visible.sync="inspectSelectPlanSetVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        width="80%"
        append-to-body
        v-if="inspectSelectPlanSetVisible"
    >
      <deviceProjectSelect
          :inputQuery="inputQuery"
          type="3"
          repairType="repair"
          :closeDialog="repairOrderSetCloseDialog"
      ></deviceProjectSelect>
    </el-dialog>


    <el-dialog
        title="选择报修设备"
        :visible.sync="deviceDialogVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        width="65%"
        v-if="deviceDialogVisible"
        append-to-body
    >
      <el-card class="el-card">
        <el-form :model="filterQuery" label-width="100px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="部门:">
                <el-input v-model="deptName" style="width: 90%" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="仓库:">
                <el-input v-model="invName" style="width: 90%" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="资产编码:">
                <el-input v-model="filterQuery.code" style="width: 90%" clearable></el-input>
              </el-form-item>
            </el-col>

          </el-row>


          <div class="top-right-btn">
            <el-button-group style="display:flex;">
              <el-button type="primary" icon="el-icon-refresh" @click="onReset">重置</el-button>
              <el-button type="primary" icon="el-icon-search" @click="queryDevice"
              >查询
              </el-button
              >
              <el-button type="primary" icon="el-icon-document-add" @click="combine">选入</el-button>
            </el-button-group>

          </div>
        </el-form>

        <el-divider style="margin: 15px"></el-divider>

        <el-table v-loading="deviceLoading" :data="deviceList" style="width: 100%" highlight-current-row border
                  ref="ref"
                  @current-change="handleCurrentChange"
        >
          <el-table-column label="序号" type="index"></el-table-column>
          <el-table-column label="设备名称" prop="deviceName" width="200"></el-table-column>
          <el-table-column label="资产编码" prop="code" width="200"></el-table-column>
          <el-table-column label="规格型号" prop="ggxh" width="120"></el-table-column>
          <el-table-column label="批次号" prop="batchNo" width="120"></el-table-column>
          <el-table-column label="生产日期" prop="productionDate" width="120"></el-table-column>
          <el-table-column label="失效日期" prop="expireDate" width="120"></el-table-column>
          <el-table-column label="生产厂家" prop="manufactory" show-overflow-tooltip></el-table-column>
          <el-table-column label="供应商" prop="supName" show-overflow-tooltip></el-table-column>
          <el-table-column label="注册证号" prop="zczbhhzbapzbh" width="150" show-overflow-tooltip></el-table-column>
        </el-table>

        <pagination
            v-show="deviceTotal>0"
            :total="deviceTotal"
            :limit.sync="filterQuery.limit"
            :page.sync="filterQuery.page"
            @pagination="getDeviceList"
        ></pagination>
      </el-card>

    </el-dialog>
  </div>

</template>

<script>
import {isBlank} from "@/utils/strUtil";
import {getDeptListByUser} from "@/api/auth/authDept";
import {getInvListByUser, warehouseUserList} from "@/api/system/invWarehouse";
import {getDeptDeviceList} from "@/api/dev/deptDevice";
import store from "@/store";
import {saveDeviceRepairOrder} from "@/api/dev/deviceRepairOrder"
import deviceInspectPlanProjectSet from "@/views/dev/DeviceInspectPlanProjectSet"
import deviceProjectSelect from "@/views/dev/DeviceProjectSelect"
import {selectDeviceInspectPlanDelect} from "@/api/dev/deviceInspectPlanDelect";
import {deleteRepairOrderDetail, filterByorderIdFk} from "@/api/dev/deviceRepairOrderDetail";


export default {
  props: {
    repairOrder: {
      type: Object,
      required: true
    },
    closeDialog: {
      type: Function,
      required: true
    }
  },
  name: "DeviceRepairOrderModify",
  data() {
    return {
      deptList: [],
      invList: [],
      userList:[],
      deviceDialogVisible: false,
      deviceLoading: false,
      filterQuery: {
        code: null,
        deptCode: this.$store.getters.locDeptCode,
        invCode: this.$store.getters.locInvCode,
        page: 1,
        limit: 10
      },
      loading: false,
      deviceList: [],
      deviceTotal: 0,
      deptName: null,
      invName: null,
      selectRow: null,
      choiceFile: "选取报修",
      uploadUrl: "",
      BASE_URL: process.env.VUE_APP_BASE_API,
      headers: {},
      fileList: [],
      formRules: {
        deptCode: [{required: true, message: '请选择部门', trigger: 'blur'}],
        invCode: [{required: true, message: '请选择仓库', trigger: 'blur'}],
        code: [{required: true, message: '请输入物资编码', trigger: 'blur'}],
        repairType: [{required: true, message: '请选择维修类型', trigger: 'blur'}],
        urgencyType: [{required: true, message: '请选择紧急程度', trigger: 'blur'}],
        planTime: [{required: true, message: '请选择计划完成日期', trigger: 'blur'}],
      },
      check: false,
      detailList: [],
      inputQuery: {},
      repairOrderSetVisible: false,
      inspectSelectPlanSetVisible: false,
    };
  },
  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(() => {
          });
    },
    submit() {
      if (isBlank(this.repairOrder.deptCode)) {
        this.$message.error("请选择部门")
        return;
      }
      if (isBlank(this.repairOrder.invCode)) {
        this.$message.error("请选择仓库")
        return;
      }
      if (isBlank(this.repairOrder.deviceName)) {
        this.$message.error("请输入设备名称")
        return;
      }
      if (isBlank(this.repairOrder.code)) {
        this.$message.error("请输入物资编码")
        return;
      }
      if (isBlank(this.repairOrder.urgencyType)) {
        this.$message.error("请选择紧急程度")
        return;
      }

      let formName = isBlank(this.repairOrder.id) ? "add" : "edit";
      saveDeviceRepairOrder(this.repairOrder, formName).then((res) => {
        if (res.code === 20000) {
          this.$message.success("添加成功");
          this.closeDialog();
        } else {
          this.$message.error(res.message);
        }
      }).catch((error) => {
        this.$message.error(error.message);
      });
    },
    selectDevice() {
      if (isBlank(this.repairOrder.deptCode) || isBlank(this.repairOrder.invCode)) {
        this.$message.warning("请先选择报修设备所属部门和仓库");
        return;
      }
      this.setDeptAnInvName();
      this.check = false
      this.deviceDialogVisible = true;
      this.filterQuery = {
        code: null,
        deptCode: this.repairOrder.deptCode,
        invCode: this.repairOrder.invCode,
        page: 1,
        limit: 10
      }
      this.getDeviceList();
    },
    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;
    },
    // 刷新表单
    resetForm() {
      if (this.$refs["dataForm"]) {
        // 清空验证信息表单
        this.$refs["dataForm"].clearValidate();
      }
    },
    combine() {
      this.resetForm();
      if (this.selectRow == null) {
        this.$message.error("请勾选设备!")
        return;
      }
      if (this.repairOrder.deviceName != null && this.repairOrder.deviceName != '') {
        this.$message.error("该设备已选入!")
        return
      }
      this.deviceDialogVisible = false;
      this.repairOrder.code = this.selectRow.code;
      this.repairOrder.ggxh = this.selectRow.ggxh;
      this.repairOrder.deviceName = this.selectRow.deviceName;
    },
    uploadHandlePreview(file) {
    },
    uploadHandleRemove(file, fileList) {
      this.repairOrder.uploadImage = 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.uploadImage == null) {
          this.repairOrder.uploadImage = response.data.name + ",";
        } else {
          this.repairOrder.uploadImage += response.data.name + ",";
        }
      } else {
        this.$message.error("文件上传失败：" + response.message);
      }
      console.log(this.repairOrder.uploadImage)
    },
    uploadHandleError() {
    },
    selectPlanFunction(row) {
      if (this.repairOrder.id != null) {
        if (isBlank(row)) {
          this.inputQuery = {};
          this.inputQuery.orderIdFk = this.repairOrder.orderId
        } else {
          this.inputQuery = row
        }
        this.inspectSelectPlanSetVisible = true;
      } else {
        this.$refs["dataForm"].validate((valid) => {
          if (valid) {
            let formName = isBlank(this.repairOrder.id) ? "add" : "edit";
            if (formName == "add") {
              this.repairOrder.planStatus = 1;
            }
            saveDeviceRepairOrder(this.repairOrder, formName).then((res) => {
              if (res.code === 20000) {
                this.repairOrder.id = res.data.id;
                this.repairOrder.orderId = res.data.orderId;
                this.inputQuery = {};
                this.inputQuery.orderIdFk = this.repairOrder.orderId
                this.inspectSelectPlanSetVisible = true;
              } else {
                this.$message.error(res.message);
              }
            }).catch((error) => {
              this.$message.error(error.message);
            });
          }
        })
      }
    },
    setPlanFunction(row) {
      if (this.repairOrder.id != null) {
        if (isBlank(row)) {
          this.inputQuery = {};
          this.inputQuery.orderIdFk = this.repairOrder.orderId
        } else {
          this.inputQuery = row
        }
        this.repairOrderSetVisible = true;
      } else {
        this.$refs["dataForm"].validate((valid) => {
          if (valid) {
            let formName = isBlank(this.repairOrder.id) ? "add" : "edit";
            if (formName == "add") {
              this.repairOrder.planStatus = 1;
            }
            saveDeviceRepairOrder(this.repairOrder, formName).then((res) => {
              if (res.code === 20000) {
                this.repairOrder.id = res.data.id;
                this.repairOrder.orderId = res.data.orderId;
                this.inputQuery = {};
                this.inputQuery.orderIdFk = this.repairOrder.orderId
                this.repairOrderSetVisible = true;
              } else {
                this.$message.error(res.message);
              }
            }).catch((error) => {
              this.$message.error(error.message);
            });
          }
        })
      }
    },
    delectPlanFunction(row) {
      deleteRepairOrderDetail({id: row.id}).then((res) => {
        if (res.code == 20000) {
          this.selectDevicerepairOrderDelect({orderIdFk: row.orderIdFk})
        } else {
          this.$message.error(res.message);
        }
      }).catch((error) => {
        this.$message.error(error.message);
      })
    },
    repairOrderSetCloseDialog() {
      this.repairOrderSetVisible = false;
      this.inspectSelectPlanSetVisible = false;
      this.selectDevicerepairOrderDelect({orderIdFk: this.inputQuery.orderIdFk})
    },
    getUserBus() {
      let query = {
        code: this.repairOrder.invCode,
      }
      //加载用户数据
      warehouseUserList(query).then((res) => {
        this.userList = [];
        this.userList = res.data.list;
      }).catch((error) => {
        this.$message.error("用户数据加载失败")
      });
    },
    selectDevicerepairOrderDelect(obj) {
      filterByorderIdFk(obj).then((res) => {
        this.loading = false;
        if (res.code === 20000) {
          this.detailList = res.data || [];
        } else {
          this.$message.error(res.message);
          this.detailList = [];
        }
      }).catch((error) => {
        this.loading = false;
        this.$message.error(error.message);
        this.detailList = [];
      })
    },
  },
  components: {
    deviceInspectPlanProjectSet, deviceProjectSelect
  },
  created() {
    this.uploadUrl = this.BASE_URL + "/udiwms/upload/register/file";
    this.headers = {
      ADMINID: store.getters.adminId,
      ADMINTOKEN: store.getters.token,
    };
    this.repairOrder.deptCode = this.$store.getters.locDeptCode
    this.repairOrder.invCode = this.$store.getters.locInvCode
    this.repairOrder.uploadImage = null;
    this.getDeptList()
    this.getUserBus()
    if (this.repairOrder.id != null) {
      this.selectDevicerepairOrderDelect({orderIdFk: this.repairOrder.orderId})
    }
  },
}
</script>

<style scoped>

</style>
