<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" label-width="100px" :model="queryParams" :inline="true">
            <el-form-item label="巡检计划名称" prop="planName">
              <el-input v-model="queryParams.planName" 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 class="flex-1" 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="['inspection:add:plan']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['inspection:edit:plan']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:plan:remove']"
              >删除</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="planList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="巡检计划名称" align="center" prop="planName" />
        <!-- <el-table-column label="执行周期" align="center" prop="executeCycle" /> -->
        <el-table-column label="执行星期" align="center">
          <template #default="scope">
            <span v-for="(item, index) in scope.row.executeDayNames" :key="index" class="pl-5px">{{ numToWeek(item) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="任务时间" align="center" prop="taskTime" />
        <el-table-column label="计划路线" align="center" prop="routeNames" />
        <el-table-column label="状态" width="150" align="center" prop="status">
          <template #default="scope">
            <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1" active-text="关闭" inactive-text="开启"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="110" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['inspection:edit:plan']">修改</el-button>
            <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['system:plan:remove']">删除</el-button>
          </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>
  </div>
</template>

<script setup name="Plan" lang="ts">
import { listPlan, getPlan, delPlan, addPlan, updatePlan } from '@/api/system/InspectionPlan/index';
import { PlanVO, PlanQuery, PlanForm } from '@/api/system/InspectionPlan/type';
import { numToWeek } from '@/utils/time';

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

interface planlistType extends PlanVO {
  routeNames?: string;
  inspectorNames?: string;
  executeDayNames?: number[];
}

const planList = ref<planlistType[]>([]);
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 planFormRef = ref<ElFormInstance>();

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

const initFormData: PlanForm = {
  id: undefined,
  planName: undefined,
  inspectorIds: undefined,
  executeCycle: undefined,
  taskTime: undefined,
  remindTime: undefined,
  inspectSetting: undefined,
  routeIds: undefined,
  status: undefined,
  remark: undefined,
  executeDay: undefined
};
const data = reactive<PageData<PlanForm, PlanQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planName: undefined,
    inspectorIds: undefined,
    executeCycle: undefined,
    taskTime: undefined,
    remindTime: undefined,
    inspectSetting: undefined,
    routeIds: undefined,
    status: undefined,
    executeDay: undefined,
    params: {}
  },
  rules: {}
});

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

/** 查询巡检计划列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPlan(queryParams.value);
  planList.value = res.rows;
  planList.value.forEach((item) => {
    item.routeNames = item.routeList.map((item) => item.routeName).join(',');
    item.executeDayNames = item.executeDay
      .split(',')
      .sort((a, b) => Number(a) - Number(b))
      .map((item) => Number(item));
  });
  total.value = res.total;
  loading.value = false;
};

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

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

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: PlanVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const router = useRouter();
/** 新增按钮操作 */
const handleAdd = () => {
  router.push({
    path: '/inspection/addPlan'
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: PlanVO) => {
  router.push({
    path: '/inspection/editPlan',
    query: {
      id: row.id
    }
  });
};

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

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

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

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