<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryRef"
      :inline="true"
      :model="queryParams"
      :size="productId ? 'small' : 'default'"
      label-width="68px"
    >
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          clearable
          placeholder="请输入设备名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item v-if="!productId" label="产品" prop="productId">
        <el-select
          v-model="queryParams.productId"
          :remote-method="getProductOptions"
          clearable
          filterable
          placeholder="请选择产品"
          remote
          remote-show-suffix
        >
          <el-option
            v-for="item in productOptions"
            :key="item.productId"
            :label="item.productName"
            :value="item.productId"
          />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="设备状态" prop="status">-->
      <!--        <el-switch-->
      <!--          v-model="queryParams.status"-->
      <!--          :active-value="1"-->
      <!--          :inactive-value="0"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="用户ID" prop="userId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.userId"-->
      <!--          clearable-->
      <!--          placeholder="请输入用户ID"-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="租户ID" prop="tenantId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.tenantId"-->
      <!--          clearable-->
      <!--          placeholder="请输入租户ID"-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="设备编号" prop="serialNumber">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.serialNumber"-->
      <!--          clearable-->
      <!--          placeholder="请输入设备编号"-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="固件版本" prop="firmwareVersion">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.firmwareVersion"-->
      <!--          clearable-->
      <!--          placeholder="请输入固件版本"-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="信号强度" prop="rssi">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.rssi"-->
      <!--          clearable-->
      <!--          placeholder="请输入信号强度"-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="是否启用设备影子(0禁用 1启用)" prop="isShadow">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.isShadow"-->
      <!--          clearable-->
      <!--          placeholder="请输入是否启用设备影子(0禁用 1启用)"-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="定位方式(1ip自动定位 2设备定位 3自定义)" prop="locationWay">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.locationWay"-->
      <!--          clearable-->
      <!--          placeholder="请输入定位方式(1ip自动定位 2设备定位 3自定义)"-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="设备所在地址" prop="networkAddress">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.networkAddress"-->
      <!--          clearable-->
      <!--          placeholder="请输入设备所在地址"-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="设备入网IP" prop="networkIp">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.networkIp"-->
      <!--          clearable-->
      <!--          placeholder="请输入设备入网IP"-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="设备经度" prop="longitude">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.longitude"-->
      <!--          clearable-->
      <!--          placeholder="请输入设备经度"-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="设备纬度" prop="latitude">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.latitude"-->
      <!--          clearable-->
      <!--          placeholder="请输入设备纬度"-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="激活时间" prop="activeTime">-->
      <!--        <el-date-picker v-model="queryParams.activeTime"-->
      <!--                        clearable-->
      <!--                        placeholder="请选择激活时间"-->
      <!--                        type="date"-->
      <!--                        value-format="YYYY-MM-DD">-->
      <!--        </el-date-picker>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="图片地址" prop="imgUrl">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.imgUrl"-->
      <!--          clearable-->
      <!--          placeholder="请输入图片地址"-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button icon="Search" type="primary" @click="handleQuery"
          >搜索
        </el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['iot:device:add']"
          :size="productId ? 'small' : 'default'"
          icon="Plus"
          plain
          type="primary"
          @click="handleAdd"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['iot:device:edit']"
          :disabled="single"
          :size="productId ? 'small' : 'default'"
          icon="Edit"
          plain
          type="success"
          @click="handleUpdate"
          >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['iot:device:remove']"
          :disabled="multiple"
          :size="productId ? 'small' : 'default'"
          icon="Delete"
          plain
          type="danger"
          @click="handleDelete"
          >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['iot:device:export']"
          :size="productId ? 'small' : 'default'"
          icon="Download"
          plain
          type="warning"
          @click="handleExport"
          >导出
        </el-button>
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="deviceList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="55" />
      <!--      <el-table-column align="center" label="设备ID" prop="deviceId" />-->
      <el-table-column align="center" label="设备名称" prop="deviceName" />
      <el-table-column align="center" label="设备编号" prop="serialNumber" />
      <el-table-column align="center" label="产品" prop="productName" />
      <!--      <el-table-column align="center" label="用户" prop="userName" />-->
      <!--      <el-table-column align="center" label="租户" prop="tenantName" />-->
      <el-table-column align="center" label="固件版本" prop="firmwareVersion" />
      <el-table-column align="center" label="设备状态" prop="status">
        <template #default="{ row }">
          <dict-tag
            :options="deviceStatusMap"
            :value="[row.status]"
            effect="dark"
            size="small"
          />
        </template>
      </el-table-column>
      <!--      <el-table-column align="center" label="信号强度" prop="rssi" />-->
      <el-table-column align="center" label="是否启用设备影子" prop="isShadow">
        <template #default="{ row }">
          <dict-tag
            :options="isShadowDict"
            :value="[row.isShadow]"
            size="small"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="定位方式" prop="locationWay">
        <template #default="{ row }">
          {{ locationWayMap.find((el) => el.value === row.locationWay)?.label }}
        </template>
      </el-table-column>
      <!--      <el-table-column align="center" label="物模型值" prop="thingsModelValue" />-->
      <!--      <el-table-column align="center" label="设备所在地址" prop="networkAddress" />-->
      <!--      <el-table-column align="center" label="设备入网IP" prop="networkIp" />-->
      <!--      <el-table-column align="center" label="设备经度" prop="longitude" />-->
      <!--      <el-table-column align="center" label="设备纬度" prop="latitude" />-->
      <el-table-column
        align="center"
        label="激活时间"
        prop="activeTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.activeTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column align="center" label="设备摘要" prop="summary" />-->
      <!--      <el-table-column align="center" label="图片地址" prop="imgUrl" />-->
      <el-table-column align="center" label="分组名称" prop="groupName">
        <template #default="{ row }">
          <el-tag v-if="row.groupName">
            {{ row.groupName }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        class-name="small-padding fixed-width"
        label="操作"
      >
        <template #default="scope">
          <!--          <el-button-->
          <!--            v-hasPermi="['iot:device:edit']"-->
          <!--            icon="Edit"-->
          <!--            link-->
          <!--            type="primary"-->
          <!--            @click="handleUpdate(scope.row)"-->
          <!--          >-->
          <!--            修改-->
          <!--          </el-button>-->
          <el-button
            v-hasPermi="['iot:device:edit']"
            icon="Edit"
            link
            type="primary"
            @click="handleDetail(scope.row)"
          >
            修改
          </el-button>
          <el-button
            v-hasPermi="['iot:device:remove']"
            icon="Delete"
            link
            type="primary"
            @click="handleDelete(scope.row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改设备对话框 -->
    <el-dialog v-model="open" :title="title" append-to-body width="800px">
      <el-form
        ref="deviceRef"
        :model="form"
        :rules="rules"
        label-position="left"
        label-width="140px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input
                v-model="form.deviceName"
                placeholder="请输入设备名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品" prop="productId">
              <!--              <el-input v-model="form.productId" placeholder="请输入产品ID" />-->
              <el-select
                v-model="form.productId"
                :disabled="productId"
                :remote-method="getProductOptions"
                clearable
                filterable
                placeholder="请选择产品"
                remote
                remote-show-suffix
              >
                <el-option
                  v-for="item in productOptions"
                  :key="item.productId"
                  :label="item.productName"
                  :value="item.productId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <!--            <el-form-item label="用户ID" prop="userId">-->
            <!--              &lt;!&ndash;              <el-input v-model="form.userId" placeholder="请输入用户ID" />&ndash;&gt;-->
            <!--              <el-tag-->
            <!--                v-if="form.userId"-->
            <!--                closable-->
            <!--                @close="form.userId = undefined"-->
            <!--              >{{ form.userName }}-->
            <!--              </el-tag>-->
            <!--              <el-button-->
            <!--                v-else-->
            <!--                icon="pointer"-->
            <!--                size="small"-->
            <!--                type="primary"-->
            <!--                @click="userOpen=true"-->
            <!--              >选择-->
            <!--              </el-button>-->
            <!--            </el-form-item>-->
          </el-col>
          <el-col :span="12">
            <!--            <el-form-item label="租户ID" prop="tenantId">-->
            <!--              <el-input v-model="form.tenantId" placeholder="请输入租户ID" />-->
            <!--            </el-form-item>-->
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备编号" prop="serialNumber">
              <el-input
                v-model="form.serialNumber"
                placeholder="请输入设备编号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="固件版本" prop="firmwareVersion">
              <el-input
                v-model="form.firmwareVersion"
                placeholder="请输入固件版本"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="激活时间" prop="activeTime">
              <el-date-picker
                v-model="form.activeTime"
                clearable
                placeholder="请选择激活时间"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="信号强度" prop="rssi">-->
          <!--              <el-input v-model="form.rssi" placeholder="请输入信号强度" />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="是否启用设备影子" prop="isShadow">
              <el-switch
                v-model="form.isShadow"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="定位方式" prop="locationWay">
              <el-select
                v-model="form.locationWay"
                placeholder="请输入定位方式"
              >
                <el-option :value="1" label="ip自动定位" />
                <el-option :value="2" label="设备定位" />
                <el-option :value="3" label="自定义" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备所在地址" prop="networkAddress">
              <el-input
                v-model="form.networkAddress"
                placeholder="请输入设备所在地址"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备经度" prop="longitude">
              <el-input v-model="form.longitude" placeholder="请输入设备经度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备纬度" prop="latitude">
              <el-input v-model="form.latitude" placeholder="请输入设备纬度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <map-select
            :lat="form.latitude"
            :lng="form.longitude"
            :lnglat="[form.longitude, form.latitude]"
            @selected="handleMapSelected"
          />
        </el-form-item>
        <!--        <div id="map-container"-->
        <!--             style="width: calc(100% - 140px);height: 300px;margin-left: 140px;margin-bottom: 18px"></div>-->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备入网IP" prop="networkIp">
              <el-input
                v-model="form.networkIp"
                placeholder="请输入设备入网IP"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="图片地址" prop="imgUrl">
          <!--          <el-input v-model="form.imgUrl" placeholder="请输入图片地址" />-->
          <image-upload v-model="form.imgUrl" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            placeholder="请输入内容"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <user-tree-select
      :user-open="userOpen"
      @close="userOpen = false"
      @user-selected="handleUserSelected"
    />
  </div>
</template>

<script name="Device" setup>
import {
  addDevice,
  delDevice,
  getDevice,
  listDevice,
  updateDevice,
} from "@/api/iot/device";
import ImageUpload from "@/components/ImageUpload/index.vue";
import { listProduct } from "@/api/product/product";
import { deviceStatusMap, isShadowDict, locationWayMap } from "@/constant/dict";
import UserTreeSelect from "@/components/UserTreeSelect/index.vue";
import {
  getCurrentInstance,
  reactive,
  ref,
  shallowRef,
  toRefs,
  watchEffect,
} from "vue";
import DictTag from "@/components/DictTag/index.vue";
import { parseTime } from "@/utils/ruoyi";
import { useRouter } from "vue-router";
import { loadMap } from "@/utils/amap";
import MapSelect from "@/components/MapSelect/index.vue";

const router = useRouter();
const { proxy } = getCurrentInstance();

const props = defineProps({
  productId: {
    type: Number,
    default: null,
  },
});

const deviceList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const productOptions = ref([]);

const userOpen = ref(false);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceName: null,
    productId: null,
    userId: null,
    tenantId: null,
    serialNumber: null,
    firmwareVersion: null,
    status: null,
    rssi: null,
    isShadow: null,
    locationWay: null,
    thingsModelValue: null,
    networkAddress: null,
    networkIp: null,
    longitude: null,
    latitude: null,
    activeTime: null,
    summary: null,
    imgUrl: null,
  },
  rules: {
    deviceName: [
      { required: true, message: "设备名称不能为空", trigger: "blur" },
    ],
    productId: [{ required: true, message: "产品ID不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

watchEffect(() => {
  queryParams.value.productId = props.productId;
  getList();
});

/** 查询设备列表 */
function getList() {
  loading.value = true;
  listDevice(queryParams.value).then((response) => {
    deviceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    deviceId: null,
    deviceName: null,
    productId: null,
    userId: null,
    tenantId: null,
    serialNumber: null,
    firmwareVersion: null,
    status: null,
    rssi: null,
    isShadow: null,
    locationWay: null,
    thingsModelValue: null,
    networkAddress: null,
    networkIp: null,
    longitude: null,
    latitude: null,
    activeTime: null,
    summary: null,
    imgUrl: null,
    createBy: null,
    createTime: null,
    remark: null,
  };
  proxy.resetForm("deviceRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.deviceId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
async function handleAdd() {
  reset();
  form.value.productId = props.productId;
  open.value = true;
  title.value = "添加设备";
  if (!AMap.value) AMap.value = await loadMap([]);
  if (!map.value)
    map.value = new AMap.value.Map("map-container", {
      zoom: 11,
    });
  map.value.on("click", handleMapClick);
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _deviceId = row.deviceId || ids.value;
  getDevice(_deviceId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改设备";
  });
}

function handleDetail(row) {
  router.push(`/device/device/detail?id=${row.deviceId}`);
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deviceRef"].validate((valid) => {
    if (valid) {
      if (form.value.deviceId != null) {
        updateDevice(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDevice(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _deviceIds = row.deviceId || ids.value;
  proxy.$modal
    .confirm('是否确认删除设备编号为"' + _deviceIds + '"的数据项？')
    .then(function () {
      return delDevice(_deviceIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "iot/device/export",
    {
      ...queryParams.value,
    },
    `device_${new Date().getTime()}.xlsx`
  );
}

function getProductOptions(keyword) {
  listProduct({
    productName: keyword,
    pageNum: 1,
    pageSize: 20,
  }).then((resp) => {
    productOptions.value = resp.rows;
  });
}

const handleUserSelected = (data) => {
  form.value.userName = data.userName;
  form.value.userId = data.userId;
  userOpen.value = false;
};

const AMap = shallowRef();
const map = shallowRef();
const handleMapClick = (event) => {
  map.value.clearMap();
  const { lnglat } = event;
  form.value.latitude = lnglat.lat;
  form.value.longitude = lnglat.lng;
  const marker = new AMap.value.Marker({
    position: lnglat,
  });
  map.value.add(marker);
};

const handleMapSelected = (lnglat) => {
  form.value.latitude = lnglat.lat;
  form.value.longitude = lnglat.lng;
};

getProductOptions();
</script>
