<template>
  <div class="h-full flex flex-col 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" label-width="100">
            <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:deviceRepair:add'])"
            :show-delete="checkPermi(['warehouse:deviceRepair:remove'])"
            :show-edit="checkPermi(['warehouse:deviceRepair:edit'])"
            @update:add="handleAdd"
            @update:edit="handleUpdate()"
            @update:delete="handleDelete()"
          ></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="deviceRepairList" border @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55" />
        <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="maintainUserNames" />
        <el-table-column align="center" label="故障描述" prop="faultDesc" />
        <el-table-column align="center" label="维修结果" prop="repairResult">
          <template #default="scope">
            <dict-tag :options="com_equipment_repair_status" :value="scope.row.repairResult"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注" prop="remark" />
        <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作" width="160">
          <template #default="scope">
            <el-button v-has-permi="['warehouse:deviceRepair:query']" link type="primary" @click="handleMain(scope.row)">查看详情</el-button>
            <el-button v-has-permi="['warehouse:deviceRepair:edit']" link type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button v-has-permi="['warehouse:deviceRepair: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="DeviceRepair" setup>
import { listDeviceRepair, delDeviceRepair } from '@/api/system/equipment/Repair';
import { DeviceRepairVO, DeviceRepairQuery, DeviceRepairForm } from '@/api/system/equipment/Repair/type';
import { checkPermi } from '@/utils/permission';

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

interface tableType extends DeviceRepairVO {
  maintainUserNames?: string;
}
const deviceRepairList = 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 deviceRepairFormRef = ref<ElFormInstance>();

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

const initFormData: DeviceRepairForm = {
  id: undefined,
  deviceId: undefined,
  deviceName: undefined,
  deviceCode: undefined,
  deviceModel: undefined,
  area: undefined,
  maintainUserIds: undefined,
  faultDesc: undefined,
  repairResult: undefined,
  repairTime: undefined,
  remark: undefined
};
const data = reactive<PageData<DeviceRepairForm, DeviceRepairQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceId: undefined,
    deviceName: undefined,
    deviceCode: undefined,
    deviceModel: undefined,
    area: undefined,
    maintainUserIds: undefined,
    faultDesc: undefined,
    repairResult: undefined,
    repairTime: undefined,
    params: {}
  }
});

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

/** 查询维修工单列表 */
// TODO 设备维修记录 用户id有，用户信息没有
const getList = async () => {
  loading.value = true;
  listDeviceRepair(queryParams.value)
    .then((res) => {
      deviceRepairList.value = res.rows;
      deviceRepairList.value.forEach((item) => {
        if (item.maintainUserList && item.maintainUserList.length > 0) {
          item.maintainUserNames = item.maintainUserList
            .map((i) => i.nickName)
            .filter((i) => i)
            .join(',');
        }
      });
      total.value = res.total;
    })
    .finally(() => {
      loading.value = false;
    });
};

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

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

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: DeviceRepairVO[]) => {
  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/addEquipmentRepair'
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: DeviceRepairVO) => {
  const _ids = row?.id || ids.value[0];

  router.push({
    path: '/equipment/editEquipmentRepair',
    query: {
      id: _ids
    }
  });
};

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

const handleMain = (row) => {
  router.push({
    path: '/equipment/equipmentRepairMain',
    query: {
      id: row.id
    }
  });
};

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

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