<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!--机构数据-->
      <el-col :span="4" :xs="24">
        <org-tree
          v-model="queryParams.orgId"
          @defaultKey="getDefaultKey"
          @defaultOrg="getDefaultOrg"
          @checkChange="checkChange"
          @click="clickTreeNode"
        ></org-tree>
      </el-col>
      <el-col :span="20" :xs="24">
        <div class="main-right-box">
          <div class="main-search-box">
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
              <el-form-item label="设备名称" prop="deviceName">
                <el-input clearable v-model="queryParams.deviceName" placeholder="请输入关键字" maxlength="50"
                          @keyup.enter.native="handleQuery"/>
              </el-form-item>
              <el-form-item label="资产分类" prop="assetType" label-width="80">
                <el-select style="width: 100%;" v-model="queryParams.assetType" placeholder="请选择资产分类"
                           @change="queryAssetSelectChange" @clear="clearAsset" clearable>
                  <el-option v-for="item in getAssetDict('AssetDeviceType',-1)" :key="item.id" :label="item.name"
                             :value="item.id"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="设备分类" prop="deviceType" label-width="80">
                <el-select style="width: 100%;" clearable v-model="queryParams.deviceType" placeholder="请选择设备分类">
                  <el-option v-for="item in assetChildrenDictList" :key="item.id" :label="item.name"
                             :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <el-row :gutter="10">
              <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-col>

              <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                           v-hasPermi="['system:device:add']">新增设备
                </el-button>
              </el-col>

              <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-upload" size="mini" @click="handleImport"
                           v-hasPermi="['system:device:importData']">导入设备
                </el-button>
              </el-col>

              <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-download" size="mini" @click="handleOut"
                           v-hasPermi="['system:device:export']">导出模版
                </el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </div>
          <el-table border height="646" size="small" v-loading="loading" :data="deviceList"
                    @selection-change="handleSelectionChange">
            <el-table-column label="序号" align="center" min-width="50">
              <template v-slot:default="scope">
                <span v-text="getPageIndex(scope.$index)"> </span>
              </template>
            </el-table-column>
            <el-table-column label="地区" align="left" prop="affiliatedArea"/>
            <el-table-column label="行社" align="left" prop="affiliatedBank"/>
            <el-table-column label="所属机构" align="left" prop="orgName"/>
            <el-table-column label="资产分类" align="center" key="assetType" prop="assetType"/>
            <el-table-column label="设备分类" align="center" key="deviceType" prop="deviceType"/>
            <el-table-column label="设备名称" align="center" prop="deviceName"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit-outline" @click="handleUpdate(scope.row)"
                           v-hasPermi="['system:device:edit']">编辑
                </el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                           v-hasPermi="['system:device:remove']">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                      @pagination="getList"/>
        </div>
      </el-col>
    </el-row>

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <DialogCom
      :title="title"
      :visible.sync="open"
      width="850px"
      @close="closeHandler"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">

        <el-row>
          <el-col :span="24">
            <el-form-item label="所属机构" prop="orgId">
              <tree-select
                v-model="form.orgId"
                :options="deptOptions"
                :show-count="true"
                :normalizer="tenantIdnormalizer"
                :props="{ checkStrictly: true, label: 'name' }"
                placeholder="请选择所属机构"
                @select="changeSelect"
                clearValueText="清除"
                :noChildrenText="''"
                noOptionsText="没有数据"
                noResultsText="没有搜索结果"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="资产编号" prop="assetNo">
              <el-input
                v-model="form.assetNo"
                placeholder="请输入设备名称"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input
                v-model="form.deviceName"
                placeholder="请输入设备名称"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="资产分类" prop="assetType">
              <el-select style="width: 100%" v-model="form.assetType" :popper-append-to-body="false"
                         placeholder="请选择资产分类" @change="assetSelectChange">
                <el-option v-for="item in getAssetDict('AssetDeviceType',-1)" :key="item.id" :label="item.name"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备分类" prop="deviceType">
              <el-select style="width: 100%" :popper-append-to-body="false" clearable v-model="form.deviceType"
                         placeholder="请选择设备分类">
                <el-option v-for="item in assetChildrenDictList" :key="item.id" :label="item.name"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="12">
            <el-form-item label="设备品牌" prop="deviceBrand">
              <el-select style="width: 100%" v-model="form.deviceBrand" placeholder="请选择设备品牌"
                         @change="brandSelectChange">
                <el-option v-for="item in getAssetDict('BrandModelType',-1)" :key="item.id" :label="item.name"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备型号" prop="deviceModel">
              <el-select @change="brandSelectChange1" style="width: 100%" v-model="form.deviceModel" placeholder="请选择设备型号">
                <el-option v-for="item in brandChildrenDictList" :key="item.id" :label="item.name"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="采购日期" prop="purchasingTime">
              <el-date-picker style="width: 100%" clearable v-model="form.purchasingTime" type="date"
                              value-format="yyyy-MM-dd" placeholder="请选择采购日期">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="安装位置" prop="address">
              <el-input v-model="form.address" placeholder="请输入安装位置" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="消防类有效期" prop="checkTime">
              <el-date-picker style="width: 100%" clearable v-model="form.checkTime" type="date"
                              value-format="yyyy-MM-dd" placeholder="请选择消防类有效期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保修期限" prop="maintenanceTerm">
              <el-date-picker style="width: 100%" clearable v-model="form.maintenanceTerm" type="date"
                              value-format="yyyy-MM-dd" placeholder="请选择保修期限">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="投产时间" prop="useTime">
              <el-date-picker style="width: 100%" clearable v-model="form.useTime" type="date"
                              value-format="yyyy-MM-dd" placeholder="请选择投产时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产状态" prop="deviceStatus">
              <el-select
                v-model="form.deviceStatus"
                clearable
                placeholder="请选择资产状态"
                style="width: 100%;">
                <el-option
                  v-for="dict in dict.type.asset_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="`${dict.value}`"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </DialogCom>

    <!-- 设备导入对话框 -->
    <DialogCom
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        :before-upload="beforeUpload"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </DialogCom>
  </div>
</template>

<script>
import {getToken} from "@/utils/auth";
import orgDropDown from "../../../components/orgTree/orgDropDown.vue";
import OrgTree from "@/components/orgTree";
import tableList from "@/mixins/tableList";
import {deptTreeSelect} from "@/api/system/public";
import {getDeviceType} from "@/api/system/dict/data";
import {
  addDevice,
  delDevice,
  getDevice, getDictList,
  getDictTree, getDictTreeByParentId,
  getHostByOrgId,
  listDevice,
  updateDevice,
} from "@/api/system/device";
import request from "@/utils/request";

export default {
  /** 引入基础minxins*/
  mixins: [tableList],
  dicts: ["sys_asset_type", "sys_device_type",'asset_status'],
  name: "Device",
  components: {OrgTree, orgDropDown},
  data() {
    return {
      checkList: [],
      roleOptions: [],
      defaultKeys: [],
      //是否关联下级
      checked: false,
      defaultProps: {
        children: "children",
        label: "name",
      },
      rules: {
        assetNo: [{required: true, message: "请输入资产编号", trigger: "change"}],
        deviceName: [{required: true, message: "请输入设备名称", trigger: "change"}],
        orgId: [{required: true, message: "请选择所属机构", trigger: "blur"}],
        assetType: [{required: true, message: '请选择资产类别', trigger: 'change'}],
      /*  hostId: [{required: true, message: '请选择主机', trigger: 'change'}],
        channel: [{required: true, message: '请输入通道号', trigger: 'change'}],*/
        deviceType: [{required: true, message: "请选择设备分类", trigger: "change"}],
        deviceStatus: [{required: true, message: "请选择资产状态", trigger: "blur"}],
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个停用
      single: true,
      //搜索tree
      deptName: null,

      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      inparm: 0,
      // 【请填写功能名称】表格数据
      deviceList: [],
      devices: null,
      searchDevices: null,
      //主机集合
      hostList: [],
      dictionaryTreeList: [],
      dictionaryList: [],
      assetChildrenDictList: [],
      brandChildrenDictList: [],
      deviceType: 0,

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      dept: {
        id: null,
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orgId: null,
        orgName: null,
        deviceName: null,
        assetType: null,
        deviceType: null,
        deviceBrand: null,
        checkTime: null,
        maintenanceTerm: null,
        hostId: null,
        channel: null,
        checkSub: true,
      },
      // 设备导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否停用上传
        isUploading: false,

        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url:
          process.env.NODE_ENV === "development"
            ? process.env.VUE_APP_BASE_API + "/system/device/importData"
            : window.origin + "/system/device/importData",
      },
      // 表单参数
      form: {
        orgId: null,
        deviceName: null,
        assetType: null,
        deviceType: null,
        deviceBrand: null,
        deviceModel: null,
        checkTime: null,
        maintenanceTerm: null,
        hostId: null,
        channel: null,
        address: null,
        definition: null,
        inBook: 0,
        purchasingTime: null,
        assetNo: null,
        deviceStatus: null,
      },
      // 表单校验

      //修改新增中的机构树
      deptOptions: [],
      selectOrgId: null,
    };
  },
  created() {
    this.getDeptTree();
    //this.getList();


  },
  mounted() {
    this.initDictionaryTreeList();
    this.initDictionaryList();
  },


  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },

  methods: {
    onOrgSelect(node) {
      this.form.orgPath = node.path;
      this.form.orgName = node.name;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    handleImport() {
      this.upload.title = "设备导入";
      this.upload.open = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        {dangerouslyUseHTMLString: true}
      );
      this.getList();
    },
    beforeUpload(file) {
      // 返回 false 可以阻止文件上传
      // 创建 FormData 对象

      let config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        responseType: 'blob'
      }
      const formData = new FormData();
      // 添加文件到 FormData
      formData.append("file", file);
      request.post(this.upload.url, formData, config)
        .then((response) => {
          // 在接收到后端响应时执行的逻辑
          // console.log(response,"response");
          this.upload.open = false;
          this.upload.isUploading = false;
          this.$refs.upload.clearFiles();
          if (response&&response.size >0) {
            this.$alert(
              "导入失败,请根据返回的Excel检查文件内容"
            );
            const blob = new Blob([response],
              {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})  //你需要的类型 转化为blob对象
            const url = window.URL.createObjectURL(blob)         //将对象转化为链接
            let a = document.createElement('a')
            // 下载链接
            a.href = url
            a.download = '设备导入结果.xlsx'
            document.body.appendChild(a)
            // 点击a标签，进行下载
            a.click()
            // 移除元素
            document.body.removeChild(a)
          } else {
            this.$alert(
              "导入成功!"
            );
          }
          this.getList();
        })
        .catch((error) => {
          // 在请求失败时执行的逻辑
          // console.log(error,"error");
        });
      return false;
    },
    getDefaultOrg(org) {
      this.orgName = org.name;
    },
    getDefaultKey(key) {
      this.queryParams.orgId = key;
      this.getList();
    },
    //单选框状态改变
    checkChange(state) {
      this.queryParams.checkSub = state;
      this.handleQuery();
    },
    getPageIndex($index) {
      //表格序号
      return (
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize + $index + 1
      );
    },
    /** 下穿状态改变*/
    changeCheckBox() {
      this.getList();
    },

    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    /** 查询机构树数据 */

    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.orgId = data.id;
      this.selectOrgId = data.id;
      this.changeSelect(data);
      this.handleQuery();
    },
    changeSelect(val) {
      if (!val || !val.id) return;
      getHostByOrgId(val).then((response) => {
        this.form.hostId = null;
        this.hostList = response.data;
      });
    },

    handleOut() {
      this.download(
        "system/device/downInChargeOfTemplate",
        {
          ...this.queryParams,
        },
        `${
          this.orgName + "-设备导入模版-" + this.formatTime(new Date(), "YYYYMMhh")
        }.xlsx`
      );
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then((response) => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
        this.defaultKeys.push(response.data[0].id);
        this.queryParams.orgId = response.data[0].id;
        this.selectOrgId = response.data[0].id;

        this.handleQuery();
      });
    },
    // 节点单击事件
    clickTreeNode(data) {
      this.queryParams.orgId = data.id;
      this.handleQuery();
    },
    /** treeSelect组件自定义数据*/
    tenantIdnormalizer(node, instanceId) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.shortName,
        children: node.children,
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    closeHandler() {
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orgId: null,
        orgName: null,
        assetNo: null,
        deviceName: null,
        assetType: null,
        deviceType: null,
        deviceBrand: null,
        deviceModel: null,
        purchasingTime: null,
        address: null,
        checkTime: null,
        maintenanceTerm: null,
        useTime: null,
        deviceStatus: null,
        hostId: null,
        channel: null,
        definition: "1",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.devices = null;
      this.searchDevices = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.names = selection.map((item) => item.deviceName);
      this.single = selection.length !== 1;
    },
    /** 新增按钮操作 */
    handleAdd(val) {
      this.open = true;
      this.title = "新增设备信息";
      this.form.orgId = this.selectOrgId;
      this.dept.id = this.selectOrgId;
      this.changeSelect(this.dept);
      this.devices = null;
    },
    //获取字典数据
    initDictionaryTreeList() {
      getDictTree().then((response) => {
        this.dictionaryTreeList = response.data;
      });
    },
    initDictionaryList() {
      getDictList().then((response) => {
        this.dictionaryList = response.data;
      });
    },
    //从基础数据中获取资产分类
    getAssetDict(type, parentId) {
      let arr = []
      this.dictionaryTreeList.filter(item => item.type === type && item.parentId == parentId).map(item => {
        arr.push(item);
      });
      return arr;
    },
    //从基础数据中获取资产分类
    getAssetDictDetailInfo(id) {
      let arr = []
      this.dictionaryList.filter(item => item.id == id).map(item => {
        arr.push(item);
      });
      return arr;
    },
    //新增设备时
    assetSelectChange(val) {
      if (!val) return;
      this.form.deviceType = null;
      getDictTreeByParentId(val).then((response) => {
        this.assetChildrenDictList = response.data;
        console.log('获取设备分类数据', this.assetChildrenDictList);
      });
    },
    //查询时
    queryAssetSelectChange(val) {
      if (!val) return;
      this.queryParams.deviceType = null;
      getDictTreeByParentId(val).then((response) => {
        this.assetChildrenDictList = response.data;
        console.log('获取设备分类数据', this.assetChildrenDictList);
      });
    },
    brandSelectChange(val) {
      if (!val) return;
      this.form.deviceModel = null;
      getDictTreeByParentId(val).then((response) => {
        this.brandChildrenDictList = response.data;
        console.log('获取设备型号数据', this.brandChildrenDictList);
      });
    },
    brandSelectChange1(val) {
      console.log(this.form.deviceModel,val)
    },
    clearAsset() {
      this.queryParams.deviceType = null;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getDevice(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "编辑设备信息";
        console.log(this.form.assetType,this.form.deviceBrand)
        getDictTreeByParentId(this.form.assetType).then((response) => {
          this.assetChildrenDictList = response.data;
        });
        getDictTreeByParentId(this.form.deviceBrand).then((response) => {
          this.brandChildrenDictList = response.data;
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateDevice(this.form).then((response) => {
              this.$modal.msgSuccess("处理成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDevice(this.form).then((response) => {
              this.$modal.msgSuccess("处理成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names = row.deviceName || this.names;
      this.$modal
        .confirm('是否确认删除名称为"' + names + '"的数据项？')
        .then(function () {
          return delDevice(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
        });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/device/export",
        {
          ...this.queryParams,
        },
        `device_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss">
//.vue-treeselect--has-value .vue-treeselect__input {
//   line-height: 100%;
//   vertical-align: middle;
//}
</style>
