<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <!-- <el-form-item label="猎鹰服务ID" prop="sid">
              <el-input v-model="queryParams.sid" placeholder="请输入猎鹰服务ID" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="服务名称" prop="sname">
              <el-input v-model="queryParams.sname" placeholder="请输入服务名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:service:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:service:edit']"
              >修改</el-button
            >
          </el-col>

          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:service:export']">导出</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="serviceList" @selection-change="handleSelectionChange">
        <el-table-column label="猎鹰服务ID" align="center" prop="sid" />
        <el-table-column label="服务名称" align="center" prop="sname" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="关联设备" placement="top">
              <el-button link type="primary" icon="Connection" @click="ShowCheckDevice(scope.row)" v-hasPermi="['system:service:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:service:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="终端" placement="top">
              <el-button link type="primary" icon="View" @click="ShowMapDevice(scope.row)"></el-button>
            </el-tooltip>
            <!-- <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:service:remove']"></el-button>
            </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改轨迹服务对话框 -->
    <el-dialog :title="dialog.title" :draggable="true" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="serviceFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="服务名称" prop="sname">
          <el-input v-model="form.sname" placeholder="请输入服务名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 关联设备维护 -->
    <el-dialog :title="dialog.connectTitle" :draggable="true" footer-class="dilogFooter" v-model="dialog.connectVisible" width="80%" append-to-body>
      <div class="deviceContent" v-loading="dialog.connctLoading">
        <div class="filter">
          <el-form :inline="true">
            <el-form-item label="关键字" prop="checkedKey">
              <el-input v-model="searchFilter.checkedKey" placeholder="imei查询" clearable @keyup.enter="handleTerminalQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="searchCheckedDevice">搜索</el-button>
              <el-button icon="Refresh" @click="searchFilter.checkedKey='';searchCheckedDevice()">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" @click="ShowAllDevice" v-hasPermi="['system:service:add']">新增</el-button>
            </el-col>

            <el-col :span="1.5">
              <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="DelChecked()" v-hasPermi="['system:service:remove']"
                >删除</el-button
              >
            </el-col>
          </el-row>
        </div>
        <div class="checked">
          <el-table
            v-loading="loading"
            border
            :data="checkedDevices"
            @selection-change="handleSelectionChange"
            reserve-selection="true"
            ref="multipleTableRef"
            row-key="id"
          >
            <el-table-column type="selection" width="55" align="center" reserve-selection="true" />
            <!-- <el-table-column label="deviceId" align="center" prop="deviceId" />
            <el-table-column label="id" align="center" prop="id" /> -->
            <el-table-column label="设备类型" align="center" prop="typeName" />
            <el-table-column label="设备名称" align="center" prop="deviceName" />
            <el-table-column label="IMEI" align="center" prop="deviceImei" />
            <el-table-column label="Mac" align="center" prop="deviceMac" />
            <el-table-column label="蓝牙名称" align="center" prop="bluetoothName" />
            <!-- <el-table-column label="高德服务id" align="center" prop="sid" /> -->
            <el-table-column label="高德终端id" align="center" prop="tid" />
            <el-table-column label="高德轨迹id" align="center" prop="trid" />
          </el-table>

          <pagination
            :total="checkedPageParams.total"
            v-model:page="checkedPageParams.pageNum"
            v-model:limit="checkedPageParams.pageSize"
            @pagination="searchCheckedDevice"
          />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelConn">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="选择设备" :draggable="true" footer-class="dilogFooter" v-model="dialog.checkVisible" width="65%" append-to-body>
      <div class="checkdeviceContent" v-loading="dialog.checkLoading">
             <div class="filter">
          <el-form :inline="true">
            <el-form-item label="关键字" prop="nocheckKey">
              <el-input v-model="searchFilter.nocheckKey" placeholder="imei查询" clearable @keyup.enter="handleTerminalQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="searchNoCheckDevice">搜索</el-button>
              <el-button icon="Refresh" @click="searchFilter.nocheckKey='';searchNoCheckDevice()">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="noCheck">
          <el-table v-loading="loading" border :data="noCheckDevices" @selection-change="checkNocheckChange" row-key="id">
            <el-table-column type="selection" width="55" align="center" :selectable="selectable" />
            <!-- <el-table-column label="deviceId" align="center" prop="deviceId" />
            <el-table-column label="id" align="center" prop="id" /> -->
            <el-table-column label="设备类型" align="center" prop="typeName" />
            <el-table-column label="设备名称" align="center" prop="deviceName" />
            <el-table-column label="IMEI" align="center" prop="deviceImei" />
            <el-table-column label="Mac" align="center" prop="deviceMac" />
            <el-table-column label="蓝牙名称" align="center" prop="bluetoothName" />
            <el-table-column label="高德服务id" align="center" prop="sid" />
            <el-table-column label="高德终端id" align="center" prop="tid" />
            <el-table-column label="高德轨迹id" align="center" prop="trid" />
          </el-table>

          <pagination
            :total="noCheckPageParams.total"
            v-model:page="noCheckPageParams.pageNum"
            v-model:limit="noCheckPageParams.pageSize"
            @pagination="searchNoCheckDevice"
          />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" :disabled="checkNoFlag" @click="checkedOK">保 存</el-button>
          <el-button @click="cancelCheck">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="查看终端" :draggable="true" footer-class="dilogFooter" v-model="dialog.showMap" width="70%" append-to-body>
      <div class="checkdeviceContent" v-loading="dialog.viewLoading">
        <div class="filter">
          <el-form :inline="true">
            <el-form-item label="关键字" prop="keywork">
              <el-input v-model="TerminalQuery.keywork" placeholder="终端名称/描述/自定义内容" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleTerminalQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetTterminalQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="noCheck">
          <el-table v-loading="loading" border :data="mapDevices" reserve-selection="true" row-key="tid">
            <el-table-column label="终端设备id" align="center" prop="tid" />
            <el-table-column label="终端名称" align="center" prop="name" />
            <el-table-column label="创建时间" align="center" prop="createtime" />
            <el-table-column label="最后定位时间" align="center" prop="locatetime" />
            <el-table-column label="终端描述" align="center" prop="desc" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="删除" placement="top">
                  <el-button link type="primary" icon="Delete" @click="deleteDevice(scope.row)" v-hasPermi="['system:service:remove']"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            :total="viewDevicePageParams.total"
            v-model:page="viewDevicePageParams.pageNum"
            v-model:limit="viewDevicePageParams.pageSize"
            @pagination="ShowMapDevice"
          />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" :disabled="checkNoFlag" @click="checkedOK">保 存</el-button>
          <el-button @click="HideMapDevice">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Service" lang="ts">
import {
  listService,
  getService,
  delService,
  addService,
  updateService,
  getDevice,
  terminalDevice,
  delTerminalDevice,
  getMapDevice,
  getMapDeviceByFilter,
  getDeviceList
} from '@/api/system/service/api';
import { ServiceVO, ServiceQuery, ServiceForm } from '@/api/system/service/types';
import type { TableInstance } from 'element-plus';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const serviceList = ref<ServiceVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<any>([]);
const checkNoDevices = ref<any>([]);
const single = ref(true);
const multiple = ref(true);
const checkNoFlag = ref(true);
const total = ref(0);
const multipleTableRef = ref<TableInstance>();
const queryFormRef = ref<ElFormInstance>();
const serviceFormRef = ref<ElFormInstance>();

const dialog = reactive({
  visible: false,
  title: '',
  connectVisible: false,
  connectTitle: '编辑关联设备',
  connctLoading: false,
  checkVisible: false,
  checkLoading: false,
  showMap: false,
  viewLoading: false
});


const searchFilter=ref({
  nocheckKey:'',
  checkedKey:''
});
const initFormData: ServiceForm = {
  id: undefined,
  sid: undefined,
  sname: undefined
};
const data = reactive<PageData<ServiceForm, ServiceQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sid: undefined,
    sname: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }]
  }
});

var cEdit = reactive<ServiceVO>({
  id: null,
  sid: null,
  sname: null
});

var noCheckPageParams = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0
});
var checkedPageParams = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0
});

var viewDevicePageParams = reactive({
  pageNum: 1,
  pageSize: 50,
  total: 0
});

var noCheckDevices = ref([]);
var checkedDevices = ref([]);
var mapDevices = ref([]);
const { queryParams, form, rules } = toRefs(data);
/** 重置按钮操作 */
const resetTterminalQuery = () => {
  TerminalQuery.value.keywork = '';
  ShowMapDevice(cEdit);
};

/** 搜索按钮操作 */
const handleTerminalQuery = () => {
  viewDevicePageParams.pageNum = 1;
  ShowMapDevice(cEdit);
};

//查看终端
function ShowMapDevice(row) {
  debugger;
  dialog.showMap = true;
  if(row && row.sid){
 cEdit = row;
  }
 

  let para2 = { sid: cEdit.sid, 
    filter: TerminalQuery.value.keywork, 
    page: viewDevicePageParams.pageNum, 
    pagesize: viewDevicePageParams.pageSize 
  };

  dialog.viewLoading = true;

  let p2 = getMapDeviceByFilter(para2);

  p2.then((res) => {
    if (res.code === 200) {
      mapDevices.value = res.rows;
      viewDevicePageParams.total = res.total;
    } else {
      mapDevices.value = [];
      viewDevicePageParams.total = 0;
    }
  }).finally(() => {
    dialog.viewLoading = false;
  });
}

function HideMapDevice() {
  dialog.showMap = false;
  cEdit = null;
}

/** 查询轨迹服务列表 */
const getList = async () => {
  loading.value = true;
  const res = await listService(queryParams.value);
  serviceList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

function selectable(row, index) {
  if (row.sid) {
    return false;
  }
  return true;
}

//查询未选择的设备
const searchNoCheckDevice = () => {
  return new Promise((resolve, reject) => {
    let para = {
      deviceStatus: 1,
      // isTid: false,
      // sid: cEdit.sid,
      pageNum: noCheckPageParams.pageNum,
      pageSize: noCheckPageParams.pageSize,
      deviceImei:searchFilter.value.nocheckKey
    };
    dialog.checkLoading = true;
    getDeviceList(para)
      .then((res) => {
        debugger;
        if (res.code === 200) {
          noCheckDevices.value = res.rows;
          noCheckPageParams.total = res.total;
          resolve(res);

          return;
        }
        resolve(null);
      })
      .catch((ex) => {
        resolve(null);
      })
      .finally(() => {
        dialog.checkLoading = false;
      });
  });
};
//查询已选择的设备
const searchCheckedDevice = () => {
  return new Promise((resolve, reject) => {
    let para = {
      deviceStatus: 1,
      isTid: true,
      sid: cEdit.sid,
      pageNum: checkedPageParams.pageNum,
      pageSize: checkedPageParams.pageSize,
      deviceImei:searchFilter.value.checkedKey
    };
    checkedPageParams.total = 0;
    dialog.connctLoading = true;
    getDevice(para)
      .then((res) => {
        console.log('查询已选择设备成功');
        if (res.code === 200) {
          debugger;
          checkedDevices.value = res.rows;
          checkedPageParams.total = res.total;
          resolve(res);
          return;
        }
        resolve(null);
      })
      .catch((ex) => {
        resolve(null);
      })
      .finally(() => {
        dialog.connctLoading = false;
      });
  });
};

/** 关闭关联设备的弹窗 */
const cancelConn = () => {
  dialog.connectVisible = false;
};
const cancelCheck = () => {
  dialog.checkVisible = false;
};
//弹出选择框
const ShowCheckDevice = (row) => {
  cEdit = row;
  dialog.connectVisible = true;
  searchCheckedDevice();
};
const ShowAllDevice = () => {
  dialog.checkVisible = true;

  searchNoCheckDevice();
};
//删除某一个
const deleteDevice = (row) => {
  proxy?.$modal.confirm('删除后不可恢复,是否确认选中的的数据项？').then((res) => {
    // delTerminalDevice(row.tid).then((res) => {
    //   if (res.code === 200) {
    //     proxy?.$modal.msgSuccess(res.msg);
    //     searchCheckedDevice();
    //   } else {
    //     proxy?.$modal.alertError('操作失败');
    //   }
    // });
  });
};
//删除所选
const DelChecked = () => {
  if (!ids.value.length) {
    proxy?.$modal.msgError('请选择要删除的数据');

    return;
  }

  let id = ids.value
    .map((v) => {
      return v.deviceId;
    })
    .join(',');

  proxy?.$modal.confirm('删除后不可恢复,是否确认选中的的数据项？').then((res) => {
    delTerminalDevice(id).then((res) => {
      if (res.code === 200) {
        proxy?.$modal.msgSuccess(res.msg);
        searchCheckedDevice();
      } else {
        proxy?.$modal.alertError('操作失败');
      }
    });
  });
};
//选中某一些设备
const checkedOK = () => {
  if (!checkNoFlag.value) {
    if (checkNoDevices.value.length > 0) {
      let arr = checkNoDevices.value.map((v) => {
        return { deviceImei: v.deviceImei, typeName: v.typeName, id: v.id };
      });
      let data = { sid: cEdit.sid, deviceList: arr };
      terminalDevice(data).then((res) => {
        if (res.code === 200) {
          proxy?.$modal.msgSuccess('操作成功');
          searchNoCheckDevice();
          searchCheckedDevice();
        } else {
          proxy?.$modal.msgError('操作失败');
        }
      });
    }
  }
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  serviceFormRef.value?.resetFields();
};

const TerminalQuery = ref({
  keywork: ''
});
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: ServiceVO[]) => {
  ids.value = selection;
  if (selection.length) {
    multiple.value = false;
  } else {
    multiple.value = true;
  }
};

const checkNocheckChange = (selection: ServiceVO[]) => {
  checkNoDevices.value = selection;
  if (selection.length) {
    checkNoFlag.value = false;
  } else {
    checkNoFlag.value = true;
  }
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加轨迹服务';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ServiceVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getService(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改轨迹服务';
};

/** 提交按钮 */
const submitForm = () => {
  serviceFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateService(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addService(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ServiceVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除轨迹服务编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delService(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/service/export',
    {
      ...queryParams.value
    },
    `service_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.deviceContent {
  width: 100%;
  height: 75vh;
}

.checkdeviceContent {
  width: 100%;
  height: 65vh;
}

.noCheck,
.checked {
  width: 100%;
  height: 100%;
  /* border: 1px solid #b8b6b6; */
  border-radius: 8px;
  padding: 8px;
  box-sizing: border-box;
}

.dilogFooter {
  text-align: center;
}
.center {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: center;
  align-items: center;
}

.cell,
:deep .cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

:deep .el-checkbox__input.is-disabled .el-checkbox__inner,
.el-checkbox__input.is-disabled .el-checkbox__inner {
  background-color: #e5e5e5 !important;
}
</style>
