<template>
  <div class="app-container entry-page">
    <el-row :gutter="14" class="entry-layout">
      <el-col :span="7" class="entry-left">
        <div class="grid-content">
          <div class="operate-left">
            <el-tooltip
              class="item"
              effect="dark"
              :content="$t('share.new')"
              placement="top-start"
            >
              <i
                class="el-icon-plus"
                @click="add"
                :class="addIcon ? 'addIcon' : ''"
              ></i>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              :content="$t('share.delete')"
              placement="top-start"
            >
              <i
                class="el-icon-delete"
                @click="remove"
                :class="deleteIcon ? 'deleteIcon' : ''"
              ></i>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              :content="$t('share.export')"
              placement="top-start"
            >
              <i class="el-icon-download" @click="handleExport"></i>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              :content="$t('share.import')"
              placement="top-start"
            >
              <i class="el-icon-upload2" @click="handleUpload"></i>
            </el-tooltip>
          </div>
          <el-input
            :placeholder="$t('entry.SearchForDeviceName')"
            v-model="queryParams"
            style="margin-bottom: 10px"
          ></el-input>
          <div class="treeBox">
            <el-tree
              :data="treeData"
              :props="defaultProps"
              @node-click="handleNodeClick"
              ref="tree"
              default-expand-all
            >
              <span slot-scope="{ node, data }" class="slot-node">
                <template>
                  <i
                    class="el-icon-box"
                    v-if="data.areaName"
                    style="margin-right: 5px"
                  ></i>
                  <i
                    class="el-icon-takeaway-box"
                    v-if="data.powerMainEquFlag == 'Yes'"
                    style="margin-right: 5px; color: #409eff"
                  ></i>
                  <i
                    class="el-icon-set-up"
                    v-if="data.powerMainEquFlag == 'No'"
                    style="margin-right: 5px; color: #a9c52b"
                  ></i>
                  <span>{{ node.label }}</span>
                </template>
              </span>
            </el-tree>
          </div>
        </div>
      </el-col>
      <el-col :span="17" class="entry-right">
        <el-empty
          :description="$t('entry.RightSidePrompt')"
          v-if="!show"
        ></el-empty>
        <div class="grid-content-right" v-if="show">
          <div class="titleName">{{ titleName }}</div>
          <el-form
            ref="ruleForm"
            :model="form"
            label-width="200px"
            :rules="rules"
          >
            <el-form-item :label="$t('entry.EquipmentName')" prop="deviceName">
              <el-input
                v-model="form.deviceName"
                :placeholder="
                  $t('share.PleaseEnter') + $t('entry.EquipmentName')
                "
              ></el-input>
            </el-form-item>
            <el-form-item :label="$t('entry.DeviceType')" prop="devicetypeId">
              <el-select
                v-model="form.devicetypeId"
                :placeholder="$t('share.PleaseEnter') + $t('entry.DeviceType')"
                :disabled="disabled"
              >
                <el-option
                  :label="item.devicetypeName"
                  :value="item.devicetypeId"
                  v-for="item in deviceTypeData"
                  :key="item.devicetypeId"
                ></el-option>
                <!-- deviceTypeData -->
              </el-select>
            </el-form-item>
            <el-form-item
              :label="$t('entry.EquipmentNumber')"
              prop="deviceCode"
            >
              <el-input
                v-model="form.deviceCode"
                :placeholder="
                  $t('share.PleaseEnter') + $t('entry.EquipmentNumber')
                "
              ></el-input>
              <span class="serial-number">{{
                $t("entry.EquipmentNumberPrompt")
              }}</span>
            </el-form-item>
            <el-form-item :label="$t('entry.DisplaySorting')" prop="orderNum">
              <el-input-number
                v-model="form.orderNum"
                controls-position="right"
                :min="0"
              ></el-input-number>
            </el-form-item>
            <el-form-item :label="$t('entry.physicalObject')">
              <el-input
                v-model="form.phyassetId"
                :placeholder="
                  $t('share.PleaseEnter') + $t('entry.physicalObject')
                "
              ></el-input>
            </el-form-item>
            <el-form-item :label="$t('entry.MonitoringIndexNumber')">
              <el-input
                v-model="form.monitorIndexNo"
                :placeholder="
                  $t('share.PleaseEnter') + $t('entry.MonitoringIndexNumber')
                "
              ></el-input>
            </el-form-item>
            <el-form-item :label="$t('entry.EquipmentModel')">
              <el-input
                v-model="form.deviceModel"
                :placeholder="
                  $t('share.PleaseEnter') + $t('entry.EquipmentModel')
                "
              ></el-input>
            </el-form-item>
            <el-form-item :label="$t('entry.EquipmentManufacturer')">
              <el-input
                v-model="form.manufacturer"
                :placeholder="
                  $t('share.PleaseEnter') + $t('entry.EquipmentManufacturer')
                "
              ></el-input>
            </el-form-item>

            <el-form-item :label="'x' + $t('entry.coordinate')">
              <el-input-number
                v-model="form.positionX"
                controls-position="right"
                :min="-20"
                :max="20"
                :step="0.1"
              ></el-input-number>
              <span class="number-title"
                >({{
                  $t("entry.suggestion") + " " + $t("entry.minimumValue")
                }}-20 {{ $t("entry.minimumValue") }}20 )</span
              >
            </el-form-item>
            <!-- 建议最小值-20，最大值20 -->
            <el-form-item :label="'y' + $t('entry.coordinate')">
              <el-input-number
                v-model="form.positionY"
                controls-position="right"
                :min="66"
                :step="0.1"
              ></el-input-number>
              <span class="number-title">({{ $t("entry.suggestion") }}66)</span>
            </el-form-item>

            <el-form-item :label="'z' + $t('entry.coordinate')">
              <el-input-number
                v-model="form.positionZ"
                controls-position="right"
                :min="-6"
                :max="20"
                :step="0.1"
              ></el-input-number>
              <span class="number-title"
                >({{
                  $t("entry.suggestion") + " " + $t("entry.minimumValue")
                }}-6 {{ $t("entry.minimumValue") }}20 )</span
              >
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="onSubmit">{{
                $t("entry.save")
              }}</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
    <!-- <el-dialog
      title="导入文件"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
    <file-upload ref="fileUpload" :file-type="['xlsx','xls']" :fileSize="100"></file-upload>
  </el-dialog> -->
    <el-dialog
      title="生产设备导入"
      v-model="upload.open"
      width="400px"
      append-to-body
      :visible="upload.open"
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls, .txt, .xml"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template> 

<script >
import { getToken } from "@/utils/auth";
import {
  treeAreaDeviceSelect,
  devicetypeList,
  deviceQuery,
  insertMainDeviceAndCommByDeviceType,
  deviceRemove,
  deviceEdit,
} from "@/api/equipment/entry";
export default {
  name: "entry",
  data() {
    return {
      queryParams: "",
      treeData: [],
      defaultProps: {
        children: "children",
        // label: "areaName",
        label: function (data) {
          return data.areaName || data.deviceName;
        },
      },
      titleName: "",
      form: {
        orderNum: 0,
        positionX: 0,
        positionY: 66,
        positionZ: 0,
        handerType: 0,
        boolAdd: 1,
        deviceId: "",
      },
      show: false,
      deleteIcon: true,
      addIcon: true,
      deviceTypeData: [],
      deviceId: "",
      rules: {
        deviceName: [
          {
            required: true,
            message:
              this.$t("share.PleaseEnter") + this.$t("enrty.EquipmentName"),
            trigger: "blur",
          },
        ],
        devicetypeId: [
          {
            required: true,
            message:
              this.$t("share.PleaseChoose") + this.$t("enrty.DeviceType"),
            trigger: "change",
          },
        ],
        deviceCode: [
          {
            required: true,
            message:
              this.$t("share.PleaseEnter") + this.$t("enrty.EquipmentNumber"),
            trigger: "blur",
          },
        ],
        orderNum: [
          {
            required: true,
            message: "请输入排序",
            trigger: "blur",
          },
        ],
      },
      type: 0,
      disabled: false,
      formObj: {},
      dialogVisible: false,
      upload: {
        open: false,
        url: process.env.VUE_APP_BASE_API + "/basedata/prodevmnt/device/importData",
         headers: { Authorization: "Bearer " + getToken() },
        updateSupport: 0,
        isUploading: false,
      },
    };
  },
  // watch: {
  //   deviceTypeData(newVal) {
  //     if (newVal.length > 0 && this.form.deviceId) {
  //       this.$nextTick(() => {
  //         // 强制触发 select 更新
  //         this.form.devicetypeId = this.form.devicetypeId;
  //       });
  //     }
  //   },
  // },
  mounted() {
    this.init();
    devicetypeList().then((res) => {
      console.log(res, 111);
      if (res.code == 200) {
        let arr = res.data.filter((item) => item.devicetypeName !== "设备类型");
        this.deviceTypeData = arr;
      }
    });
  },
  methods: {
    init() {
      treeAreaDeviceSelect().then((res) => {
        if (res.code == 200) {
          this.treeData = res.data;
        }
      });
    },
    handleNodeClick(data, e) {
      this.formObj = data;
      this.deviceId = data.deviceId;
      this.titleName = data.areaName || data.deviceName;
      this.disabled = true;
      (this.form.parentName = data.areaName), (this.form.areaId = data.areaId);

      if (data.areaName) {
        this.show = false;
        this.deleteIcon = true;
        this.addIcon = false;
      } else if (data.deviceName) {
        this.show = true;
        this.titleName = this.$t("share.edit") + " " + data.deviceName;
        this.deleteIcon = false;
        this.addIcon = true;
        deviceQuery(data.deviceId).then((res) => {
          console.log(res, 1111);
          if (res.code == 200) {
            this.type = 1;
            this.form = res.data;
            this.form.devicetypeId = Number(this.form.devicetypeId);
          }
        });
      }
    },
    add() {
      this.form = {};
      this.show = true;
      this.type = 0;
      this.disabled = false;
    },
    remove() {
      this.$confirm("是否确定删除", "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deviceRemove(this.deviceId).then((res) => {
          console.log(res, 1111);
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功",
            });
            this.init();
          }
        });
      });
    },
    onSubmit() {
      this.form.areaId = this.formObj.areaId;
      this.form.areaName = this.areaName;
      this.$refs["ruleForm"].validate((v) => {
        if (v) {
          if (this.type == 0) {
            insertMainDeviceAndCommByDeviceType(this.form).then((res) => {
              if (res.code == 200) {
                this.$message({
                  type: "success",
                  message: "新增成功",
                });
                this.form = {};
                this.form = {
                  orderNum: 0,
                  positionX: 0,
                  positionY: 66,
                  positionZ: 0,
                  handerType: 0,
                  boolAdd: 1,
                  deviceId: "",
                };
                this.init();
              }
            });
          } else {
            // this.form.handerType=2;
            // this.form.updateTime=null;
            deviceEdit(this.form).then((res) => {
              if (res.code == 200) {
                this.$message({
                  type: "success",
                  message: "编辑成功",
                });
                this.form = {};
                this.form = {
                  orderNum: 0,
                  positionX: 0,
                  positionY: 66,
                  positionZ: 0,
                  handerType: 0,
                  boolAdd: 1,
                };
                this.init();
              }
            });
          }
          this.show = false;
        }
      });
    },
    // 导出
    handleExport() {
      this.download(
        "/basedata/prodevmnt/device/export",
        {
          ...this.queryParams,
        },
        `entry_${new Date().getTime()}.xlsx`
      );
    },
    // 导入
    handleUpload() {
      // this.dialogVisible = true;
      this.upload.open = true;
    },
    handleClose() {
      this.upload.open = false;
    },
    /**文件上传中处理 */
    handleFileUploadProgress() {
      this.upload.isUploading = true;
    },
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs["uploadRef"].handleRemove(file);
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.init();
    },
    submitFileForm(){
      this.$refs["uploadRef"].submit();
    }
  },
};
</script>

<style lang="scss" scoped>
.entry-page {
  overflow: hidden;
}

.entry-layout {
  flex: 1 1 auto !important;
  min-height: 0;
  height: 100%;
  display: flex;
  overflow: hidden;
}

.entry-left,
.entry-right {
  height: 100%;
  min-height: 0;
  overflow: hidden;
}

.entry-left {
  display: flex;
  flex-direction: column;
  padding: 12px !important;
  background: #0f124a;
  border: 1px solid #0b2567;
}

.entry-right {
  display: flex;
  flex-direction: column;
  padding-left: 14px !important;
  padding-right: 0 !important;
}

.grid-content {
  height: 100%;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.operate-left {
  flex: 0 0 auto;
  height: 30px;
  display: flex;
  justify-content: flex-end;
  i {
    font-size: 20px;
    margin-left: 5px;
    cursor: pointer;
  }
}
::v-deep .el-tree-node:focus > .el-tree-node__content {
  color: #4a9de7 !important;
  // color: #fff !important;
}
::v-deep .el-tree-node__content {
  height: 34px !important;
}
/*节点失焦时的背景颜色*/
//   .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content{
//     background-color: #4a9de7 !important;
//     color: #fff !important;
//   }
.grid-content-right {
  flex: 1 1 auto;
  height: 100%;
  min-height: 0;
  overflow-y: auto;
  padding: 0 10%;
  background: #0f124a;
  border: 1px solid #0b2567;
}

.entry-right ::v-deep .el-empty {
  flex: 1 1 auto;
  height: 100%;
  background: #0f124a;
  border: 1px solid #0b2567;
}
.titleName {
  font-size: 26px;
  padding: 10px;
}
.number-title {
  margin-left: 10px;
}
.serial-number {
  color: #999;
  font-size: 12px;
  margin-bottom: 30px;
  margin-top: 20px;
}
.deleteIcon,
.addIcon {
  color: #dddddd;
  cursor: not-allowed;
}
.treeBox {
  flex: 1 1 auto;
  min-height: 0;
  height: auto;
  overflow-y: auto;
  overflow-x: hidden;
}
</style>
