<template>
  <div class="examination secondApprove">
    <div class="common-head-search">
      <el-form :inline="true">
        <el-form-item label="样品类型">
          <el-select v-model="search.sampleTypeCode" clearable filterable collapse-tags size="small"
            style="width: 150px" placeholder="请选择">
            <el-option v-for="item in sampleTypeNameType" :key="item.baseCode" :label="item.baseName"
              :value="item.baseCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="样品名称">
          <el-input v-model="search.matName" size="small" placeholder="请输入样品名称" style="width: 150px"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="中心编号">
          <el-input v-model="search.sampleNo" size="small" placeholder="请输入中心编号" style="width: 150px"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="委托编号">
          <el-input v-model="search.carNo" size="small" placeholder="请输入委托编号" style="width: 150px" clearable></el-input>
        </el-form-item>
        <el-form-item label="委托日期">
          <el-date-picker v-model="search.stateTime[0]" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date"
            placeholder="开始日期" size="mini" style="width: 150px">
          </el-date-picker>
          <span>至</span>
          <el-date-picker v-model="search.stateTime[1]" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date"
            placeholder="结束日期" size="mini" style="width: 150px">
          </el-date-picker>
          <!-- <el-date-picker v-model="search.stateTime" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="daterange"
            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" size="mini" style="width: 200px">
          </el-date-picker> -->
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="goon" size="mini" :loading="dataLoading"
            @click="searchData">查询</el-button>
          <el-button icon="el-icon-refresh" type="info" plain size="mini" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-row>
      <el-col :span="4">
        <div class="common-title-div">
          <div class="common-title-name">
            <img style="width: 25px; height: 25px" src="../../../assets/img/imgScreen/logo.png" />
            <span style="font-size: 15px">物料名称</span>
          </div>
        </div>
        <div class="common-table-div">
          <el-table ref="tableMain11" :height="singleTableHeight" v-loading="tableLoading" :data="table.list"
            highlight-current-row @row-click="handleCurrentChange" :summary-method="getSummaries"
            :header-cell-style="tableHeaderCellStyle" show-summary border style="width: 100%" :icorePanelShown="100"
            :icore-filter-flag="icoreFilterFlag">
            <el-table-column sortable show-overflow-tooltip align="center" min-width="100" prop="MAT_NAME"
              label="物料名称"></el-table-column>
          </el-table>
        </div>
      </el-col>
      <el-col :span="20">
        <div class="common-title-div">
          <div class="common-title-name">
            <img style="width: 25px; height: 25px" src="../../../assets/img/imgScreen/logo.png" />
            台账信息
          </div>
          <div class="common-button-div">
            <el-button icon="el-icon-download" type="goon" size="mini" :loading="tableExportLoading"
              @click="maintenance">维护上下限</el-button>
            <el-button icon="el-icon-download" type="goon" size="mini" :loading="tableExportLoading"
              @click="doExport">导出</el-button>
          </div>
        </div>
        <div class="common-table-div" id="topTable">
          <el-table ref="el_table_1" border :height="singleTableHeight" width="100%" highlight-current-row
            @selection-change="searchFollow" :data="table.list1">
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column sortable show-overflow-tooltip align="center" width="160" prop="CAR_NO"
              label="委托编号"></el-table-column>
            <el-table-column sortable show-overflow-tooltip align="center" width="120" prop="SAMPLE_NO"
              label="中心编号"></el-table-column>
            <el-table-column sortable show-overflow-tooltip align="center" width="120" prop="MAT_NAME"
              label="物料名称"></el-table-column>
            <el-table-column sortable show-overflow-tooltip align="center" width="120" prop="MEMO"
              label="委托备注"></el-table-column>
            <el-table-column v-for="col in cols" :prop="col.ANLY_ITEM_NO" show-overflow-tooltip align="center"
              :key="col.ANLY_ITEM_NO" :label="col.ANLY_ITEM_NAME">
              <template slot-scope="scope">
                <span :style="redStyle(scope.row.SA_ID, col.ANLY_ITEM_NO)">{{
                  scope.row[col.ANLY_ITEM_NO]
                  }}</span>
              </template>
            </el-table-column>
            <el-table-column sortable show-overflow-tooltip align="center" width="120" prop="UPDATE_TIME"
              label="开始时间"></el-table-column>
            <el-table-column sortable show-overflow-tooltip align="center" width="120" prop="CREATE_TIME"
              label="结束时间"></el-table-column>
          </el-table>
        </div>
        <div class="common-foot-style">
          <el-pagination @size-change="pageSizeChange" @current-change="pageCurrentChange" :current-page="page.pageNum"
            :page-sizes="[50, 100, 200, 500, 1000]" :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="page.totalPage" background>
          </el-pagination>
        </div>
      </el-col>
    </el-row>
    <el-dialog :close-on-click-modal="false" @close="closebatch" width="100%" :visible.sync="recallShow" top="0">
      <div slot="title" class="titleBox">
        <i class="el-icon-document" style="font-size: 20px"></i>
        <span style="margin-left: 10px; font-size: 18px">维护信息</span>
      </div>
      <div class="common-table-div">
        <el-table border ref="dataTable123" :data="recallList" :height="theight2" @selection-change="recallSelection"
          highlight-current-row>
          <el-table-column type="selection" width="45" align="center"></el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="80" align="center" prop="ANLY_ITEM_NAME"
            label="检测项目"></el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="80" align="center" prop="MIN_SIGN" label="下限符号">
            <template slot-scope="scope">
              <input v-model="scope.row.MIN_SIGN" size="small" @keydown="keyDown($event, scope.row, scope.$index)"
                :id="scope.column.id + '--' + scope.$index" @change="inputDataPl($event, scope.$index)" style="
                  width: 100%;
                  height: 28px;
                  line-height: 28px;
                  border: 0px;
                  padding-left: 3px;
                  text-align: center;
                  font-size: 15px;
                " />
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="80" align="center" prop="MIN_VALUE" label="下限值">
            <template slot-scope="scope">
              <input v-model="scope.row.MIN_VALUE" size="small" @keydown="keyDown($event, scope.row, scope.$index)"
                :id="scope.column.id + '--' + scope.$index" @change="inputDataPl($event, scope.$index)"
                oninput="value=value.replace(/[^0-9\[.\]{1}-]/g,'')" style="
                  width: 100%;
                  height: 28px;
                  line-height: 28px;
                  border: 0px;
                  padding-left: 3px;
                  text-align: center;
                  font-size: 15px;
                " />
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="80" align="center" prop="MAX_SIGN" label="上限符号">
            <template slot-scope="scope">
              <input v-model="scope.row.MAX_SIGN" size="small" @keydown="keyDown($event, scope.row, scope.$index)"
                :id="scope.column.id + '--' + scope.$index" @change="inputDataPl($event, scope.$index)" style="
                  width: 100%;
                  height: 28px;
                  line-height: 28px;
                  border: 0px;
                  padding-left: 3px;
                  text-align: center;
                  font-size: 15px;
                " />
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="80" align="center" prop="MAX_VALUE" label="上限值">
            <template slot-scope="scope">
              <input v-model="scope.row.MAX_VALUE" size="small" @keydown="keyDown($event, scope.row, scope.$index)"
                :id="scope.column.id + '--' + scope.$index" @change="inputDataPl($event, scope.$index)"
                oninput="value=value.replace(/[^0-9\[.\]{1}-]/g,'')" style="
                  width: 100%;
                  height: 28px;
                  line-height: 28px;
                  border: 0px;
                  padding-left: 3px;
                  text-align: center;
                  font-size: 15px;
                " />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="goon" size="mini" icon="el-icon-check" :loading="batchLoading"
          @click="determineList()">确认</el-button>
        <el-button size="mini" type="goon" icon="el-icon-remove-outline" @click="closebatch">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getCookie, formatDate } from "@/utils/util.js";
import { cookieUserId, cookieUserName } from "@/config/config.js";
import { exportToExcel } from "../../../utils/utils.js";
let userName = getCookie(cookieUserName);
let userId = getCookie(cookieUserId);
export default {
  data() {
    return {
      search: {
        sampleTypeCode: "",
        sampleNo: "",
        carNo: "",
        matName: "",
        stateTime: [],
      },
      dataLoading: false,
      dataLoading1: false,
      sampleTypeNameType: [], //样品类型
      saveMainData: [], //勾选数据
      tableList: {},
      table: {
        list: [],
        list1: [],
      },
      page: {
        pageNum: 1,
        pageSize: 100,
        totalPage: 0,
      },
      cols: ["无"],
      redDataCk: [], //显红的数据
      singleTableHeight: 600,
      icoreFilterFlag: true,
      tableLoading: false,
      tableExportLoading: false,
      batchLoading: false,
      recallShow: false,
      recallList: [],
      theight2: 0,
      recallSelectionList: [],
      clickMap: {}
    };
  },
  created() {
    this.singleTableHeight = window.innerHeight - 190;
    this.theight2 = window.innerHeight - 180;
    let aaa = new Date();
    let bbb = new Date().getTime() - 60000 * 60 * 24 * 7;
    aaa.setTime(bbb);
    this.search.stateTime = [this.getYNM(aaa), this.getYNM(new Date())];
  },
  mounted() {
    this.axios
      .post(
        "pass/baseManagement/v1/limsbaseinfos/queryBaseInfoByBaseCode",
        { validFlag: 1, baseCode: 4801 },
        { individualType: "json" }
      )
      .then((res) => {
        this.sampleTypeNameType = res.data;
      });
  },
  methods: {
    getYNM(date) {
      let year = date.getFullYear().toString();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      month = month < 10 ? "0" + month : month;
      day = day < 10 ? "0" + day : day;
      return `${year}-${month}-${day}`;
    },
    mainData() {
      this.page.pageNum = 1;
      this.page.pageSize = 100;
      this.searchData();
    },
    searchFollow(val) {
      this.saveMainData = val;
    },
    searchData1() {
      let startTime = "";
      let endTime = "";
      if (!this.search.stateTime) {
      } else {
        startTime = this.search.stateTime[0];
        endTime = this.search.stateTime[1];
      }
      let obj = {
        matName: this.search.matName,
        sampleTypeCode: this.search.sampleTypeCode,
        sampleNo: this.search.sampleNo,
        carNo: this.search.carNo,
        stateFlag: 1,
        validFlag: 1,
        startTime: startTime,
        endTime: endTime,
      };
      if (this.tableList.MAT_NO != null) {
        this.searchData()
      } else {
        this.dataLoading = true;
        this.axios
          .post(
            "pass/baseManagement/v1/limssamplereleases/queryParameterMatName",
            obj,
            { individualType: "json" }
          )
          .then((res) => {
            if (res.code == 0 || res.code == 200) {
              this.table.list = res.data;
            } else {
              this.$message.error(res.message);
            }
            this.dataLoading = false;
          })
          .catch((err) => {
            this.dataLoading = false;
            this.$message.error(err.message);
          });
      }
    },
    searchData() {
      let startTime = "";
      let endTime = "";
      if (!this.search.stateTime) {
      } else {
        startTime = this.search.stateTime[0];
        endTime = this.search.stateTime[1];
      }
      let obj = {
        sampleTypeCode: this.search.sampleTypeCode,
        sampleNo: this.search.sampleNo,
        carNo: this.search.carNo,
        pageIndex: this.page.pageNum,
        pageSize: this.page.pageSize,
        stateFlag: 1,
        validFlag: 1,
        startTime: startTime,
        endTime: endTime,
        matName: this.clickMap.MAT_NAME || this.search.matName,
        matNo: this.clickMap.MAT_NO,
      };
      this.dataLoading = true;
      this.axios
        .post("pass/baseManagement/v1/limssamplereleases/queryParameter", obj, {
          individualType: "json",
        })
        .then((res) => {
          if (res.code == 0 || res.code == 200) {
            if (res.data.head[0] != null) {
              this.cols = res.data.head;
            } else {
              this.cols = [];
            }
            this.table.list1 = res.data.badyData.list;
            if (this.table.list1 != null && this.table.list1.length > 0) {
              if (Object.keys(this.clickMap).length === 0) {
                this.table.list = res.data.badyData.list[0].sampleResults
              }
            } else {
              if (Object.keys(this.clickMap).length === 0) {
                this.table.list = []
              }
            }
            this.page.totalPage = res.data.badyData.total;
            this.redDataCk = res.data.redMap || {};
            this.clickMap = {}
          } else {
            this.$message.error(res.message);
          }
          this.dataLoading = false;
        })
        .catch((err) => {
          this.dataLoading = false;
          this.$message.error(err.message);
        });
    },
    closebatch() {
      this.recallShow = false;
      this.recallList = [];
    },
    recallSelection(val) {
      this.recallSelectionList = val;
    },
    determineList() {
      if (this.recallSelectionList.length < 1) {
        this.$message.warning("请勾选要确定的数据！");
        return;
      }
      let arr = [];
      this.saveMainData.forEach((s) => {
        arr.push(s.SA_ID);
      });
      let obj = {
        list: arr,
        map: this.recallSelectionList,
      };
      this.batchLoading = true;
      this.axios
        .post(
          "pass/baseManagement/v1/limssamplereleaseds/updateLimsSampleReleaseD",
          obj,
          { individualType: "json" }
        )
        .then((res) => {
          if (res.code == 0 || res.code == 200) {
            this.closebatch();
            this.$message.success("维护成功！");
            this.searchData();
          } else {
            this.$message.error(res.message);
          }
          this.batchLoading = false;
        })
        .catch((err) => {
          this.batchLoading = false;
          this.$message.error(err.message);
        });
    },
    maintenance() {
      if (this.saveMainData.length < 1) {
        this.$message.warning("请先选择一个需要维护的数据！");
        return;
      }
      let arr = [];
      this.saveMainData.forEach((s) => {
        arr.push(s.SA_ID);
      });
      this.tableExportLoading = true;
      this.axios
        .post(
          "pass/baseManagement/v1/limssamplereleaseds/maintenanceList",
          arr,
          { individualType: "json" }
        )
        .then((res) => {
          if (res.code == 0 || res.code == 200) {
            this.recallList = res.data;
            this.recallShow = true;
          } else {
            this.$message.error(res.message);
          }
          this.tableExportLoading = false;
        })
        .catch((err) => {
          this.tableExportLoading = false;
          this.$message.error(err.message);
        });
    },
    // 导出
    doExport() {
      // if (this.table.list1.length === 0) {
      //     this.$message.warning("表格无数据不能导出");
      //     return true;
      // }
      if (this.saveMainData.length < 1) {
        this.$message.warning("表格无数据不能导出");
        return;
      }
      this.tableExportLoading = true;
      let tHeader = [];
      let filterVal = [];
      tHeader = [
        "委托编号",
        "中心编号",
        "物料名称",
        "委托备注",
        "开始时间",
        "结束时间",
      ];
      filterVal = [
        "CAR_NO",
        "SAMPLE_NO",
        "MAT_NAME",
        "MEMO",
        "UPDATE_TIME",
        "CREATE_TIME",
      ];
      this.cols.forEach((s) => {
        tHeader.push(s.ANLY_ITEM_NAME);
        filterVal.push(s.ANLY_ITEM_NO);
      });
      exportToExcel(
        this.saveMainData,
        tHeader,
        filterVal,
        "台账信息",
        [],
        [],
        []
      );

      // setTimeout(() => {
      //     setTimeout(() => {
      //     setTimeout(() => {
      this.tableExportLoading = false;
      //         this.doExport2();
      //     }, 0);
      //     }, 0);
      // }, 0);
    },
    doExport2() {
      this.$nextTick(() => {
        let table = document.querySelector("#topTable .el-table");
        let header = document.querySelector(
          "#topTable .el-table .el-table__header"
        );
        let body = document.querySelector(
          "#topTable .el-table .el-table__body"
        );
        let oTd = document.querySelectorAll("#topTable .el-table td");
        let oTh = document.querySelectorAll("#topTable .el-table th");
        header.border = "1";
        body.border = "1";
        for (let item of Array.from(oTd)) {
          item.style.height = "27px";
        }
        for (let item of Array.from(oTh)) {
          item.style.height = "27px";
        }
        let ex =
          '<th class="gutter" align= "left" style="width: 10px; height: 27px;"></th>';
        let ex2 =
          '<th class="gutter" align= "left" style="width: 0px; height: 27px;"></th>';
        ex = new RegExp(ex, "g").test(table.outerHTML) ? ex : ex2;
        let bd = table.outerHTML.replace(new RegExp(ex, "g"), "");
        bd = bd.replace("正在整理数据", "");
        let html =
          '<html><head><meta charset="utf-8" /></head><body>' +
          bd +
          "</body></html>";
        let blob = new Blob([html], { type: "application/vnd.ms-excel" });
        let link = document.createElement("a");
        link.download = "台账信息.xls";
        link.href = URL.createObjectURL(blob);
        link.click();
        header.border = "0";
        body.border = "0";
        for (let item of Array.from(oTd)) {
          item.style.height = "";
        }
        for (let item of Array.from(oTh)) {
          item.style.height = "";
        }
      });
    },
    handleCurrentChange(row) {
      this.clickMap = JSON.parse(JSON.stringify(row))
      this.searchData();
    },
    tableHeaderCellStyle() {
      return "color: rgb(255,255,255);border-bottom: 1px solid #DCDFE7;";
    },
    pageSizeChange(size) {
      this.page.pageSize = size;
      this.searchData();
    },
    pageCurrentChange(index) {
      this.page.pageNum = index;
      this.searchData();
    },
    reset() {
      this.search = {};
      let aaa = new Date();
      let bbb = new Date().getTime() - 60000 * 60 * 24 * 7;
      aaa.setTime(bbb);
      this.search.stateTime = [this.getYNM(aaa), this.getYNM(new Date())];
      this.tableList = {}
      this.table.list = []
      this.table.list1 = []
      this.searchData();
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计：" + data.length;
        }
      });
      return sums;
    },
    handleInput(val, index, prop) {
      let regex = /^>=?$/;
      let newValue = val;
      if (regex.test(newValue)) {
        this.recallList[index][prop] = newValue;
      } else {
        this.recallList[index][prop] = "";
      }
    },
    inputDataPl(val, index) {
      this.$refs.dataTable123.toggleRowSelection(this.recallList[index], true);
    },
    keyDown(event, row, rindex) {
      let tdTarget = event.target;
      let pid = tdTarget.id;
      if (!pid) {
        return true;
      }
      let ids = pid.split("--");
      if (ids.length != 2) {
        return true;
      }
      let columnId = ids[0];
      let index = ids[1];
      let that = this;
      while (tdTarget.tagName !== "TD") {
        tdTarget = tdTarget.parentElement;
      }
      // if (event.keyCode === 13) {
      //   this.jisuanRow(row, rindex)
      // }
      // 如果按下键盘下键或者回车键
      if (event.keyCode === 40 || event.keyCode === 13) {
        let ind = Number(index) + 1;
        let id = "#" + columnId + "--" + ind;
        let input = $(id);
        if (input) {
          // this.$refs.tablePllr.setCurrentRow(this.tableData[ind])
          input.focus();
          input.select(); // 选中内容
          event.stopPropagation();
          event.stopImmediatePropagation();
          event.preventDefault();
          return false;
        }
      } else if (event.keyCode === 38) {
        // 键盘上键
        let ind = Number(index) - 1;
        let id = "#" + columnId + "--" + ind;
        let input = $(id);
        if (input) {
          // this.$refs.tablePllr.setCurrentRow(this.tableData[ind])
          input.focus();
          input.select(); // 选中内容
          event.stopPropagation();
          event.stopImmediatePropagation();
          event.preventDefault();
          return false;
        }
      } else if (event.keyCode === 37) {
        // 键盘左键
        let input =
          $(tdTarget).prev().find("input") &&
          $(tdTarget).prev().find("input")[0];
        if (input) {
          input.focus();
          input.select(); // 选中内容
          event.stopPropagation();
          event.stopImmediatePropagation();
          event.preventDefault();
          return false;
        }
      } else if (event.keyCode === 39) {
        // 键盘右键
        let input = $(tdTarget).next().find("input")[0];
        if (input) {
          input.focus();
          input.select(); // 选中内容
          event.stopPropagation();
          event.stopImmediatePropagation();
          event.preventDefault();
          return false;
        }
      }
    },
    redStyle(stId, anlyNo) {
      let arr = this.redDataCk[stId];
      if (!arr || arr.length < 1) {
        return {};
      }
      let obj = arr.find((ii) => ii == anlyNo);
      if (obj) {
        return { color: "red" };
      } else {
        return {};
      }
    },
  },
};
</script>
<style scoped></style>
