<template>
  <div class="pd10">
    <div v-show="showCircuitPreview">
      <div v-show="showCircuitEdit">
        <el-form
          ref="form"
          :model="form"
          label-width="80px"
          class="demo-form-inline"
          :inline="true"
        >
          <el-form-item label="项目名称">
            <el-input
              v-model="formInline.searchValue"
              placeholder="请输入项目名称"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="onSubmitquery"
              icon="el-icon-search"
              >查询</el-button
            >
          </el-form-item>
          <el-form-item>
            &lt;!&ndash; <el-button type="primary" @click="onSubmitset">重置</el-button> &ndash;&gt;
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmitadd" icon="el-icon-plus"
              >新增</el-button
            >
          </el-form-item>
        </el-form>
        <div
          :style="'height:' + vth"
          style="overflow-x: hidden; overflow-y: scroll"
          v-loading="isLoading"
          element-loading-text="数据加载中"
        >
          <el-row :gutter="12">
            <el-col :span="6" v-for="item in data" :key="item.id" class="mt10">
              <el-card class="box-card" @click="querdata(item)" shadow="hover">
                <div slot="header" class="clearfix">
                  <span
                    >{{ item.name }}

                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="修改项目"
                      placement="top"
                    >
                      <i
                        style="padding: 0px 3px"
                        class="el-icon-edit xiaoshou color"
                        @click="editd(item)"
                      ></i> </el-tooltip
                  ></span>
                  <div style="float: right">
                    <el-button
                      class="color"
                      icon="el-icon-share"
                      style="padding: 3px 0"
                      type="text"
                      @click="Aclick(item)"
                      >设计</el-button
                    >
                    &lt;!&ndash;  <el-button
                      icon="el-icon-share"
                      style="padding: 3px 0; color: green"
                      type="text"
                      @click="shejid(item)"
                      >设计</el-button
                    >&ndash;&gt;
                    &lt;!&ndash; <el-button
                    icon="el-icon-edit"
                    style="padding: 3px 0; color: blue"
                    type="text"
                    @click="shejid(item)"
                    >编辑</el-button
                  > &ndash;&gt;
                    <el-button
                      icon="el-icon-delete"
                      style="padding: 3px 0; color: red"
                      type="text"
                      @click="deleted(item)"
                      >删除</el-button
                    >
                  </div>
                </div>
                <img
                  :src="item.fileContent"
                  class="image xiaoshou"
                  @click="imgData(item)"
                />
              </el-card>
            </el-col>
          </el-row>
        </div>
        <div class="blockPage">
          <el-pagination
            class="mt10"
            align="right"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="formInline.pageNum"
            :page-sizes="[12, 24, 36, 48]"
            :page-size="formInline.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>

        &lt;!&ndash;弹框&ndash;&gt;
        <el-dialog
          :title="title"
          :visible.sync="dialogVisible"
          v-if="dialogVisible"
          width="30%"
          :before-close="handleClose"
          :close-on-click-modal="false"
        >
          <el-form
            ref="form"
            :rules="rules"
            :model="form"
            label-width="90px"
            class="form"
          >
            <el-form-item label="项目名称:" prop="name">
              <el-input
                v-model.trim="form.name"
                placeholder="请输入项目名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="工程项目:" class="top" prop="projectIds">
              <el-select
                v-model="value"
                multiple
                style="width: 100%"
                placeholder="请选择"
                :popper-append-to-body="false"
                @remove-tag="removetag"
                collapse-tags
                @clear="clearall"
                clearable
              >
                <el-option :value="form.projectIds" class="setstyle" disabled>
                  <el-tree
                    :data="Engineering"
                    :props="defaultProps"
                    ref="tree"
                    show-checkbox
                    default-expand-all
                    :expand-on-click-node="false"
                    node-key="id"
                    check-strictly
                    @check-change="handleNodeClick"
                  ></el-tree>
                </el-option>
              </el-select>

              &lt;!&ndash; <el-cascader
                style="width: 100%"
                v-model="form.projectIds"
                :options="Engineering"
                :props="props"
                collapse-tags
                :show-all-levels="false"
                filterable
                clearable
              ></el-cascader>&ndash;&gt;
            </el-form-item>
            <el-form-item label="项目排序:" class="top" prop="orderBy">
              <el-input
                v-model.number="form.orderBy"
                @keyup.native="
                  form.orderBy = test(form.orderBy) ? form.orderBy : ''
                "
                placeholder="请输入项目顺序,只能输入数字"
              ></el-input>
            </el-form-item>
            &lt;!&ndash; <el-form-item label="关联设备:">
                <el-select v-model="form.value" placeholder="请选择" style="width:100%">
                <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
                </el-option>
             </el-select>
            </el-form-item> &ndash;&gt;

            <el-form-item label="备注:" class="top">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model.trim="form.remark"
              >
              </el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button
              type="primary"
              v-if="this.title == '新增项目'"
              @click="addFn"
              :loading="loading"
              >确 定</el-button
            >
            <el-button
              type="primary"
              v-if="this.title == '修改项目'"
              @click="auditFn"
              :loading="loading"
              >确 定</el-button
            >
          </span>
        </el-dialog>
      </div>
      <CircuitEdit
        v-if="!showCircuitEdit"
        @open="open"
        :params="params"
        @exit="exit"
      />
    </div>
    <CircuitPreview
      @refresh="showCircuitPreview = true"
      v-if="!showCircuitPreview"
      :svgId="svgId"
    />
  </div>
</template>
<script>
import {
  add,
  coFqueryPage,
  audit,
  queryPageData,
  deviceTree,
} from "@/api/configuration/configurationList";
import CircuitEdit from "@/views/CircuitEdit.vue";
import CircuitPreview from "@/views/CircuitPreview.vue";
import { queryPage } from "@/api/configuration/configuration.js";
export default {
  components: { CircuitEdit, CircuitPreview },
  data() {
    return {
      value: [],

      defaultProps: {
        children: "children",
        label: "name",
      },

      props: {
        multiple: true,
        children: "children",
        label: "name",
        value: "id",
      },
      loading: false,
      params: {},
      svgId: "",
      showCircuitEdit: true,
      showCircuitPreview: true,
      isLoading: false,
      vth: null,
      Engineering: [],
      form: {
        name: "",
        projectIds: [],
        orderBy: 100,
        remark: "",
      },
      rules: {
        name: [{ required: true, message: "请输入项目名称", trigger: "blur" }],
        projectIds: [
          { required: true, message: "请选择工程项目", trigger: "change" },
        ],
        orderBy: [{ required: true, message: "请输入排序", trigger: "blur" }],
      },

      formInline: {
        // deptId: JSON.parse(window.sessionStorage.getItem("Info")).deptId,
        searchValue: "",
        searchBeginTime: "",
        searchEndTime: "",
        orderBy: "",
        pageNum: 1,
        pageSize: 12,
      },
      total: 0,
      title: "新增项目",
      src: require("@/assets/yct.png"),
      dialogVisible: false,
      data: [],
      editoData: [],
    };
  },
  created() {
    this.onSubmitquery();
  },
  mounted() {
    
    deviceTree({}).then((res) => {
      let list = res.data;
      let del = [];
      list.forEach((item, ind) => {
        if (item.children.length == 0) {
          del.unshift(ind);
        } else {
          item.children.forEach((value) => {
            value.children = null;
          });
        }
      });

      for (let i = 0; i < del.length; i++) {
        list.splice(del[i], 1);
      }
      this.Engineering = list;
    });
    this.setHeight()
        window.addEventListener('resize', this.setHeight)
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.setHeight)
    },
    methods: {
        setHeight() {
          this.vth = window.sessionStorage.getItem("appheight") - 100 + "px";
          
        },
    handleNodeClick(data, self, child) {
      console.log(this.$refs.tree.getCheckedNodes());
      let datalist = this.$refs.tree.getCheckedNodes();
      this.form.projectIds = []; //置空
      this.value = [];
      datalist.forEach((item) => {
        this.form.projectIds.push(item.id);
        this.value.push(item.name);
      });
    },
    removetag() {
      this.form.projectIds.splice(0, 1);
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(this.form.projectIds);
      });
    },
    clearall() {
      this.form.projectIds = [];
      this.$nextTick(() => {
        this.$refs.tree.setCheckedNodes([]);
      });
    },

    //每页条数改变时触发 选择一页显示多少行
    handleSizeChange(val) {
      this.formInline.pageSize = val;
      this.onSubmitquery();
    },
    //当前页改变时触发 跳转其他页
    handleCurrentChange(val) {
      this.formInline.pageNum = val;
      this.onSubmitquery();
    },
    //查询
    onSubmitquery() {
      this.isLoading = true;
      coFqueryPage(this.formInline).then((res) => {
        this.data = res.data.records;
        this.total = res.data.total;
        this.isLoading = false;
      });
    },
    //弹窗关闭
    handleClose(done) {
      done();
    },
    //新增
    onSubmitadd() {
      this.dialogVisible = true;

      this.value = [];
      this.title = "新增项目";
      this.form = {
        name: "",
        projectIds: [],
        orderBy: 100,
        remark: "",
      };
      this.$nextTick(() => {
        this.$refs.tree.setCheckedNodes([]);
      });
    },
    //新增确定
    addFn() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          this.loading = true;
          await add(this.form)
            .then((res) => {
              if (res.code == "A0000") {
                this.$message({
                  message: res.message,
                  type: "success",
                });
              }
              this.dialogVisible = false;
              this.loading = false;
              this.onSubmitquery();
            })
            .catch(() => {
              this.loading = false;
            });
        }
      });
    },
    open(id) {
      this.svgId = id;
      this.showCircuitPreview = false;
    },
    onSubmitset() {},
    //项目图跳转
    imgData(e) {
    //   const link = document.createElement("a"); //创建下载a标签
    //   link.target = `_blank`;
    //   link.href = `http://192.168.1.129:3001/zutai/#/?id=${e.id}&&name=decodeURI(${e.name})&&flag=true`;

    //   link.style.display = "none"; //默认隐藏元素
    //   document.body.appendChild(link); // body中添加元素
    //   link.click(); // 执行点击事件

    //   document.body.removeChild(link); //下载完成后移除元素
        window.open(window.location.origin + `/zutai/?id=${e.id}&&name=decodeURI(${e.name})&&flag=true`)
    },
    //过滤触发
    querdata() {},
    // 跳转
    Aclick(e) {
    //   const link = document.createElement("a"); //创建下载a标签
    //   link.target = `_blank`;
    //   link.href = `http://192.168.1.129:3001/zutai/#/?id=${e.id}&&name=decodeURI(${e.name})&&flag=false`;

    //   link.style.display = "none"; //默认隐藏元素
    //   document.body.appendChild(link); // body中添加元素
    //   link.click(); // 执行点击事件

    //   document.body.removeChild(link); //下载完成后移除元素
        window.open(window.location.origin + `/zutai/?id=${e.id}&&name=decodeURI(${e.name})&&flag=false`)
    },
    //设计触发
    shejid(e) {
      // this.$router.push({
      //   path: "/webzuta/2deditor",
      //   name: "CircuitEdit",
      //   params: e,
      // });
      this.params = e;
      this.showCircuitEdit = false;
    },
    // 返回
    exit() {
      this.showCircuitEdit = true;
      this.onSubmitquery();
    },
    //编辑触发
    editd(e) {
      this.dialogVisible = true;

      this.title = "修改项目";
      this.form = {
        name: e.name,
        remark: e.remark,
        projectIds: e.projectIds,
        orderBy: e.orderBy,
        id: e.id,
        fileContent: e.fileContent,
      };
      this.editoData = e;

      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(e.projectIds);
      });
    },
    //编辑确定
    auditFn() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          this.loading = true;
          await audit(this.form)
            .then((res) => {
              if (res.code == "A0000") {
                this.$message({
                  message: res.message,
                  type: "success",
                });
              }
              this.dialogVisible = false;
              this.loading = false;
              this.onSubmitquery();
            })
            .catch(() => {
              this.loading = false;
            });
        }
      });
    },
    //删除触发
    deleted(e) {
      console.log(e);
      this.$confirm("此操作将永久删除该项目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {
            id: e.id,
            name: e.name,
            status: "0",
          };
          audit(data).then((res) => {
            if (res.code == "A0000") {
              this.$message({
                type: "success",
                message: "删除项目成功!",
              });
            }
            this.onSubmitquery();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    test(num) {
      num = num.toString();
      var reg = /^((?!0)\d{1,9})$/;
      if (!num.match(reg)) {
        return false;
      } else {
        return true;
      }
    },
  },
};
</script>
<style lang="less" scoped>
@import url("../../styles/comStyle.less");
.text {
  font-size: 14px;
}
span {
  font-size: 16px;
}
.item {
  margin-bottom: 18px;
}
.image {
  display: block;
  width: 390px;
  height: 220px;
}
.clearfix::before,
.clearfix::after {
  display: table;
  content: "";
}
.clearfix::after {
  clear: both;
}

.box-card {
  width: 100%;
}
.xiaoshou {
  cursor: pointer;
}
.setstyle {
  min-height: 200px;
  padding: 0 !important;
  margin: 0;
  overflow: auto;
  cursor: default !important;
}
::v-deep.el-select-dropdown__wrap {
  max-height: 300px;
}
::v-deep .el-tree {
  padding-top: 15px;
  padding-left: 10px;
  // 不可全选样式
  .el-tree-node {
    .is-leaf + .el-checkbox .el-checkbox__inner {
      display: inline-block;
    }
    .el-checkbox .el-checkbox__inner {
      display: none;
    }
  }
}
::v-deep .el-card__header {
  padding: 13px 20px;
  height: 44px;
}
</style>
<style lang="scss" scoped>
.color {
  color: $themeColor;
}
</style>
