<template>
  <div class="container">
    <TableSearch :query="query" :options="searchOpt" :search="handleSearch" />
    <div class="table-container">
      <TableCustom :selection-change="handleSelect" :columns="columns" :tableData="tableData" :paging="paging" :changePage="changePage">
        <template #toolbarBtn>
          <!-- <el-button type="primary" @click="handleAdd">新增</el-button> -->
          <el-button @click="handleEdit()">设备关联</el-button>
          <!-- <el-button>地图位置</el-button> -->
          <!-- <el-button>导出</el-button> -->
        </template>

        <template #status="{ rows }">
          <el-tag :type="statusColor[rows.status]">{{ statusEnum[rows.status] }}</el-tag>
        </template>
        <template #useStatus="{ rows }">
          <el-switch v-model="rows.useStatus" :active-value="1" :inactive-value="0" @click="handelSwitch(rows, 1)" />
        </template>
        <template #deviceSwitch="{ rows }">
          <el-switch v-model="rows.deviceSwitch" :active-value="1" :inactive-value="0" @click="handelSwitch(rows, 2)" />
        </template>
        <template #mode="{ rows }">
          <el-tag :type="modeColor[rows.mode]">{{ modeEnum[rows.mode] }}</el-tag>
        </template>
        <template #battery="{ rows }"> {{ rows.battery }}% </template>
        <template #operator="{ rows }">
          <el-button link type="primary" size="small" @click="toPage('deviceInfo', rows)"> 详细信息 </el-button>
          <el-button link type="primary" size="small" @click="toPage('mapLocation', rows)"> 地图位置 </el-button>
          <el-button link type="primary" size="small" @click="toPage('setting', rows)"> 专项配置 </el-button>
          <el-button link type="primary" size="small" @click="handelRow(rows)"> 设备控制 </el-button>
          <el-button link type="primary" size="small" @click="handleEdit(rows)"> 修改 </el-button>
          <!-- <el-button link type="danger" size="small" @click="handelDel(rows)"> 删除 </el-button> -->
        </template>
      </TableCustom>
    </div>
    <el-dialog :title="isEdit ? '编辑' : '新增'" v-model="visible" width="700px" destroy-on-close :close-on-click-modal="false" @close="closeDialog">
      <TableEdit :form-data="rowData" :options="TableEditOptions" :edit="isEdit" :update="updateData" @close="closeDialog" />
    </el-dialog>

    <el-dialog title="设备控制" v-model="visible1" width="700px" destroy-on-close :close-on-click-modal="false" @close="closeDialog">
      <!-- <TableEdit :form-data="rowData" :options="controlOptions" :update="updateData" /> -->
      <DeviceControl v-model="controlForm" @change="handelControl" />
    </el-dialog>
    <el-dialog title="设备关联" v-model="visible2" width="700px" destroy-on-close :close-on-click-modal="false" @close="closeDialog">
      <BindArea :orgAllData="orgAllData" :selectDeviceList="selectDeviceList" @close="visible2 = false" :api="bindWebFn" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="basetable">
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { deviceList, setMode, deviceGetLocation, deviceControl, setUseStatus, setStatus, orgAllList, bindWeb } from "@/api/index";
import { TbindWeb, TDevice, TOrg } from "@/api/index.d";
import TableCustom from "@/components/table-custom.vue";
import TableSearch from "@/components/table-search.vue";
import TableEdit from "@/components/table-edit.vue";
import DeviceControl from "./deviceControl.vue";
import BindArea from "./bindArea.vue";
import { TableItem } from "@/types/table";
import { FormOption, FormOptionList } from "@/types/form-option";
import { useRouter } from "vue-router";

enum statusEnum {
  "离线" = 0,
  "在线",
  "充电中",
}

enum modeEnum {
  "常规",
  "审讯模式",
  "户外押送",
}

const statusColor = ["danger", "success", "warning"];
const modeColor = ["primary", "danger", "warning"];

const router = useRouter();
// 新增/编辑弹窗相关
let TableEditOptions = ref<FormOption>({
  labelWidth: "100px",
  span: 24,
  list: [],
});
const addOp = [{ type: "input", label: "唯一编码", prop: "name", required: true }];
const editOp = [
  { type: "select", label: "选择手铐", prop: "name", required: true },
  { type: "select", label: "辖区列表", prop: "name2" },
  { type: "select", label: "账号列表", prop: "name3" },
];

// 查询相关
const query = reactive({});
const searchOpt = ref<FormOptionList[]>([
  { type: "input", label: "手铐SN：", prop: "deviceId" },
  { type: "input", label: "警察名称：", prop: "name" },
  {
    type: "select",
    label: "当前模式：",
    prop: "mode",
    opts: [
      { label: "常规", value: "0" },
      { label: "审讯", value: "1" },
      { label: "户外押送", value: "2" },
    ],
  },
  {
    type: "select",
    label: "设备状态：",
    prop: "status",
    opts: [
      { label: "离线", value: "0" },
      { label: "在线", value: "1" },
      { label: "充电中", value: "2" },
    ],
  },
  {
    type: "select",
    label: "使用状态：",
    prop: "useStatus",
    opts: [
      { label: "未使用", value: "0" },
      { label: "使用中", value: "1" },
    ],
  },
]);
const handleSearch = () => {
  changePage(1);
};
const selectDeviceList = ref<TDevice.IListRes[]>([]);
// 表格相关
let columns = ref([
  { type: "selection", reserveSelection: true },
  { type: "index", label: "序号", width: 55, align: "center" },
  { prop: "deviceId", label: "IMEI", width: 120 },
  { prop: "adminName", label: "绑定警察名称", width: 180 },
  { prop: "adminUsername", label: "绑定警察账户", width: 120 },
  { prop: "orgName", label: "关联辖区", width: 120 },
  { prop: "battery", label: "电量", width: 100 },
  { prop: "deviceVersion", label: "版本号", width: 100 },
  { prop: "status", label: "设备状态", width: 100 },
  { prop: "mode", label: "当前模式", width: 100 },
  { prop: "useStatus", label: "使用状态", width: 100 },
  { prop: "deviceSwitch", label: "启用开关", width: 100 },
  { prop: "createTime", label: "最新通信时间", width: 180 },
  { prop: "createTime", label: "创建时间", width: 180 },
  { prop: "operator", label: "操作", width: 400, fixed: "right" },
]);
const paging = reactive({
  page: 1,
  size: 10,
  total: 0,
});
const controlForm = reactive({
  mode: 0,
  location: 1,
});

const tableData = ref<TDevice.IListRes[]>([]);
const orgAllData = ref<TOrg.IOrgRecordRes[]>([]);
const getData = async () => {
  const res = await deviceList({ ...paging, ...query });
  tableData.value = res.records;
  paging.total = res.total;
};

const bindWebFn = (val: TbindWeb) => {
  bindWeb(val).then(() => {
    ElMessage.success("操作成功");
    visible2.value = false;
    getData();
  });
};

const handleSelect = (val: TDevice.IListRes[]) => {
  selectDeviceList.value = val;
};

const changePage = (val: number) => {
  paging.page = val;
  getData();
};

const visible1 = ref(false);
const visible2 = ref(false);
const visible = ref(false);
const isEdit = ref(false);
const rowData = ref<TDevice.IListRes>();

const handleAdd = () => {
  TableEditOptions.value.list = addOp;
  visible.value = true;
};

// 编辑
const handleEdit = (row?: TDevice.IListRes) => {
  if (row) {
    selectDeviceList.value = [row];
  }
  if (selectDeviceList.value.length == 0) return ElMessage.warning("请选择设备");
  visible2.value = true;
};

const handelRow = (row?: TDevice.IListRes) => {
  rowData.value = { ...row };
  controlForm.mode = row.mode;
  visible1.value = true;
};
const handelSwitch = (val: TDevice.IListRes, type: number) => {
  let api = type == 1 ? setUseStatus : setStatus;
  api({
    deviceId: val.deviceId,
    status: type == 1 ? val.useStatus : val.deviceSwitch,
  }).then(() => {
    getData();
    ElMessage.success("操作成功");
  });
};

const getOrgAllList = () => {
  orgAllList().then((res) => {
    orgAllData.value = res;
  });
};
const handelControl = (type: number) => {
  switch (type) {
    case 4:
      deviceGetLocation({
        deviceId: rowData.value.deviceId,
      }).then(() => {
        ElMessage.success("操作成功");
      });
      break;
    case 5:
      setMode({
        deviceId: rowData.value.deviceId,
        mode: controlForm.mode,
      }).then(() => {
        getData();
        ElMessage.success("操作成功");
      });
      break;
    default:
      let cmdEnum = {
        1: "poweroff",
        2: "restart",
        3: "factory",
      };
      deviceControl({
        deviceId: rowData.value.deviceId,
        cmd: cmdEnum[type],
      }).then(() => {
        ElMessage.success("操作成功");
      });
      break;
  }

  visible1.value = false;
};

const updateData = () => {
  closeDialog();
  getData();
};

const closeDialog = () => {
  visible.value = false;
  isEdit.value = false;
};

onMounted(() => {
  getData();
  getOrgAllList();
});

//
const toPage = (path: string, row: TDevice.IListRes) => {
  let p;
  if (path == "deviceInfo") {
    p = { ...row };
  } else if (path == "mapLocation") {
    p = { deviceId: row.deviceId };
  } else if (path == "setting") {
    p = { deviceId: row.deviceId };
  }
  router.push({
    path,
    query: p,
  });
};
</script>

<style scoped>
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
