<template>
  <div class="app-container">
    <transition name="fade">
      <div v-show="showSearch" class="mb-[10px]">
        <el-form ref="queryFormRef" :model="planForm" :inline="true">
          <el-form-item style="width: 200px" label="预案类型：" prop="planType" label-width="auto">
            <el-select v-model="planForm.planType" placeholder="全部" clearable>
              <el-option v-for="item in plan_type" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布日期：" prop="publish_date" label-width="auto">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-input v-model="planForm.keywords" placeholder="请输入预案名称/编制单位" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          </el-form-item>
          <el-form-item>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete(selectedRow)">删除</el-button>
      </el-col>
      <!--      <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>-->
    </el-row>

    <!-- 表格组件 -->
    <el-table v-loading="loading" :data="demoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="预案编号" align="center" prop="planId" />
      <el-table-column label="预案名称" align="center" prop="planName" />
      <el-table-column label="预案类型" align="center" prop="planType">
        <template #default="scope">
          <dict-tag :options="plan_type" :value="scope.row.planType" />
        </template>
      </el-table-column>
      <el-table-column label="发文字号" align="center" prop="document" />
      <el-table-column label="编制单位" align="center" prop="organizingUnit" />
      <el-table-column label="发布日期" align="center" prop="publishDate" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-text v-hasPermi="['system:menu:View']" class="common-btn-text-primary" @click="handleView(scope.row)">查看</el-text>
          <el-text v-hasPermi="['system:menu:edit']" class="common-btn-text-primary" @click="handleUpdate(scope.row)">修改</el-text>
          <el-text v-hasPermi="['system:menu:remove']" class="common-btn-text-danger" @click="handleDelete(scope.row)">删除</el-text>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:page="planForm.page" v-model:limit="planForm.pageSize" :total="total" @pagination="getList" />

    <!-- 新增/修改弹窗 -->
    <div v-show="dialog.visible" class="common-dialog">
      <div class="common-dialog-content">
        <div class="common-dialog-title-box">
          <i class="common-dialog-title-icon" />
          <div>{{ dialog.title }}</div>
        </div>
        <div class="common-dialog-box">
          <el-form ref="demoFormRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="预案名称：" prop="planName">
              <el-input v-model="form.planName" placeholder="请输入预案名称" />
            </el-form-item>
            <el-form-item label="预案类型：" prop="planType">
              <el-select v-model="form.planType" placeholder="请选择预案类型" clearable>
                <el-option v-for="item in plan_type" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="发布日期：" prop="publishDate">
              <el-date-picker v-model="form.publishDate" type="date" placeholder="选择发布日期" value-format="YYYY-MM-DD"></el-date-picker>
            </el-form-item>
            <el-form-item label="编制单位：" prop="organizingUnit">
              <el-input v-model="form.organizingUnit" placeholder="请输入编制单位" />
            </el-form-item>
            <el-form-item label="发文字号：" prop="document">
              <el-input v-model="form.document" placeholder="请输入发文字号" />
            </el-form-item>
            <el-form-item label="事件类型：" prop="event_type">
              <el-select v-model="form.event_type" placeholder="请输入对应事件类型" clearable>
                <el-option v-for="item in mm_event_type" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="预案附件：" prop="fileList">
              <file-upload v-model="form.fileList"  fileSize="15"/>
            </el-form-item>
          </el-form>
        </div>
        <div class="common-dialog-footer" style="display: flex; justify-content: center">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, toRefs } from 'vue';
import { PlanForm, PlanVO } from '@/api/system/user/types';
import { getDicts } from '@/api/system/dict/data';
import { useRouter } from 'vue-router';
import { getPlanDetail, getPlanList, updateReport, deletePlan, addReport } from '@/api/riskPrevention/planManage';
import { addDateRange2 } from '@/utils/ruoyi';
import { to } from 'await-to-js';

const router = useRouter();
const demoFormRef = ref(null);
const demoList = ref<PlanVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<string[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const selectedRow = ref<PlanVO | null>(null);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { mm_event_type, plan_type } = toRefs<any>(proxy?.useDict('plan_type', 'mm_event_type'));

const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const planForm = reactive<PlanForm>({
  page: 1,
  pageSize: 10,
  planType: '',
  keywords: ''
});

let form = ref({
  planId: '',
  planName: '',
  planType: '',
  document: '',
  organizingUnit: '',
  publishDate: '',
  event_type: '',
  fileList: []
});

const rules = reactive({
  planName: [{ required: true, message: '预案名称不能为空', trigger: 'blur' }],
  planType: [{ required: true, message: '预案类型不能为空', trigger: 'blur' }],
  document: [{ required: true, message: '发文字号不能为空', trigger: 'blur' }],
  event_type: [{ required: true, message: '对应事件类型不能为空', trigger: 'blur' }],
  organizingUnit: [{ required: true, message: '编制单位不能为空', trigger: 'blur' }],
  publishDate: [{ required: true, message: '发布日期不能为空', trigger: 'blur' }]
});

const planTypeSelection = ref([]);

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

const getList = async () => {
  loading.value = true;
  const res = await getPlanList(addDateRange2(planForm, dateRange.value));
  loading.value = false;
  demoList.value = res.data;
  total.value = res.total;
};
const handleQuery = () => {
  planForm.page = 1;
  getList();
};

const resetQuery = () => {
  planForm.page = 1;
  planForm.planType = '';
  planForm.keywords = '';
  dateRange.value = ['', ''];
  handleQuery();
};

const handleSelectionChange = (selection: PlanVO[]) => {
  ids.value = selection.map((item) => item.planUid);
  selectedRow.value = selection.length === 1 ? selection[0] : null;
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  resetForm();
  dialog.visible = true;
  dialog.title = '添加预案';
};

const handleUpdate = async (row: PlanVO) => {
  if (row) {
    resetForm();
    const res = await getPlanDetail(row.planId);
    form.value = res.data;
    dialog.visible = true;
    dialog.title = '修改预案';
  }
};

const handleDelete = async (row) => {
  const planUid = row && row.planUid ? [row?.planUid] : ids.value;
  const [err] = await to(proxy?.$modal.confirm('是否确认删除选择的数据项？') as any);
  if (!err) {
    await deletePlan(planUid);
    getList();
    proxy?.$modal.msgSuccess('删除成功');
  }
};

const handleView = (row: PlanVO) => {
  router.push({
    path: '/riskPrevention/planManage/planList',
    query: { planId: row.planId }
  });
};

const submitForm = () => {
  demoFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        buttonLoading.value = true;
        form.value.planId ? await updateReport(form.value) : await addReport(form.value);
        proxy?.$modal.msgSuccess(form.value.planId ? '修改成功' : '新增成功');
        dialog.visible = false;
        getList();
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

const resetForm = () => {
  form.value = {
    planId: '',
    planName: '',
    planType: '',
    document: '',
    organizingUnit: '',
    publishDate: '',
    event_type: ''
  };
  demoFormRef.value?.resetFields();
};

const cancel = () => {
  resetForm();
  dialog.visible = false;
};

onMounted(() => {
  getList();
  getDicts('mm_event_type').then((res) => {
    planTypeSelection.value = res.data;
  });
});
</script>
