<template>
  <div class="flex flex-col h-full p-2">
    <pageheader></pageheader>

    <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" :inline="true" :model="queryParams" @submit.prevent="handleQuery">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="queryParams.deviceName" clearable maxlength="20" placeholder="请输入设备名称" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="设备编号" prop="deviceCode">
              <el-input v-model="queryParams.deviceCode" clearable maxlength="20" placeholder="请输入设备编号" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">搜索</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card class="flex-1" shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <right-toolbar
            :disable-delete="multiple"
            :disable-edit="single"
            :show-add="checkPermi(['warehouse:device:add'])"
            :show-delete="checkPermi(['warehouse:device:remove'])"
            :show-edit="checkPermi(['warehouse:device:edit'])"
            @update:add="handleAdd"
            @update:edit="handleUpdate()"
            @update:delete="handleDelete()"
          ></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="deviceList" border @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column align="center" label="设备分类" prop="categoryName" width="100" />
        <el-table-column align="center" label="设备名称" prop="deviceName" />
        <el-table-column align="center" label="设备编号" prop="deviceCode" />
        <el-table-column align="center" label="品牌型号" prop="deviceModel" />
        <el-table-column align="center" label="所在区域" prop="area" show-overflow-tooltip />
        <el-table-column align="center" label="设备状态" prop="status" width="80">
          <template #default="scope">
            <dict-tag :options="com_equipment_archive_status" :value="scope.row.status"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="维护人员" prop="maintainUserListName" show-overflow-tooltip />
        <el-table-column align="center" label="备注" prop="remark" show-overflow-tooltip />
        <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作" width="180">
          <template #default="scope">
            <el-button v-has-permi="['warehouse:device:query']" link type="primary" @click="handleMain(scope.row)">查看详情</el-button>
            <el-button v-has-permi="['warehouse:device:edit']" link type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button v-has-permi="['warehouse:device:remove']" 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-card>
  </div>
</template>

<script lang="ts" name="Device" setup>
import { listDevice, delDevice, addDevice, updateDevice } from '@/api/system/equipment/archive';
import { DeviceVO, DeviceQuery, DeviceForm } from '@/api/system/equipment/archive/type';
import { checkPermi } from '@/utils/permission';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { com_equipment_archive_status } = toRefs<any>(proxy?.useDict('com_equipment_archive_status'));

interface tableType extends DeviceVO {
  maintainUserListName?: string;
}
const deviceList = ref<tableType[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const deviceFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: DeviceForm = {
  id: undefined,
  categoryId: undefined,
  deviceName: undefined,
  deviceCode: undefined,
  deviceModel: undefined,
  area: undefined,
  maintainUserIds: undefined,
  status: undefined,
  remark: undefined
};
const data = reactive<PageData<DeviceForm, DeviceQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryId: undefined,
    deviceName: undefined,
    deviceCode: undefined,
    deviceModel: undefined,
    area: undefined,
    maintainUserIds: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
    categoryId: [{ required: true, message: '设备分类ID不能为空', trigger: 'blur' }],
    deviceName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }]
  }
});

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

/** 查询设备列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDevice(queryParams.value);
  deviceList.value = res.rows;
  deviceList.value.forEach((item) => {
    if (item.maintainUserList && item.maintainUserList.length > 0) {
      item.maintainUserListName = item.maintainUserList
        .map((it) => (it.nickName ? it.nickName : null))
        .filter((it) => it !== null)
        .join(',');
    }
  });
  total.value = res.total;
  loading.value = false;
};

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

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

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: DeviceVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
const router = useRouter();
/** 新增按钮操作 */
const handleAdd = () => {
  router.push({
    path: '/equipment/addArchive'
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: DeviceVO) => {
  const _ids = row?.id || ids.value;
  router.push({
    path: '/equipment/editArchive',
    query: {
      id: _ids
    }
  });
};
/** 详情按钮操作 */
const handleMain = async (row?: DeviceVO) => {
  router.push({
    path: '/equipment/archiveMain',
    query: {
      id: row.id
    }
  });
};

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

/** 删除按钮操作 */
const handleDelete = async (row?: DeviceVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除该设备？').finally(() => (loading.value = false));
  await delDevice(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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

onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
.el-table {
  height: calc(100% - 80px);
}
</style>
