<template>
  <div>
    <el-card style="margin-top: -10px">
      <el-form :model="inspectTake" ref="formRef" label-width="120px" style="margin-bottom: -15px" :rules="rules">
        <el-button-group style="display: flex;margin: 0px 0 10px 75%; height: 35px" v-if="type != 3">
          <el-button
              type="primary"
              @click.native="selectDevice()"
          >选择设备
          </el-button>
          <el-button type="primary" v-if="inspectTake.status == 0" @click.native="submit(0)">草稿保存</el-button>
          <el-button type="primary" @click.native="submit(2)">提交</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="inspectTake.deptCode" placeholder="请选择部门" clearable="true"
                         :disabled="inspectTake.code != null"
                         @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="inspectTake.invCode" placeholder="请选择仓库"
                         :disabled="inspectTake.code != null"
                         clearable="true" 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 label="设备名称:" prop="deviceName">
              <el-input v-model="inspectTake.deviceName" disabled placeholder="请输入设备名称" style="width: 90%"
                        clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="物资编码:" prop="code">
              <el-input v-model="inspectTake.code" disabled placeholder="请输入编码" style="width: 90%"
                        clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="ischeck">
          <el-col :span="10">
            <el-form-item class="query-form-item" label="维修类型:" prop="repairType">
              <el-select v-model="inspectTake.repairType"
                         :disabled="formName == 'edit' || type == 3"
                         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="level">
              <el-select v-model="inspectTake.level"
                         :disabled="formName == 'edit' || type == 3"
                         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-row>
          <el-col :span="10">
            <el-form-item label="负责人:" prop="inspectUser">
              <el-select v-model="inspectTake.inspectUser"
                         :disabled="type == 3"
                         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-col :span="10">
            <el-form-item label="任务类型:" prop="type">
              <el-select v-model="inspectTake.type" style="width: 90%"
                         :disabled="formName == 'edit' || type == 3 || delectList.length > 0"
                         @change="repairType"
                         placeholder="请选择任务类型"
              >
                <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-col :span="10">
            <el-form-item label="预期结束时间:" prop="expectedTime">
              <el-date-picker
                  v-model="inspectTake.expectedTime"
                  type="datetime"
                  placeholder="选择任务预期结束时间"
                  style="width: 90%"
                  :disabled="type == 3"
                  :picker-options="pickerOptionsExpected"
                  :clearable="false"
                  value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="提醒时间:" prop="remindTime">
              <el-date-picker
                  v-model="inspectTake.remindTime"
                  type="datetime"
                  placeholder="选择提醒时间"
                  style="width: 90%"
                  :disabled="type == 3"
                  :picker-options="pickerOptionsExpected"
                  :clearable="false"
                  value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注:" prop="remark">
              <el-input type="textarea" :rows="3"
                        :disabled="type == 3"
                        v-model="inspectTake.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)" v-if="type != 3" :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)" v-if="type != 3" :loading="loading">
            新增
          </el-button>
        </el-button-group>
      </el-row>

      <el-table :data="delectList" 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="projectContent" width="400"></el-table-column>
        <el-table-column label="状态" prop="status" width="100">
          <template slot-scope="scope">
            <el-tag>{{ statusMap[scope.row.status] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="现场照片" prop="inspectImage" width="250">
          <template slot-scope="scope">
            <div style="color: #1890ff;" @click="showImgViewer(scope.row)">{{ scope.row.inspectImage }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button type="text" size="small" v-if="type != 3" @click.native.stop="editDialog(scope.row,'edit')">编辑</el-button>
            <el-button type="text" size="small" @click.native.stop="editDialog(scope.row,'detail')">详情</el-button>
            <el-button type="text" size="small" @click.native.stop="delectPlanFunction(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
        :title="name"
        :visible.sync="inspectTakeSetVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        width="45%"
        append-to-body
        v-if="inspectTakeSetVisible"
    >
      <DeviceInspectTakeProjectSet
          :inputQuery="inputQuery"
          :editType="editType"
          :type="type"
          check="ckeck"
          :closeDialog="inspectTakeSetCloseDialog"
      ></DeviceInspectTakeProjectSet>
    </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"
    >
      <DeviceProjectSelectTake
          :inputQuery="inputQuery"
          :type="inspectTake.type"
          :closeDialog="inspectPlanSetCloseDialog"
      ></DeviceProjectSelectTake>
    </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>
        <el-form class="query-form" :model="filterQuery" :inline="true" label-width="100px">
          <el-form-item class="query-form-item" label="部门:">
            <el-input v-model="deptName" disabled></el-input>
          </el-form-item>
          <el-form-item class="query-form-item" label="仓库:">
            <el-input v-model="invName" disabled></el-input>
          </el-form-item>
          <el-form-item class="query-form-item" label="资产编码:">
            <el-input v-model="filterQuery.code" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button-group>
              <el-button type="primary" icon="el-icon-refresh" @click="onReset"></el-button>
              <el-button type="primary" icon="search" @click="queryDevice"
              >查询
              </el-button
              >
              <el-button type="primary" icon="search" @click="combine">确定</el-button>
            </el-button-group>
          </el-form-item>
        </el-form>
        <el-divider style="margin: 15px"></el-divider>

        <el-table v-loading="deviceLoading" :data="deviceList" style="width: 100%" highlight-current-row border
                  @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>


    <el-image-viewer v-if="imgViewerVisible" style="z-index:9999" :on-close="closeImgViewer" :url-list="imgList"/>

  </div>

</template>

<script>
import {isBlank} from "@/utils/strUtil";
import {getDeptListByUser} from "@/api/auth/authDept";
import {getInvListByUser, warehouseUserList} from "@/api/system/invWarehouse";
import {saveDeviceInspectPlan, updateStatus} from "@/api/dev/deviceInspectPlan";
import DeviceInspectTakeProjectSet from "@/views/dev/DeviceInspectTakeProjectSet"
import {
  delectDeviceInspecTakeDetail,
  saveDeviceInspectTake,
  selectDeviceInspecTakeDetail,
  uploadDeviceTake
} from "@/api/dev/deviceInspectTake";
import {previewImage, previewFile} from "@/api/purchase/supCompany";
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import {getDeptDeviceList} from "@/api/dev/deptDevice";
import DeviceProjectSelectTake from "@/views/dev/DeviceProjectSelectTake"


export default {
  props: {
    inspectTake: {
      type: Object,
      required: true
    },
    type: {
      type: Object,
      required: true
    },
    closeDialog: {
      type: Function,
      required: true
    },
    formName: {
      type: Function,
      required: true
    },
  },
  name: "DeviceInspectTakeAdd",
  data() {
    return {
      deptList: [],
      invList: [],
      userList: [],
      imgList: [],
      name: '',
      BASE_URL: process.env.VUE_APP_BASE_API,
      editType: null,
      deviceDialogVisible: false,
      deviceLoading: false,
      filterQuery: {
        code: null,
        deptCode: null,
        invCode: null,
        page: 1,
        limit: 10
      },
      loading: false,
      inputQuery: {
        id: null,
        projectCode: null,
        projectContent: null,
        status: null,
        result: null,
        inspectImage: null,
        inspectUser: null,
        updateTime: null,
        taskOrderIdFk: null
      },
      ischeck: false,
      deviceList: [],
      delectList: [],
      deviceTotal: 0,
      deptName: null,
      invName: null,
      selectRow: null,
      imgViewerVisible: false,
      inspectTakeSetVisible: false,
      inspectSelectPlanSetVisible: false,
      rules: {
        deptCode: [{required: true, message: "请选择部门!", trigger: 'blur'}],
        invCode: [{required: true, message: "请选择仓库!", trigger: 'blur'}],
        deviceName: [{required: true, message: "请输入设备名称!", trigger: 'blur'}],
        code: [{required: true, message: "请输入物资编码!", trigger: 'blur'}],
        type: [{required: true, message: "请选择类型!", trigger: 'blur'}],
        repairType: [{required: true, message: "请选择维修类型!", trigger: 'blur'}],
        level: [{required: true, message: "请选择紧急程度!", trigger: 'blur'}],
      },
      statusMap: {
        1: "未开始",
        2: "已检查",
        3: "异常",
        4: "不巡检",
      },
      pickerOptionsExpected: {
        disabledDate: (time) => {
          return time.getTime() <= new Date(this.inspectTake.createDate).getTime() - 86400000;
        },
      },
    };
  },
  methods: {
    deptChange() {
      this.inspectTake.invCode = null;
      this.invList = [];
      this.getInvList();
    },
    getDeptList() {
      getDeptListByUser().then((res) => {
        this.deptList = res.data || [];
        this.getInvList();
      });
    },
    repairType(val) {
      if (val == 3) {
        //报修
        this.ischeck = true;
      } else
        this.ischeck = false;

    },
    getInvList() {
      let params = {deptCode: this.inspectTake.deptCode};
      getInvListByUser(params)
          .then((response) => {
            this.invList = response.data || [];
            this.getList();
          })
          .catch(() => {
          });
    },
    submit(status) {
      this.$refs["formRef"].validate((valid) => {
        if (valid) {
          if(status == 2){
            if(isBlank(this.inspectTake.inspectUser)){
              return this.$message.error("负责人不能为空");
            }
            if(isBlank(this.inspectTake.expectedTime)){
              return this.$message.error("预期结束时间不能为空");
            }
          }
          //当类型是报修的话
          if(this.inspectTake.type == 3){
            if(isBlank(this.inspectTake.repairType)){
              return this.$message.error("维修类型不能为空");
            }
            if(isBlank(this.inspectTake.level)){
              return this.$message.error("紧急程度不能为空");
            }
          }
          if (this.formName == "add" && isBlank(this.inspectTake.id)) {
            this.inspectTake.status = status
            saveDeviceInspectTake(this.inspectTake,'add').then((res) => {
              if (res.code === 20000) {
                this.$message.success("提交成功");
                this.closeDialog();
              } else {
                this.$message.error(res.message);
              }
            }).catch((error) => {
              this.$message.error(error.message);
            });
          } else {
            this.inspectTake.status = status
            uploadDeviceTake(this.inspectTake).then((res) => {
              if (res.code === 20000) {
                this.$message.success("提交成功");
                this.closeDialog();
              } else {
                this.$message.error(res.message);
              }
            }).catch((error) => {
              this.$message.error(error.message);
            });
          }
        }
      })
    },

    onReset() {
      this.filterQuery.code = null;
      this.filterQuery.page = 1;
      this.getDeviceList();
    },
    queryDevice() {
      this.filterQuery.page = 1;
      this.getDeviceList();
    },

    combine() {
      if( this.selectRow == null){
        return this.$message.error("请选择设备！");
      }
      this.deviceDialogVisible = false;
      this.inspectTake.code = this.selectRow.code;
      this.inspectTake.deviceName = this.selectRow.deviceName;
    },

    //!--------------------------------------------------------------   新加方法           --------------------------------------------------------- //
    selectDeviceInspecTakeDetail(obj) {
      selectDeviceInspecTakeDetail(obj).then((res) => {
        this.loading = false;
        if (res.code === 20000) {
          this.delectList = res.data || [];
        } else {
          this.$message.error(res.message);
          this.delectList = [];
        }
      }).catch((error) => {
        this.loading = false;
        this.$message.error(error.message);
        this.delectList = [];
      })
    },
    getUserBus() {
      let query = {
        code: this.inspectTake.invCode,
      }
      //加载用户数据
      warehouseUserList(query).then((res) => {
        this.userList = [];
        this.userList = res.data.list;
      }).catch((error) => {
        this.$message.error("用户数据加载失败")
      });
    },
    setPlanFunction(row) {
      if (this.inspectTake.orderId != null) { //edit
        if (isBlank(row)) {
          this.inputQuery = {};
          this.inputQuery.status = 1;
          this.inputQuery.taskOrderIdFk = this.inspectTake.orderId
        } else {
          this.inputQuery = row
        }
        this.inspectTakeSetVisible = true;
      } else { // add
        this.$refs["formRef"].validate((valid) => {
          if (valid) {
            this.inspectTake.type = this.inspectTake.type
            this.inspectTake.status = 0;
            let formName = isBlank(this.inspectTake.id) ? "add" : "edit";
            saveDeviceInspectTake(this.inspectTake, formName).then((res) => {
              if (res.code === 20000) {
                this.inspectTake.id = res.data.id;
                this.inspectTake.orderId = res.data.orderId;
                this.inputQuery.taskOrderIdFk = this.inspectTake.orderId
                this.inputQuery.projectCode = res.data.code;
                this.inspectTakeSetVisible = true;
              } else {
                this.$message.error(res.message);
              }
            }).catch((error) => {
              this.$message.error(error.message);
            });
          }
        })
      }
    },

    selectPlanFunction(row) {
      if (this.inspectTake.orderId != null) { //edit
        if (isBlank(row)) {
          this.inputQuery = {};
          this.inputQuery.taskOrderIdFk = this.inspectTake.orderId
          this.inputQuery.projectCode = this.inspectTake.code
        } else {
          this.inputQuery = row
        }
        this.inspectSelectPlanSetVisible = true;
      } else {
        this.$refs["formRef"].validate((valid) => {
          if (valid) {
            this.inspectTake.type = this.inspectTake.type
            this.inspectTake.status = 0;
            let formName = isBlank(this.inspectTake.id) ? "add" : "edit";
            saveDeviceInspectTake(this.inspectTake, formName).then((res) => {
              if (res.code === 20000) {
                this.inspectTake.id = res.data.id;
                this.inspectTake.orderId = res.data.orderId;
                this.inspectTake.code = res.data.code;
                this.inputQuery = {};
                this.inputQuery.taskOrderIdFk = res.data.orderId
                this.inputQuery.projectCode = res.data.code;
                this.inspectSelectPlanSetVisible = true;
              } else {
                this.$message.error(res.message);
              }
            }).catch((error) => {
              this.$message.error(error.message);
            });
          }
        })
      }

    },
    inspectPlanSetCloseDialog() {
      this.inspectPlanSetVisible = false;
      this.inspectSelectPlanSetVisible = false;
      this.selectDeviceInspecTakeDetail({taskOrderIdFk: this.inspectTake.orderId});

    },

    selectDevice() {
      if (isBlank(this.inspectTake.deptCode) || isBlank(this.inspectTake.invCode)) {
        this.$message.warning("请先选择巡检设备所属部门和仓库");
        return;
      }
      this.setDeptAnInvName();
      this.deviceDialogVisible = true;
      this.filterQuery = {
        code: null,
        deptCode: this.inspectTake.deptCode,
        invCode: this.inspectTake.invCode,
        page: 1,
        limit: 10
      }
      this.getDeviceList();
    },

    setDeptAnInvName() {
      this.deptList.forEach((item) => {
        if (item.code === this.inspectTake.deptCode) {
          this.deptName = item.name;
        }
      });

      this.invList.forEach((item) => {
        if (item.code === this.inspectTake.invCode) {
          this.invName = item.name;
        }
      })
    },
    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;
      });
    },
    handleCurrentChange(row) {
      this.selectRow = row;
    },

    editDialog(row, type) {
      this.inputQuery = row;
      this.inspectTakeSetVisible = true
      if (type == 'edit') {
        this.editType = 1;
        this.name = "巡检任务编辑"
      } else if (type == 'detail') {
        this.editType = 2;
        this.name = "巡检任务详情"
      } else {
        this.editType = 3;
      }
    },
    delectPlanFunction(row) {
      delectDeviceInspecTakeDetail({id: row.id}).then((res) => {
        if (res.code == 20000) {
          this.selectDeviceInspecTakeDetail({taskOrderIdFk: this.inspectTake.orderId});
        } else {
          this.$message.error(res.message);
        }
      }).catch((error) => {
        this.$message.error(error.message);
      })
    },
    showImgViewer(row) {
      if (row.inspectImage.substr(-1) == ',') {
        row.inspectImage = row.inspectImage.slice(0, row.inspectImage.length - 1);
      }
      this.certFileUrl = this.BASE_URL + "/udiwms/image/register/file/getImage?type=image2&name=";
      this.imgList = [];
      previewImage({imageUrl: row.inspectImage, certFileUrl: this.certFileUrl}).then(response => {
        if (response.code === 20000) {
          this.imgList = response.data;
        }
        console.log(this.imgList)
        this.imgViewerVisible = true;
      });
      const m = (e) => {
        e.preventDefault()
      };
      document.body.style.overflow = 'hidden';
      document.addEventListener("touchmove", m, false); // 禁止页面滑动

    },
    closeImgViewer() {
      this.imgViewerVisible = false;
      const m = (e) => {
        e.preventDefault()
      };
      document.body.style.overflow = 'auto';
      document.removeEventListener("touchmove", m, true);
    },
    inspectTakeSetCloseDialog() {
      this.inspectTakeSetVisible = false
      this.selectDeviceInspecTakeDetail({taskOrderIdFk: this.inspectTake.orderId});
    }
  }
  ,
  components: {
    DeviceInspectTakeProjectSet, ElImageViewer, DeviceProjectSelectTake
  }
  ,
  created() {
    this.inspectTake.createDate = new Date().getTime();
    this.getDeptList();
    this.getUserBus();
    if (!isBlank(this.inspectTake.id)) {
      this.selectDeviceInspecTakeDetail({taskOrderIdFk: this.inspectTake.orderId});
      if (this.inspectTake.type == 3) {
        this.ischeck = true //报修字段显示
      }
    }
  }
  ,
}
</script>

<style scoped>

</style>
