<template>
  <div class="app-container">
    <transition name="fade">
      <div v-show="showSearch" class="mb-[10px]">
        <el-form ref="queryFormRef" :model="riskForm" :inline="true">
          <el-form-item :span="1.5" label="风险源类型：" prop="type" label-width="auto">
            <el-select v-model="riskForm.type" placeholder="全部" clearable>
              <el-option v-for="item in risk_type" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :span="5" label="巡查周期：" prop="risk_cycle" label-width="auto">
            <el-select v-model="riskForm.cycle" placeholder="全部" clearable>
              <el-option v-for="item in risk_cycle" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </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="task_number" />
        <el-table-column label="排查时间范围" align="center" prop="task_time" />
        <el-table-column label="风险源类型" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="risk_type" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="排查周期" align="center" prop="cycle" >
          <template #default="scope">
            <dict-tag :options="risk_cycle" :value="scope.row.cycle" />
          </template>
        </el-table-column>
        <el-table-column label="排查范围" align="center" prop="task_range" >
          <template #default="scope">
            <dict-tag :options="risk_range" :value="scope.row.task_range" />
          </template>
        </el-table-column>
        <el-table-column label="创始人" align="center" prop="create_by" />
        <el-table-column label="创建时间" align="center" prop="create_time" />
        <el-table-column label="任务状态" align="center" prop="task_status" >
          <template #default="scope">
            <dict-tag :options="risk_status" :value="scope.row.task_status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-text   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  class="common-btn-text-primary" @click="handlefinal(scope.row)">完结任务</el-text>
            <el-text  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="riskForm.page" v-model:limit="riskForm.pageSize" :total="total" @pagination="getList" />

    <!-- 新增/修改弹窗 -->
    <div v-if="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"  label-width="100px" :rules="rules">
            <el-form-item label="风险源类型：" prop="type" >
              <el-select v-model="form.type" placeholder="请选择风险源排查类型">
                <el-option
                  v-for="item in risk_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="排查时间范围：" prop="publish">
              <el-date-picker v-model="form.start_time" type="date" placeholder="选择开始日期" value-format="YYYY-MM-DD"></el-date-picker>
              <el-date-picker v-model="form.end_time" type="date" placeholder="选择结束日期" value-format="YYYY-MM-DD"></el-date-picker>
            </el-form-item>
            <el-form-item label="排查周期：" prop="cycle">
              <el-radio-group v-model="form.cycle">
                <el-radio value="0" size="large">每年</el-radio>
                <el-radio value="1" size="large">每月</el-radio>
                <el-radio value="2" size="large">每周</el-radio>
                <el-radio value="3" size="large">每天</el-radio>
                <el-radio value="4" size="large">一次</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item  label="选择时间：" prop="corn_query">
              <el-date-picker v-model="form.corn_query" type="dates" placeholder="选择日期时间"></el-date-picker>
            </el-form-item>
            <el-form-item label="排查范围：" prop="task_range">
              <el-radio-group v-model="form.task_range">
                <el-radio  value="0" size="large">市级</el-radio>
                <el-radio  value="1" size="large">区县级</el-radio>
                <el-radio  value="2" size="large">镇街级</el-radio>
                <el-radio  value="3" size="large">村居级</el-radio>
              </el-radio-group>
            </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 { RiskForm, RiskVO } from '@/api/system/user/riskManagement1';  //PlanForm 转换为：RiskForm PlanVO
import { getDicts } from '@/api/system/dict/data';
import { useRouter } from 'vue-router';
import { addDateRange2 } from '@/utils/ruoyi';
import { to } from 'await-to-js';
import  { ElMessageBox } from 'element-plus';
import {
  addtask,
  deleteRisk,
  getRiskDetail,
  risklist,
  updatetask
} from "@/api/inspectionWork/riskManagement";
import EventDetails from "@/views/duty/eventing/eventDetails.vue";
import EventEditDialog from "@/views/duty/eventing/EventEditDialog.vue";

const router = useRouter();
const demoFormRef = ref(null);
const demoList = ref<RiskVO[]>([]);
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<RiskVO | null>(null);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { risk_cycle, risk_type, risk_range,risk_status } = toRefs<any>(proxy?.useDict('risk_type', 'risk_cycle', 'risk_range', 'risk_status'));
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const rules = reactive({
  type: [{ required: true, message: '风险源类型不能为空', trigger: 'blur' }],
  start_time: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  end_time: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
  cycle: [{ required: true, message: '排查周期不能为空', trigger: 'blur' }],
  corn_query: [{ required: true, message: '下发周期时间不能为空', trigger: 'blur' }],
  task_range: [{ required: true, message: '排查范围不能为空', trigger: 'blur' }]
});


const riskForm = reactive<RiskForm>({  // planForm
  page: 1,
  pageSize: 10,
  type: '',  //plantype 转化了type，风险源类型
  cycle: ''  // keywords转换了cycle
});

let form = ref({
  // task_number: '',
  id: '',
  type: '',
  start_time: '',
  end_time: '',
  cycle: '',
  corn_query: '',
  task_range: ''
});

const handlefinal = async (row) => {
  try {
    const confirmed = await ElMessageBox.confirm('确定要完结任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    if (confirmed) {
      try {
        await updatetask({ id: row.id, task_status: '3' });
        console.log(`任务 ${row.id} 已完结`);
        getList();
      } catch (error) {
        console.error(`任务 ${row.id} 完结失败:`, error);
      }
    } else {
      console.log(`任务 ${row.id} 未完结`);
    }
  } catch (error) {
    console.error('确认对话框处理失败:', error);
  }
};

//获取风险源类型
const riskTypeSelection = ref([]);

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

//调接口获取列表
const getList = async () => {
  loading.value = true;
  const res = await risklist(riskForm);  //调用列表的接口
  loading.value = false;
  demoList.value = res.data;
  total.value = res.total;
};

// 搜索功能
const handleQuery = () => {
  riskForm.page = 1;
  getList();
};
//重置功能
const resetQuery = () => {
  riskForm.page = 1;
  riskForm.type = '';
  riskForm.cycle = '';
  // dateRange.value = ['', ''];
  handleQuery();
};
// 选择行
const handleSelectionChange = (selection: RiskVO[]) => {  // PlanVO 转换为 RiskVO
  ids.value = selection.map((item) => item.riskUid); // planUid 转换为 riskUid
  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: RiskVO) => {
  if (row) {
    resetForm();
    const res = await getRiskDetail(row.id);
    form.value = res.data;
    dialog.visible = true;
    dialog.title = '修改任务';
  }
};
//删除
const handleDelete = async (row) => {
  // debugger
  const riskUid = row && row.id ? [row?.id] : ids.value; //planUid 转换为 riskUid
  const [err] = await to(proxy?.$modal.confirm('是否确认删除选择的数据项？') as any);
  if (!err) {
    await deleteRisk(riskUid);
    getList();
    proxy?.$modal.msgSuccess('删除成功');
  }
};
// 查看详情
const handleView = (row: RiskVO) => {
  router.push({
    path: '/inspectionWork/riskdetails',
    query: { id: row.id }
  });
};
// 提交表单
const submitForm = () => {
  demoFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        buttonLoading.value = true;
        form.value.task_number ? await updatetask(form.value) : await addtask(form.value); //根据 form.value.planId 是否存在，调用 updateReport 或 addReport 方法
        proxy?.$modal.msgSuccess(form.value.task_number ? '修改成功' : '新增成功');
        dialog.visible = false;
        getList();
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};
// 重置表单数据和表单验证状态
const resetForm = () => {
  form.value = {
    // id: '',
    task_number: '',
    type: '',
    start_time: '',
    end_time: '',
    cycle: '',
    corn_query: '',
    task_range: ''
  };
  demoFormRef.value?.resetFields();  // 重置表单的验证状态
};

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


onMounted(() => {
  getList();
  getDicts('risk_type').then((res) => {
    riskTypeSelection.value = res.data;
  });
});

</script>
