<template>
  <div class="page">
    <el-card shadow="never" v-loading="batchLoading">
      <div class="system-user-search mb15">
        <el-form :model="tableData.param" ref="queryRef" inline class="search-form">
          <div class="search-conditions">
            <!-- 关键字 -->
            <el-form-item :label="$t('message.device.formI18nLabel.keyword')" prop="keyWord">
              <!-- 输入名称或标识 -->
              <el-input v-model="tableData.param.keyWord" :placeholder="$t('message.device.formI18nPlaceholder.keyword')" clearable style="width: 200px" @keyup.enter.native="typeList" />
            </el-form-item>
            <!--          <el-form-item label="标识" prop="key">-->
            <!--            <el-input v-model="tableData.param.key" placeholder="请输入设备标识" clearable style="width: 150px" @keyup.enter.native="typeList" />-->
            <!--          </el-form-item>-->
            <!-- 状态 -->
            <el-form-item :label="$t('message.device.formI18nLabel.status')" prop="status">
              <!-- 状态 -->
              <el-select v-model="tableData.param.status" :placeholder="$t('message.device.formI18nLabel.status')" clearable style="width: 88px">
                <!-- 在线 -->
                <el-option :label="$t('message.device.formI18nOption.online')" :value="2" />
                <!-- 离线 -->
                <el-option :label="$t('message.device.formI18nOption.offline')" :value="1" />
                <!-- 未启用 -->
                <el-option :label="$t('message.device.formI18nOption.off')" :value="0" />
              </el-select>
            </el-form-item>

            <template v-if="showMoreFilter">
              <!-- 所属产品 -->
              <el-form-item :label="$t('message.device.formI18nLabel.productBind')" prop="productKey">
                <!-- 选择产品 -->
                <el-select v-model="tableData.param.productKey" style="width: 120px" filterable clearable :placeholder="$t('message.device.formI18nLabel.productBind')">
                  <el-option v-for="item in productData" :key="item.key" :label="item.name" :value="item.key" value-key="id"> </el-option>
                </el-select>
              </el-form-item>

              <!-- 设备类型 -->
              <el-form-item :label="$t('message.device.formI18nLabel.deviceType')" prop="deviceTypes">
                <el-select v-model="tableData.param.deviceTypes" multiple style="width: 260px" clearable :placeholder="$t('message.device.formI18nLabel.deviceType')">
                  <!-- 设备 -->
                  <el-option :label="$t('message.device.formI18nOption.device')" value="设备" />
                  <!-- 网关 -->
                  <el-option :label="$t('message.device.formI18nOption.gateway')" value="网关" />
                  <!-- 子设备 -->
                  <el-option :label="$t('message.device.formI18nOption.subDevice')" value="子设备" />
                </el-select>
              </el-form-item>

              <!-- 所属组织 -->
              <el-form-item :label="$t('message.device.formI18nLabel.deptIds')" prop="deptIds">
                <!-- 请选择所属组织 -->
                <el-cascader
                  v-model="tableData.param.deptIds"
                  :options="deptOptions"
                  :props="{
                    checkStrictly: true,
                    value: 'deptId',
                    label: 'deptName',
                    children: 'children',
                    multiple: true,
                    emitPath: false
                  }"
                  style="width: 200px"
                  clearable
                  :placeholder="$t('message.device.formI18nPlaceholder.deptIds')"
                  collapse-tags
                  collapse-tags-tooltip
                  filterable
                />
              </el-form-item>

              <!-- 设备标签 -->
              <el-form-item :label="$t('message.device.formI18nLabel.deviceTag')" prop="tags">
                <!-- 请输入标签 -->
                <el-select
                  v-model="tableData.param.tags"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  :placeholder="$t('message.device.formI18nPlaceholder.deviceTag')"
                  style="width: 260px"
                  clearable
                >
                </el-select>
              </el-form-item>

              <!--          <el-form-item label="创建时间" prop="dateRange">-->
              <!--            <el-date-picker v-model="tableData.param.dateRange" style="width: 240px" value-format="YYYY-MM-DD" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>-->
              <!--          </el-form-item>-->
            </template>
          </div>

          <div class="search-actions">
            <el-form-item>
              <el-button link type="primary" @click="showMoreFilter = !showMoreFilter">
                <!-- 收起/更多筛选 -->
                {{ showMoreFilter ? $t('message.device.formI18nButton.collapse') : $t('message.device.formI18nButton.showMoreFilter') }}
                <el-icon class="el-icon--right">
                  <component :is="showMoreFilter ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </el-button>
            </el-form-item>

            <el-form-item>
              <!-- 查询 -->
              <el-button type="primary" class="ml10" @click="typeList">
                <el-icon>
                  <ele-Search />
                </el-icon>
                {{ $t('message.tableI18nAction.query') }}
              </el-button>
              <!-- <el-button @click="resetQuery(queryRef)">
                <el-icon>
                  <ele-Refresh />
                </el-icon>
                重置
              </el-button> -->
              <!-- 新增 -->
              <el-button type="primary" class="ml10" @click="onOpenAddDic" v-auth="'add'">
                <el-icon>
                  <ele-FolderAdd />
                </el-icon>
                {{ $t('message.tableI18nAction.add') }}
              </el-button>
              <!-- 删除 -->
              <el-button type="info" class="ml10" @click="onRowDel()" v-auth="'del'">
                <el-icon>
                  <ele-Delete />
                </el-icon>
                {{ $t('message.tableI18nAction.delete') }}
              </el-button>

              <el-dropdown>
                <!-- 更多 -->
                <el-button type="danger" class="ml10">
                  {{ $t('message.tableI18nAction.more') }}
                  <el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item>
                      <!-- 批量启用 -->
                      <el-button type="success" @click="setDeviceStatus1()">
                        <el-icon>
                          <ele-Open />
                        </el-icon>
                        {{ $t('message.device.formI18nButton.batchEnable') }}
                      </el-button>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <!-- 批量禁用 -->
                      <el-button type="warning" @click="setDeviceStatus0()">
                        <el-icon>
                          <ele-TurnOff />
                        </el-icon>
                        {{ $t('message.device.formI18nButton.batchDisable') }}
                      </el-button>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <!-- 导入设备 -->
                      <el-button @click="onOpenexcelDic('upload')">
                        <el-icon>
                          <ele-Upload />
                        </el-icon>
                        {{ $t('message.device.formI18nButton.importDevice') }}
                      </el-button>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <!-- 导出设备 -->
                      <el-button @click="onOpenexcelDic('down')">
                        <el-icon>
                          <ele-Download />
                        </el-icon>
                        {{ $t('message.device.formI18nButton.exportDevice') }}
                      </el-button>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <el-table :data="tableData.data" style="width: 100%" @selection-change="handleSelectionChange" v-loading="tableData.loading">
        <el-table-column type="selection" width="55" align="center" />
        <!-- 标识 -->
        <el-table-column :label="$t('message.device.tableI18nColumn.key')" prop="key" min-width="150" show-overflow-tooltip v-col="'key'">
          <template #default="{ row }">
            <copy :text="row.key"></copy>
          </template>
        </el-table-column>
        <!-- 设备名称 -->
        <el-table-column :label="$t('message.device.tableI18nColumn.deviceName')" prop="name" min-width="160" show-overflow-tooltip v-col="'name'" />
        <!-- 设备类型 -->
        <el-table-column :label="$t('message.device.tableI18nColumn.deviceType2')" prop="product.deviceType" min-width="120" align="center" show-overflow-tooltip v-col="'deviceType'" />
        <!-- 所属产品 -->
        <el-table-column :label="$t('message.device.formI18nLabel.productBind')" prop="productName" min-width="160" align="center" show-overflow-tooltip v-col="'productName'" />
        <!-- 状态 -->
        <el-table-column prop="status" :label="$t('message.device.tableI18nColumn.status')" min-width="90" align="center" v-col="'status'">
          <template #default="scope">
            <!-- 离线 -->
            <el-tag type="danger" size="small" v-if="scope.row.status == 1">{{ $t('message.device.formI18nOption.offline') }}</el-tag>
            <!-- 在线 -->
            <el-tag type="success" size="small" v-if="scope.row.status == 2">{{ $t('message.device.formI18nOption.online') }}</el-tag>
            <!-- 未启用 -->
            <el-tag type="info" size="small" v-if="scope.row.status == 0">{{ $t('message.device.formI18nOption.off') }}</el-tag>
          </template>
        </el-table-column>
        <!-- 最后上线时间  -->
        <el-table-column prop="lastOnlineTime" :label="$t('message.device.tableI18nColumn.lastOnlineTime')" align="center" width="160" v-col="'lastOnlineTime'"></el-table-column>
        <!-- 说明 -->
        <el-table-column prop="desc" :label="$t('message.device.tableI18nColumn.desc2')" min-width="110" show-overflow-tooltip v-col="'desc'"></el-table-column>
        <!-- 操作 -->
        <el-table-column :label="$t('message.tableI18nColumn.operation')" width="200" align="center" fixed="right">
          <template #default="scope">
            <!-- 详情 -->
            <router-link :to="'/iotmanager/device/instance/' + scope.row.key" class="link-type" style="padding-right: 12px;font-size: 12px;color: #409eff;" v-auth="'detail'">
              <span>{{ $t('message.tableI18nAction.detail') }}</span>
            </router-link>
            <!-- 修改 -->
            <el-button size="small" text type="warning" @click="onOpenEditDic(scope.row)" v-auth="'edit'">{{ $t('message.tableI18nAction.edit') }}</el-button>
            <!-- 启用 -->
            <el-button size="small" text type="success" @click="onActionStatus(scope.row)" v-if="scope.row.status == 0" v-auth="'status'">{{ $t('message.device.enable') }}</el-button>
            <!-- 停用 -->
            <el-button size="small" text type="primary" @click="onActionStatus(scope.row)" v-if="scope.row.status > 0" v-auth="'status'">{{ $t('message.device.disable') }}</el-button>
            <!-- 删除 -->
            <el-button size="small" text type="info" @click="onRowDel(scope.row)" v-auth="'del'">{{ $t('message.tableI18nAction.delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="tableData.total > 0" :total="tableData.total" v-model:page="tableData.param.pageNum" v-model:limit="tableData.param.pageSize" @pagination="typeList" />
    </el-card>
    <EditDic ref="editDicRef" @typeList="typeList" />
    <ExcelDic ref="excelDicRef" @typeList="typeList" />
  </div>
</template>

<script lang="ts">
import { toRefs, reactive, onMounted, ref, defineComponent } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessageBox, ElMessage, FormInstance } from 'element-plus';
import EditDic from './component/edit.vue';
import ExcelDic from './component/excel.vue';
import api from '/@/api/device';
import systemApi from '/@/api/system';
import { ArrowDown, ArrowUp } from '@element-plus/icons-vue'

// 定义接口来定义对象的类型
interface TableDataRow {
  id: number;
  name: string;
  key: string;
  status: number;
  desc: string;
  createBy: string;
}
interface TableDataState {
  keys: string[];
  productData: Array<TableDataRow>;
  tableData: {
    data: Array<TableDataRow>;
    total: number;
    loading: boolean;
    param: {
      pageNum: number;
      pageSize: number;
      keyWord: string;
      key: string;
      productKey: string;
      status: string;
      deviceTypes: string[];
      deptIds: number[];
      tags: string[];
      dateRange: string[];
    };
  };
}

export default defineComponent({
  name: 'deviceInstance',
  components: { EditDic, ExcelDic, ArrowDown, ArrowUp },
  setup() {
    const addDicRef = ref();
    const editDicRef = ref();
    const excelDicRef = ref();
    const detailRef = ref();
    const queryRef = ref();
    const batchLoading = ref(false);
    const showMoreFilter = ref(false); // 控制是否显示更多筛选条件
    const deptOptions = ref([]); // 部门树数据
    const route = useRoute();
    const state = reactive<TableDataState>({
      keys: [],
      productData: [],
      tableData: {
        data: [],
        total: 0,
        loading: false,
        param: {
          pageNum: 1,
          pageSize: 20,
          keyWord: '',
          key: '',
          productKey: <string>route.query?.productKey || '',
          status: '',
          deviceTypes: [],
          deptIds: [],
          tags: [],
          dateRange: [],
        },
      },
    });
    // 初始化表格数据
    const initTableData = () => {
      typeList();
      getProductList();
      getDeptTree();
    };
    const typeList = () => {
      state.tableData.loading = true;
      api.instance.getList(state.tableData.param).then((res: any) => {
        state.tableData.data = res.device;
        state.tableData.total = res.total;
      }).finally(() => (state.tableData.loading = false));
    };
    const getProductList = () => {
      api.product.getLists().then((res: any) => {
        state.productData = res.product
      })
    }
    //查看详情
    const onOpenDetail = (row: TableDataRow) => {
      detailRef.value.openDialog(row);
    }
    // 打开新增产品弹窗
    const onOpenAddDic = () => {
      editDicRef.value.openDialog();
    };
    // 打开修改产品弹窗
    const onOpenEditDic = (row: TableDataRow) => {
      editDicRef.value.openDialog(row);
    };


    const onOpenexcelDic = (type: string) => {
      excelDicRef.value.openDialog(type);
    };

    //批量启用
    const setDeviceStatus1 = (row?: TableDataRow) => {
      let keys: string[] = [];
      if (row) {
        keys = [row.key];
      } else {
        keys = state.keys;
      }
      if (keys.length === 0) {
        // 请选择要操作的数据。
        ElMessage.error('请选择要操作的数据。');
        return;
      }
      // 确认要批量启用这些设备吗？
      ElMessageBox.confirm("确认要批量启用这些设备吗？", '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          batchLoading.value = true
          api.device.setDeviceStatus({ ids: keys, status: 1 }).then(() => {
            // 启用成功
            ElMessage.success('启用成功');
            typeList();
          }).finally(() => batchLoading.value = false)
        })
        .catch(() => { });
    }

    //批量禁用
    const setDeviceStatus0 = (row?: TableDataRow) => {
      let keys: string[] = [];
      if (row) {
        keys = [row.key];
      } else {
        keys = state.keys;
      }
      if (keys.length === 0) {
        // 请选择要操作的数据。
        ElMessage.error('请选择要操作的数据。');
        return;
      }
      // 确认要批量禁用这些设备吗？
      ElMessageBox.confirm("确认要批量禁用这些设备吗？", '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          batchLoading.value = true
          api.device.setDeviceStatus({ ids: keys, status: 0 }).then(() => {
            // 禁用成功
            ElMessage.success('禁用成功');
            typeList();
          }).finally(() => batchLoading.value = false)
        })
        .catch(() => { });
    }
    // 删除产品
    const onRowDel = (row?: TableDataRow) => {
      // 你确定要删除所选数据？
      let msg = '你确定要删除所选数据？';
      let keys: string[] = [];
      if (row) {
        // 此操作将永久删除设备："${row.name}"，是否继续?
        msg = `此操作将永久删除设备："${row.name}"，是否继续?`;
        keys = [row.key];
      } else {
        keys = state.keys;
      }
      if (keys.length === 0) {
        // 请选择要删除的数据。
        ElMessage.error('请选择要删除的数据。');
        return;
      }
      ElMessageBox.confirm(msg, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          api.instance.del(keys).then(() => {
            // 删除成功
            ElMessage.success('删除成功');
            typeList();
          });
        })
        .catch(() => { });
    };
    // 页面加载时
    onMounted(() => {
      initTableData();
    });
    /** 重置按钮操作 */
    const resetQuery = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      formEl.resetFields();
      state.tableData.param.tags = []; // 确保标签也被重置
      state.tableData.param.deviceTypes = []; // 确保设备类型也被重置
      state.tableData.param.deptIds = []; // 确保所属组织也被重置
      typeList();
    };
    // 多选框选中数据
    const handleSelectionChange = (selection: TableDataRow[]) => {
      state.keys = selection.map((item) => item.key);
    };

    const onActionStatus = (item: TableDataRow) => {
      if (item.status == 0) {
        api.instance.devdeploy(item.key).then((res: any) => {
          typeList();
          // 操作成功
          ElMessage.success(res.message || '操作成功');
        });
      } else {
        api.instance.devundeploy(item.key).then((res: any) => {
          typeList();
          // 操作成功
          ElMessage.success(res.message || '操作成功');
        });
      }
    }

    // 获取部门树
    const getDeptTree = () => {
      systemApi.dept.getList({status: -1}).then((res: any) => {
        if (Array.isArray(res)) {
          deptOptions.value = res;
        } else {
          console.error('获取部门树失败，返回数据不是数组', res);
        }
      }).catch(error => {
        console.error('获取部门树出错', error);
      });
    };

    return {

      addDicRef,
      excelDicRef,
      onOpenexcelDic,
      editDicRef,
      detailRef,
      queryRef,
      onActionStatus,
      batchLoading,
      showMoreFilter,
      deptOptions,
      setDeviceStatus1,
      setDeviceStatus0,
      onOpenDetail,
      onOpenAddDic,
      onOpenEditDic,
      onRowDel,
      typeList,
      resetQuery,
      handleSelectionChange,
      ...toRefs(state),
    };
  },
});
</script>

<style lang="scss" scoped>
.search-form {
  display: flex;
  justify-content: space-between;
  width: 100%;
  flex-wrap: wrap;

  .search-conditions {
    display: flex;
    flex-wrap: wrap;
    flex: 1;
  }

  .search-actions {
    display: flex;
    justify-content: flex-end;
    margin-left: auto;
  }
}
</style>
