<template>
  <div class="content-main">
    <el-form
      :inline="true"
      :model="formInline"
      class="demo-form-inline search-form"
      label-width="100px"
    >
      <el-row>
        <el-form-item label="承储企业:">
          <el-input
            class="inputCompatible"
            clearable
            v-model="formInline.ccqy"
            style="width: 170px"
            placeholder="模糊查询库点名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="仓号:">
          <el-input
            class="inputCompatible"
            clearable
            v-model="formInline.cfmc"
            style="width: 170px"
            placeholder="模糊查询仓房名称"
          ></el-input>
        </el-form-item>

        <el-form-item class="search-button">
          <span class="search-line"></span>
          <div class="search-select" @click="searchShowMore">
            更多条件
            <i class="el-icon-arrow-up" v-show="searchShowMoreBool"></i
            ><i class="el-icon-arrow-down" v-show="!searchShowMoreBool"></i>
          </div>
          <el-button
            type="primary"
            @click="doSearch"
            size="small"
            class="iconfont iconchaxun"
            >查询</el-button
          >
          <el-button
            type="primary"
            @click="doReset"
            size="small"
            class="iconfont iconzhongzhi"
            >重置</el-button
          >
        </el-form-item>
      </el-row>
      <el-row v-show="searchShowMoreBool">
        <el-form-item label="品种:">
          <el-cascader
            clearable
            class="inputCompatible"
            :options="pzOptions"
            :props="pzProps"
            :show-all-levels="false"
            v-model="formInline.pzbm"
            placeholder="请选择"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="处理方式:" v-if="type == 1">
          <el-select v-model="formInline.clfs" placeholder="请选择" clearable>
            <el-option label="手动处理" :value="0"></el-option>
            <el-option label="自动处理" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-button
        type="warning"
        size="small"
        @click="msgDialogVisible = true"
        style="position: absolute; top: 24px; right: 10px"
        >预警说明</el-button
      >
      <el-dialog
        title="预警说明"
        size="small"
        :visible.sync="msgDialogVisible"
        width="35%"
        top="30vh"
        :modal="false"
      >
        <div>
          <span>1、临近存储超限时间3个月/1个月，未完全出库，黄色预警提示。</span><br><br>
          <span>2、当超过存储年限时，未完全出库，红色预警提示。</span>
        </div>
      </el-dialog>
    </el-form>
    <el-row>
      <el-table
        :data="tableData"
        v-loading="listLoading"
        border
        stripe
        fit
        highlight-current-row
        style="width: 100%"
        :header-cell-style="{'text-align':'center'}"
      >
        <el-table-column
          align="center"
          label="序号"
          width="50"
          type="index"
        ></el-table-column>
        <el-table-column
          width="260"
          show-overflow-tooltip
          prop="ccqy"
          label="承储库"
          v-if="type == 0"
        >
          <template slot-scope="scope">
            <img v-if="scope.row.cfzt == 3" src="./red.png" />
            <img v-if="scope.row.cfzt < 3" src="./yellow.png" />
            <span>{{ scope.row.ccqy }}</span>
          </template>
        </el-table-column>
        <el-table-column
          min-width="240"
          show-overflow-tooltip
          prop="ccqy"
          label="承储库"
          align="center"
          v-if="type == 1"
        >
        </el-table-column>
        <el-table-column
          width="105"
          align="center"
          prop="cfmc"
          label="仓房名称"
        >
        </el-table-column>
        <el-table-column
          align="center"
          min-width="215"
          show-overflow-tooltip
          prop="lyxz"
          label="粮油性质"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="pzmc"
          min-width="120"
          show-overflow-tooltip
          label="品种"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="kcsl"
          width="110"
          label="库存数量(吨)"
        >
          <template slot-scope="scope">
            <span>{{!parseFloat(scope.row.kcsl) ? "" :(Number.isInteger(scope.row.kcsl) ? scope.row.kcsl : parseFloat(scope.row.kcsl).toFixed(3))}}</span>
            <!-- <span>
              {{String(scope.row.kcsl).indexOf(".") > -1 ? parseFloat(scope.row.kcsl).toFixed(3) : scope.row.kcsl}}
            </span> -->
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="scnf"
          label="生产年份"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="cbnx"
          label="储备年限"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="cccxsj"
          width="110"
          label="储存超限时间"
        ></el-table-column>
        <el-table-column align="center" prop="bjsj" width="110" label="报警日期">
        </el-table-column>
        <el-table-column
          align="center"
          prop="clfs"
          label="处理方式"
          v-if="type == 1"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.clfs == 0 ? "手动处理" : "自动处理" }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="130">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="light"
              content="查看"
              placement="top"
              v-if="type == 1"
            >
              <el-button
                type="primary"
                size="small"
                class="operate_show_btn iconfont iconchakan2"
                @click="handleDetail(scope.row, 0)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="light"
              content="处理"
              placement="top"
              v-if="buttonNameList.indexOf('处理') > -1 && type == 0"
            >
              <el-button
                type="primary"
                @click="handleDetail(scope.row, 1)"
                class="operate_edit_btn iconfont iconchuli"
                size="small"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="light"
              content="图像"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                class="operate_show_btn iconfont iconchaxun"
                @click="handlePic(scope.row,0)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="light"
              content="监控"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                class="operate_show_btn iconfont iconchaxun iconjk"
                @click="handlePic(scope.row,1)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="pageForm.page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageForm.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageForm.total"
      ></el-pagination>
    </el-row>
    <el-dialog title="提示" :visible.sync="dialogVisible" :close-on-click-modal="false" width="50%">
      <el-form
        :model="formDetail"
        label-width="100px"
        :rules="rule"
        ref="formDetail"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="处理人:">
              <el-input
                disabled
                class="inputCla"
                clearable
                v-model="formDetail.clrmc"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处理时间:">
              <el-input
                class="inputCla"
                disabled
                v-model="formDetail.clsj"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="处理意见:" prop="clyj">
              <el-input
                class="inputClaBig"
                type="textarea"
                clearable
                :disabled="showFlag"
                v-model="formDetail.clyj"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          class="iconfont iconbaocun"
          size="small"
          @click="save"
          v-if="type == 0"
          >保存</el-button
        >
        <el-button
          type="primary"
          class="iconfont iconfanhui"
          size="small"
          @click="dialogVisible = false"
          >返回</el-button
        >
      </span>
    </el-dialog>
    <el-dialog title="查看图像" :visible.sync="picVisible" :close-on-click-modal="false" width="70%">
      <div class="content_box" v-if="imgList.length >0" v-loading="picLoading">
        <div class="block" v-for="(item,index) in imgList" :key="index" >
          <el-image
            style="width: 100%;min-height:200px"
            :src="item.fileUrl"
            fit="contain"
          >
          </el-image>
        </div>
      </div>
      <div class="empty" style="width:100%;heigth:50px;line-height:50px" v-else>暂无内容</div>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          class="iconfont iconfanhui"
          size="small"
          @click="picVisible = false"
          >返回</el-button
        >
      </span>
    </el-dialog>
    <el-dialog title="查看监控" ref="monitorVisible" :visible.sync="monitorVisible" :close-on-click-modal="false" @close="jkcloseDialog" width="70%">
      <div class="content_box" v-if="imgList.length >0" v-loading="picLoading">
        <div class="monitor">
          <h4>监控视频</h4>
        </div>
        <el-row style="display: flex; justify-content: space-between">
          <el-col :span="24">
            <div style="height: 400px">
              <!-- 插件未启动，正在尝试启动，请稍候... -->
              <div id="playHys" class="playHys"></div>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="empty" style="width:100%;heigth:50px;line-height:50px" v-else>暂无内容</div>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          class="iconfont iconfanhui"
          size="small"
          @click="jkcloseDialog"
          >返回</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  alarmList,
  alarmUpdate,
  videoList,
} from "@/api/earlyWarning/storageOverrunWarning/index";
import { authorityControl, getVarietyList } from "@/api/login/login.js";
import { getNowDate } from "@/utils/index";

export default {
  props: ["type"],
  data() {
    return {
      msgDialogVisible: false,
      dialogVisible: false,
      pzProps: {
        label: "dictName",
        value: "dictCode",
        // checkStrictly: true,
        emitPath: false,
      },
      searchShowMoreBool: false,
      listLoading: true,
      formInline: {
        ccqy: "",
        cfmc: "",
        clfs: "",
        pzbm: "",
      },
      pageForm: {
        page: 1,
        size: 10,
        total: 0,
      },
      kdOptions: [], // 库点名称列表
      pzOptions: [], // 品种列表
      tableData: [],
      buttonNameList: [],
      formDetail: {
        clrmc: "",
        clsj: "",
        clyj: "",
      },
      showFlag: true,
      rule: {
        clyj: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      picLoading: false,
      picVisible: false,
      monitorVisible: false,
      imgList: [],
      monitorCode: "", //监控编码
    };
  },
  methods: {
    doReset() {
      this.formInline = {
        ccqy: "",
        cfmc: "",
        clfs: "",
        pzbm: "",
      };
      this.doSearch();
    },
    doSearch() {
      this.pageForm.page = 1;
      this.listLoading = true;
      this.getList();
    },
    getButtonList() {
      let codeData = {
        resourceCode: sessionStorage.getItem("resourceCode"),
        userId: sessionStorage.getItem("userCode"),
      };
      authorityControl(codeData).then((res) => {
        res.data.forEach((item) => {
          this.buttonNameList.push(item.resourceName);
        });
        this.getList("start");
      });
    },
    getList(type) {
      if (type != "start") {
        //非初始化调用：查询、分页
        sessionStorage.setItem("searchData", JSON.stringify(this.formInline));
        sessionStorage.setItem("pageData", JSON.stringify(this.pageForm));
      } else {
        //初始化分两种情况，详情页等返回后的初始化，以及第一次进入此菜单的初始化
        if (JSON.parse(sessionStorage.getItem("searchData"))) {
          //详情页返回后，将对应查询条件和分页的字段赋值，页面回显参数
          this.formInline = JSON.parse(sessionStorage.getItem("searchData"));
          this.pageForm = JSON.parse(sessionStorage.getItem("pageData"));
        } else {
          //第一次进去此菜单时，保存上方默认的data
          sessionStorage.setItem("searchData", JSON.stringify(this.formInline));
          sessionStorage.setItem("pageData", JSON.stringify(this.pageForm));
        }
      }
      //   // 把字符串转为null , 后台现处理不了空字符
      //   Object.keys(this.formInline).forEach((k) => {
      //     if (this.formInline[k] === "") {
      //       this.formInline[k] = null;
      //     }
      //   });
      let data = {
        ...this.formInline,
        pageNum: this.pageForm.page,
        pageSize: this.pageForm.size,
        clzt: this.type,
      };
      alarmList(data)
        .then((res) => {
          this.listLoading = false;
          if (res.code === 200) {
            this.tableData = res.data.list;
            this.pageForm.total = res.data.total;
            this.pageForm.page = res.data.pageNum;
            return;
          }
        })
        .catch((err) => {
          this.listLoading = false;
          this.$message.error("获取数据失败");
        });
    },
    handleDetail(row, state) {
      this.formDetail.id = row.id;
      if (state) {
        this.showFlag = false;
        this.formDetail.clsj = getNowDate();
        this.formDetail.clrmc = sessionStorage.getItem("userName");
        this.formDetail.clyj = "";
      } else {
        this.showFlag = true;
        this.formDetail.clsj = row.clsj;
        this.formDetail.clrmc = row.clrmc;
        this.formDetail.clyj = row.clyj;
      }
      this.dialogVisible = true;
    },
    save() {
      this.$refs.formDetail.validate((valid) => {
        if (valid) {
          let data = {
            ...this.formDetail,
          };
          alarmUpdate(data)
            .then((res) => {
              if (res.code == 200) {
                this.$message({ type: "success", message: "保存成功！" });
                this.dialogVisible = false;
                this.getList();
              } else {
                this.$message({ type: "error", message: res.message });
              }
            })
            .catch((res) => {
              this.$message({ type: "error", message: "保存失败！" });
            });
        }
      });
    },
    handleSizeChange(val) {
      this.pageForm.size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.pageForm.page = val;
      this.getList();
    },
    searchShowMore() {
      this.searchShowMoreBool = !this.searchShowMoreBool;
    },
    // 获取品种
    async getVarieties() {
      let res = await getVarietyList();
      if (res.infoCode === 200) {
        this.pzOptions = res.data;
        return;
      }
      this.$message.error(res.msg || "获取品种列表失败");
    },
    // 仓内视频图
    handlePic(row, type) {
      this.picLoading = true;
      if (type == 0) {
        this.picVisible = true
      }else{
        this.monitorVisible = true
      }
      let data = {
        kqdm:row.kqbm,
        cfdm:row.cfbm,
        startDate:row.bjsj,
        endDate:row.bjsj,
      };
      videoList(data)
        .then((res) => {
          this.picLoading = false;
          this.imgList = res.data.list
          if (res.data.list.length>0 && type == 1) {
            this.monitorCode = res.data.list[0].jkdbm
            this.camera(this.monitorCode);
          }else{
            this.monitorCode = ""
          }
        })
        .catch((err) => {
          this.picLoading = false;
          this.$message.error("获取数据失败");
        });
    },
    // 摄像头
    camera(spl) {
      var that = this;
      let widthNum = this.$refs.monitorVisible.$el.offsetWidth * 0.5
      that.oWebControl = new WebControl({
        szPluginContainer: "playHys",
        iServicePortStart: 15900,
        iServicePortEnd: 15909,
        cbConnectSuccess: function () {
          that.oWebControl
            .JS_StartService("window", {
              dllPath: "./VideoPluginConnect.dll",
            })
            .then(
              function () {
                that.oWebControl
                  .JS_CreateWnd("playHys", widthNum, 400)
                  .then(function () {
                    that.oWebControl
                      .JS_RequestInterface({
                        //要显示视频预览或回放的窗口，需要对插件进行初始化，初始化接口为：JS_RequestInterface
                        funcName: "init",
                        argument: JSON.stringify({
                          appkey: "24012924",
                          secret: "uHzSYRUJpnCVCJSIEUWc",
                          ip: "10.69.3.1",
                          // playMode: 0,  // 0预览   1回放
                          playMode: that.playMode,
                          port: 443,
                          snapDir: "D:SnapDir",
                          layout: "1x1",
                          enableHTTPS: 1,
                          encryptedFields: "",
                        }),
                      })
                      .then(function (oData) {
                          that.ylFnCnHys(spl);
                      });
                  }).catch((res)=>{
                    console.log(res,"res");
                  })
              },
              function () {}
            );
        },
        cbConnectError: function () {
          that.oWebControl = null;
          $("#playHys").html("插件未启动，正在尝试启动，请稍候...");
        },
        cbConnectClose: function () {
          that.oWebControl = null;
        },
      });
    },
    // 摄像头预览方法
    ylFnCnHys(spl) {
      var that = this;
      that.oWebControl
        .JS_RequestInterface({
          funcName: "startPreview",
          argument: JSON.stringify({
            // cameraIndexCode: "7eba727650794851b1d34f281a6e22b8",
            cameraIndexCode: spl,
            streamMode: 0,
            transMode: 1,
            gpuMode: 0,
          }),
        })
        .then(function (oData) {});
    },
    //关闭摄像头窗口
    jkcloseDialog() {
      this.monitorVisible = false;
      let oWebControl = this.oWebControl;
      if (oWebControl != null) {
        oWebControl.JS_HideWnd(); // 先让窗口隐藏，规避可能的插件窗口滞后于浏览器消失问题
        oWebControl.JS_Disconnect().then(
          function () {
            // 断开与插件服务连接成功
          },
          function () {
            // 断开与插件服务连接失败
          }
        );
      }
    },
  },
  // created() {
  //   this.getButtonList();
  // },
};
</script>

<style lang="scss" scoped>
.inputCla {
  width: 90%;
}
.inputClaBig {
  width: 96%;
}
.content_box{
  width: 70%;
  min-height: 400px;
  margin: auto;
  .block{
    margin-top: 10px;
    border: 1px solid #006ad576;
  }
}
.iconjk{
  background-color: #006bd5 !important;
}
/deep/ .el-image__error{
  width: 100%;
  height: 200px;
  line-height: 200px;
}
</style>
