<!-- 检定管理 -->
<template>
  <basic-container>
    <div class="main">
      <SearchHeader
        style="margin-left: -10px"
        :searchForm="searchForm"
        :searchText="searchText"
        @searchHandle="searchHandle"
        @addHandle="addHandle"
      >
        <el-select
          class="inputHeight"
          v-model="searchForm.status"
          placeholder="请选择状态"
          size="small"
          clearable
        >
          <el-option
            v-for="item in statusList"
            :key="item.dictKey"
            :label="item.dictValue"
            :value="item.dictKey"
          >
          </el-option>
        </el-select>
      </SearchHeader>
      <avue-crud
        id="avue-id"
        v-model="form"
        :option="option"
        :table-loading="loading"
        :data="tableData"
        :page.sync="page"
        ref="crud"
        :row-key="getRowKeys"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @row-save="rowSave"
        @row-update="rowUpdate"
        @row-del="rowDel"
      >
        <template slot-scope="{ row, index }" slot="menu">
          <el-button @click="$refs.crud.rowEdit(row, index)">编辑</el-button>
          <el-button @click="$refs.crud.rowDel(row, index)">删除</el-button>
          <el-button type="primary" @click="testHandle(row, index)"
            >检定</el-button
          >
        </template>
        <template slot="menuForm">
          <el-button size="small" @click="$refs.crud.closeDialog()"
            >取消</el-button
          >
          <el-button size="small" @click="$refs.crud.rowSave()">确定</el-button>
        </template>
        <template slot-scope="{ row }" slot="status">
          <span :style="{ color: row.status == 1 ? '#999' : '#EE922F' }"
            >●{{ row.status | statusFl }}</span
          >
        </template>
      </avue-crud>
    </div>
    <el-dialog
      title="设备检定"
      :visible.sync="dialogVisible"
      width="920px"
      class="custom el-custom"
    >
      <div>
        <avue-form v-model="testObj" :option="testOption" @submit="submit">
          <template slot="menuForm">
            <el-button class="cus-cencel" size="small" @click="testCloseDialog"
              >取 消</el-button
            >
            <el-button class="cus-confirm" size="small" @click="submit()"
              >提 交</el-button
            >
          </template>
        </avue-form>
      </div>
    </el-dialog>
    <el-dialog
      title="多项设备检定"
      width="60%"
      :visible.sync="selectdialogVisible"
      :close-on-click-modal="false"
    >
      <div class="q_add">
        <el-input
          type="text"
          v-model="verificationMechanism"
          placeholder="检定机构"
          style="width: 255px; margin-right: 20px"
        ></el-input>
        <el-button @click="addDept" style="background-color: #1e60f5; color:#fff;">确认检定机构</el-button>
        <el-input
          style="width: 255px; margin: 0 20px"
          type="text"
          v-model="verificationInfo"
          placeholder="检定情况"
        ></el-input>
        <el-button @click="addReamrk" style="background-color: #1e60f5; color:#fff;">确认检定情况</el-button>
      </div>
      <el-table
        :data="selectionList"
        :row-style="{ height: '66px' }"
        :header-cell-style="{
          background: '#f6f8fa',
          color: '#999999',
          fontWeight: '400',
          height: '66px',
        }"
        tooltip-effect="dark"
        style="width: 100%; color: #333333"
      >
        <el-table-column
          :align="left"
          prop="code"
          label="设备编号"
        ></el-table-column>
        <el-table-column :align="left" prop="equipStatus" label="设备情况">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.equipStatus"
              placeholder="请选择设备情况"
            >
              <el-option
                v-for="item in situationList"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          :align="left"
          prop="verificationMechanism"
          label="设备机构"
        >
          <template slot-scope="scope">
            <el-input
              type="text"
              v-model="scope.row.verificationMechanism"
              placeholder="设备机构"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column :align="left" prop="verificationTime" label="检定时间">
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.verificationTime"
              type="date"
              placeholder="检定时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 99%"
            >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column :align="left" prop="verificationInfo" label="检定情况">
          <template slot-scope="scope">
            <el-input
              type="text"
              v-model="scope.row.verificationInfo"
              placeholder="检定情况"
            ></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div class="footer">
        <el-button class="cus-cencel" size="small" @click="cencel">取 消</el-button>
        <el-button class="cus-confirm" size="small" @click="testSubmit" :loading="testSubmitLoading"
          >提 交</el-button
        >
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  remove,
  add,
  update,
  getStatus,
  addTest,
  getSituation,
  verification
} from "@/api/capital/test.js";
import { dateFormat } from '@/util/date'
import { tableOption } from "@/const/capital/test.js";
let that;
export default {
  data() {
    return {
      testSubmitLoading: false,
      verificationMechanism: "",
      verificationInfo: "",
      selectionList: [],
      selectdialogVisible: false,
      // 检定
      dialogVisible: false,
      testObj: {
        
      },  
      testOption: {
        labelPosition: "top",
        gutter: 60,
        // 提交
        submitBtn: false,
        // 清空
        emptyBtn: false,
        // emptyBtn:true,//隐藏清空按钮
        column: [
          {
            type: "input",
            span: 8,
            label: "设备编号",
            prop: "code",
            readonly: true,
          },
          {
            type: "input",
            label: "设备名称",
            span: 8,
            prop: "equipName",
            rules: [{ required: true, message: "设备名称必须填写" }],
            readonly: true,
          },
          {
            type: "select",
            label: "设备情况",
            overHidden: true,
            span: 8,
            prop: "equipStatus",
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=test_equipment",
            required: true,
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [{ required: true, message: "设备情况必须填写" }],
          },
          {
            type: "input",
            label: "检定机构",
            span: 8,
            prop: "verificationMechanism",
            rules: [{ required: true, message: "请输入检定机构" }],
          },

          // {
          //   span: 8,
          //   hide: true,
          //   display: true,
          //   type: "select",
          //   overHidden: true,
          //   label: "检定人员",
          //   prop: "verificationUser",
          //   component: "wf-user-select",
          //   rules: [{ required: true, message: "请选择检定人员" }],
          // },
          {
            label: "检定时间",
            prop: "verificationTime",
            span: 8,
            align: "left",
            overHidden: "true",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            rules: [{ required: true, message: "请输入检定机构" }],
          },
          {
            type: "textarea",
            label: "检定情况",
            span: 24,
            prop: "verificationInfo",
            overHidden: true,
          },
        ],
      },
      // 状态
      statusList: [],
      // 查询
      searchForm: {
        equipName: "",
      },
      searchText: {
        flag: 3,
        addText: "批量检定",
      },
      // 表格
      loading: false,
      option: tableOption,
      tableData: [],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      // 从仪器设备传来的仪器设备对象
      equipmentObj: {},
      situationList: [],
    };
  },
  filters: {
    statusFl: (data) => {
      for (const i in that.statusList) {
        const element = that.statusList[i];
        if (data == element.dictKey) {
          return element.dictValue;
        }
      }
    },
  },
  beforeCreate() {
    that = this;
  },
  created() {
    // 获取状态list
    getStatus().then((res) => {
      this.statusList = res.data.data;
    });
    getSituation().then((res) => {
      this.situationList = res.data.data;
    });
    if (this.$route.query.row) {
      this.equipmentObj = JSON.parse(this.$route.query.row);
      this.form = Object.assign({
        equipName: this.equipmentObj.name,
        equipModel: this.equipmentObj.model,
        manufacturerOrBrand: this.equipmentObj.manufacturerBrand,
        status: "0",
        code: this.equipmentObj.code,
        enableTime: this.equipmentObj.enableDate,
        saveById: this.equipmentObj.saveById,
        warnBefore: 30,
        cycle: "1",
        instrumentId: String(this.equipmentObj.id)
      });
      Object.assign(this.searchForm, { instrumentId: String(this.equipmentObj.id) });
      getList(this.page.currentPage, this.page.pageSize, this.searchForm).then(
        (res) => {
          let tempTotal = res.data.data.total;
          if (tempTotal === 0) {
            // 调起新增弹框
            this.$refs.crud.rowAdd();
          }
        }
      );
    }
  },
  mounted() {
    if (JSON.stringify(this.$store.state.client.testParams) !== "{}") {
      this.searchForm = this.$store.state.client.testParams;
    }
    this.onLoad(this.page);
  },
  methods: {
    // 填充机构数据
    addDept() {
      this.selectionList = this.selectionList.map((item) => {
        return {
          ...item,
          verificationMechanism: this.verificationMechanism,
        };
      });
      this.verificationMechanism = "";
    },
    // 填充设备情况数据
    addReamrk() {
      this.selectionList = this.selectionList.map((item) => {
        return {
          ...item,
          verificationInfo: this.verificationInfo,
        };
      });
      this.verificationInfo = "";
    },
    // 取消
    cencel() {
      this.selectdialogVisible = false;
    },
    testSubmit() {
      this.testSubmitLoading = true
      verification({verificationList: this.selectionList}).then(res => {
        this.$message.success("批量检定成功！")
        this.testSubmitLoading = false
        this.selectdialogVisible = false
        this.onLoad(this.page)
      })

    },
    selectionChange(list) {
      this.selectionList = list;
    },
    getRowKeys(row) {
      return row.id;
    },
    // 检定-跳转检定记录
    testHandle(row) {
      this.testObj = { ...row };
      this.testObj.equipStatus =  "1"
      this.testObj.verificationTime = dateFormat(new Date())
      this.dialogVisible = true;
    },
    // 检定提交
    submit() {
      addTest(this.testObj).then((res) => {
        this.$message.success("检定成功!");
        this.dialogVisible = false;
        this.$router.push({
          path: "/repair/verificationRecord",
          query: { row: JSON.stringify(this.testObj) },
        });
        this.testObj = {};
      });
    },
    testCloseDialog() {
      this.dialogVisible = false;
    },
    // 分页
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },
    sizeChange(pagesize) {
      this.page.pagesize = pagesize;
      this.onLoad(this.page);
    },
    /**
     * 列表查询
     */
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.searchForm)
      ).then((res) => {
        const { total, records } = res.data.data;
        this.page.total = total;
        this.tableData = records;
        this.loading = false;
      });
    },
    /**
     * 搜索组件
     */
    searchHandle(item, index) {
      this.searchForm.equipName = item.name;
      this.page.currentPage = 1;
      if (index === 1) {
        this.searchForm = { equipName: "" };
        this.onLoad(this.page);
      } else {
        this.onLoad(this.page, item);
      }
      this.$store.dispatch("changeSetting", {
        title: "testParams",
        form: this.searchForm,
      });
    },
    // 新增弹框
    addHandle() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择勾选数据项！");
      } else {
        this.selectionList = this.selectionList.map((item) => {
          return {
            ...item,
            equipStatus: "1",
            verificationTime: dateFormat(new Date()),
          };
        });
        this.selectdialogVisible = true;
      }
    },
    // 新增
    rowSave(row, done, loading) {
      add(row).then(
        (res) => {
          // 获取新增数据的相关字段
          const data = res.data.data;
          row.id = data.id;
          // row.tenantId = data.tenantId
          this.$message({ type: "success", message: "新增成功!" });
          this.onLoad(this.page);
          // 数据回调进行刷新
          done(row);
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    // 编辑
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.$message({ type: "success", message: "修改成功!" });
          this.onLoad(this.page);
          // 数据回调进行刷新
          done(row);
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    // 行删除
    rowDel(row, index) {
      this.$confirm("此操作会删除该数据，且无法恢复，确定删除数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        remove(row.id).then((res) => {
          this.$message.success("删除成功!");
          this.onLoad(this.page);
        });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
/deep/ .avue-crud__menu {
  display: none;
}
.q_add {
  display: flex;
  margin: 20px 0;
}
.footer {
  margin-top: 30px;
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
