<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
        <el-form-item label="维护日期" prop="timeRange">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="仪器编号" prop="deviceNum">
          <el-input
            v-model="queryParams.deviceNum"
            placeholder="请输入仪器编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="仪器名称" prop="deviceName">
          <el-input
            v-model="queryParams.deviceName"
            placeholder="请输入仪器名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['app:preserve:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDeleteAll"
            v-hasPermi="['app:preserve:remove']"
          >删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </el-card>
    <br>
    <el-card>
      <el-table border stripe  v-loading="loading" ref="multipleTable" :data="disposalList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"  />
        <!--  <el-table-column label="ID"  prop="id" width="80" />  -->
        <el-table-column label="维护日期"  prop="maintenanceTime" >
          <template slot-scope="scope">
            {{changeDate(scope.row.maintenanceTime)}}
          </template>
        </el-table-column>
        <el-table-column label="仪器编号"  prop="deviceNum" />
        <el-table-column label="仪器名称"  prop="deviceName" />
        <el-table-column label="维护项目"  prop="maintenanceProject" />
        <el-table-column label="维护内容"  prop="maintenanceSituation" />
        <el-table-column label="维护人"  prop="maintenanceUser" />
        <el-table-column label="责任人"  prop="userName" />
        <el-table-column label="操作" width="180"  class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
            >查看</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['app:preserve:edit']"
              style="margin-right: 10px"
            >修改</el-button>
            <el-popconfirm
              v-hasPermi="['app:preserve:remove']"
              :title="'是否确认删除所选数据项？'"
              @confirm="handleDelete(scope.row)"
            >
              <el-button
                size="mini"
                type="text"
                slot="reference"
                icon="el-icon-delete"
              >删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改死淘处理方式对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" label-position="left" :model="form" :rules="rules" :disabled="isView" label-width="120px">
        <el-form-item label="维护日期" prop="maintenanceTime">
          <el-date-picker
            style="width: 100%"
            v-model="form.maintenanceTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="选择仪器" prop="deviceNum">
          <el-select v-model="form.deviceNum" style="width: 100%" :disabled="form.id !== null" placeholder="请选择仪器" @change="selectProject">
            <el-option v-for="item in deviceList" :key="item.id" :value="item.deviceNum" :label="item.text"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="维护项目" prop="maintenanceProject">
          <!-- <el-input v-model="form.maintenanceProject" show-word-limit maxlength="20" :placeholder="isView ? '' : '请输入维护项目'" /> -->
          <el-select v-model="form.maintenanceProject"  style="width: 100%" :placeholder="isView ? '' : '请选择维护项目'">
            <el-option v-for="(item,index) in selectList" :key="index" :value="item.maintenanceItem" :label="item.maintenanceItem"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="维护情况描述" prop="maintenanceSituation">
          <el-input type="textarea" :autosize="{ minRows: 2 }"   v-model="form.maintenanceSituation" maxlength="50" show-word-limit placeholder="请输入维护情况描述" />
        </el-form-item>
        <el-form-item label="维护人" prop="maintenanceUser">
          <el-select v-model="form.maintenanceUser" style="width: 100%">
            <el-option v-for="item in staffList" :key="item.id" :value="item.realname" :label="item.realname" placeholder="请选择维护人" ></el-option>
          </el-select>
          <!--          <el-input v-model="form.maintenanceUser" placeholder="请输入维护人" />-->
        </el-form-item>
        <el-form-item label="责任人" prop="userName">
          <el-input v-model="form.userName" show-word-limit maxlength="10" placeholder="请输入责任人" />
        </el-form-item>
        <el-form-item label="规格型号" prop="specificationNoGroup">
          <el-input type="textarea" :autosize="{ minRows: 2 }"   disabled v-model="form.specificationNoGroup" maxlength="50" show-word-limit :placeholder="isView ? '' : '请输入规格型号'" />
        </el-form-item>
        <el-form-item label="维修结果" prop="repairDetail">
          <el-input type="textarea" :autosize="{ minRows: 2 }"   v-model="form.repairDetail" maxlength="50" show-word-limit :placeholder="isView ? '' : '请输入维修结果'" />
        </el-form-item>
        <el-form-item label="故障描述" prop="faultDetail">
          <el-input type="textarea" :autosize="{ minRows: 2 }"   v-model="form.faultDetail" maxlength="50" show-word-limit :placeholder="isView ? '' : '请输入故障描述'" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!isView">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {changeDate, getFindByKey} from "../../../utils";
import {
  getPreservePage,
  getPreserveDetail,
  addPreservePage,
  editPreservePage,
  delPreservePage
} from "../../../api/app/preserve";
import {required} from "../../../utils/formRules";
import { getInstrumentList } from "../../../api/app/instrument";
import {getUserProfile} from "../../../api/system/user";
import {listStaff} from "../../../api/app/staff";

export default {
  name: "",
  dicts: ['default_inspection_instrument_maintain_item'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      disposalList: [],
      // 弹出层标题
      title: "",
      isView:false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        timeRange: null,
        deviceNum: null,
        deviceName: null,
        startTime: null,
        endTime: null
      },
      pickerOptions: {
        disabledDate(time) {
          // 获取当前日期
          const today = new Date();
          today.setHours(0, 0, 0, 0); // 将时间设置为当天的 00:00:00

          // 禁用今天之后的日期
          return time.getTime() > today.getTime();
        }
      },
      // 表单参数
      form: {
        id: null,
        deviceName: null,
        deviceNum: null,
        maintenanceProject: null,
        maintenanceSituation: "仪器状态正常",
        maintenanceTime: changeDate(new Date()),
        maintenanceUser: null,
        userName: "",
        specificationNoGroup: null,
        repairDetail: "仪器完好",
        faultDetail: "无"
      },
      rules: {
        deviceNum: [required('仪器不能为空')],
        maintenanceTime: [required('维护日期不能为空')],
        userName: [required('责任人不能为空')]
      },
      deviceList: [],
      user: {},
      staffList: [],
      selectList: [],
      projectList: [],
    }
  },
  watch: {
    "queryParams.timeRange": {
      handler(newVal) {
        if (newVal) {
          this.queryParams.startTime = newVal[0]
          this.queryParams.endTime = newVal[1]
        } else {
          this.queryParams.startTime = null
          this.queryParams.endTime = null
        }
      },
      deep: true
    },
    "form.deviceNum": {
      handler(newVal) {
        if(newVal) {
          let item = getFindByKey(this.deviceList, newVal, 'deviceNum')
          if(item) {
            console.log(item)
            this.form.deviceName = item.deviceName;
            this.form.specificationNoGroup = item.model;
          }
        } else {
          this.form.deviceName = null;
          this.form.specificationNoGroup = null;
        }
      },
      deep: true
    }
  },
  created() {
    this.getStaff()
    this.getUser()
    this.getDevice()
    this.getList();
  },
  methods: {
    changeDate(val) {
      return changeDate(val)
    },
    selectProject(val) {
      this.selectList = []
      let arr = []
      //目前只有默认的维护项目，但保留判断逻辑
      if(arr.length==0){
        arr = this.dict.type.default_inspection_instrument_maintain_item.map(item=>{
            return {
              maintenanceItem:item.value
            }
        })
      }
      this.selectList = arr

    },
    /** getStaff **/
    getStaff() {
      let params = {
        pageNum: 1,
        pageSize: 1000,
        postId: 27
      }
      listStaff(params).then(res => {
        this.staffList = res.data.records;
      })
    },
    /** getUser **/
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.form.userName = response.data.nickName
      });
    },
    /** 仪器列表 **/
    getDevice() {
      getInstrumentList().then(res => {
        res.data.forEach(item => {
          item.text = item.deviceName + '('+ item.deviceNum + ')'
        })
        this.deviceList = res.data
      })
    },
    /** 查询检验项目列表 */
    getList() {
      getPreservePage(this.queryParams).then(res => {
        this.disposalList = res.data.records;
        this.total = res.data.total;
        this.loading = false;
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        timeRange: null,
        deviceNum: null,
        deviceName: null,
        startTime: null,
        endTime: null
      }
      // this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isView = false;
      this.title = "添加检验仪器维护登记";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      let params = {
        id: id
      }
      getPreserveDetail(params).then(res => {
        this.form = res.data;
        this.open = true;
        this.isView = false;
        this.title = "修改检验仪器维护登记";
      })
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id;
      let params = {
        id: id
      }
      getPreserveDetail(params).then(res => {
        this.form = res.data;
        this.open = true;
        this.isView = true;
        this.title = "查看检验仪器维护登记";
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deviceName: null,
        deviceNum: null,
        maintenanceProject: null,
        maintenanceSituation: "仪器状态正常",
        maintenanceTime: changeDate(new Date()),
        maintenanceUser: null,
        userName: this.user.nickName,
        specificationNoGroup: null,
        repairDetail: "仪器完好",
        faultDetail: "无"
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            // 编辑
            editPreservePage(this.form).then(res => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            })
          } else {
            // 新增
            addPreservePage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      let params = {
        ids: ids
      }
      delPreservePage(params).then(res => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      })
    },
    /** 删除按钮操作 */
    handleDeleteAll() {
      const ids = this.ids;
      this.$modal.confirm('是否确认删除所选数据项？').then(() => {
        let params = {
          ids: ids.join(',')
        }
        delPreservePage(params).then(res => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
          this.$refs.multipleTable.clearSelection();
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">

</style>
