<template>
  <div>
    <div v-show="!patrolSubTasksState.show && !patrolTaskAddState.show" class="app-container">
      <div>
        <transition name="fade">
          <div v-show="showSearch">
            <el-form ref="queryFormRef" :model="queryParams">
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="巡查业务：" prop="business" label-width="auto">
                    <el-select v-model="queryParams.business" placeholder="全部" clearable>
                      <el-option v-for="item in businessOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="巡查周期：" prop="cycle" label-width="auto">
                    <el-select v-model="queryParams.cycle" placeholder="全部" clearable>
                      <el-option v-for="item in cycleOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-button type="primary" @click="handleQuery">搜索</el-button>
                  <el-button @click="resetQuery">重置</el-button>
                </el-col>
              </el-row>
            </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 :disabled="multiple" icon="Delete" @click="handleDelete(selectedRow)"> 删除 </el-button>
          </el-col>
        </el-row>
        <!-- 表格组件 -->
        <el-table ref="multipleTable" v-loading="loading" :data="tableData" @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">
            <template #default="scope">
              <el-text type="primary" @click="openPatrolSubTasks(scope.row)">{{ convertStatus(scope.row.business, 'business') }}</el-text>
            </template>
          </el-table-column>
          <el-table-column label="巡查时间范围" width="200" align="center" prop="task_time" />
          <el-table-column label="巡查周期" align="center">
            <template #default="scope">
              {{ convertStatus(scope.row.cycle, 'cycle') }}
            </template>
          </el-table-column>
          <el-table-column label="巡查范围" align="center">
            <template #default="scope">
              {{ convertStatus(scope.row.inspection_range, 'inspection_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">
            <template #default="scope">
              {{ convertStatus(scope.row.task_status, '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="handleUpdate(scope.row)">编辑</el-text>
              <el-text v-if="scope.row.task_status !== '3'" class="common-btn-text-danger" @click="handleWork(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="queryParams.page" v-model:limit="queryParams.pageSize" :total="total" @pagination="tableData" />
      </div>
    </div>
    <PatrolSubTasks v-if="patrolSubTasksState.show" :event-id="patrolSubTasksState.eventId" @close="handleCancel" @refreshsub="fetchWorkrData" />
    <PatrolTaskEdit v-if="patrolTaskEditState.show" :event-id="patrolTaskEditState.eventId" @close="handleCancel" @refresh="fetchWorkrData" />
    <PatrolTaskAdd v-if="patrolTaskAddState.show" @close="handleCancel" @refresh="fetchWorkrData" />
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import PatrolSubTasks from './patrolSubTasks.vue';
import PatrolTaskAdd from './patrolTaskAdd.vue';
import PatrolTaskEdit from './patrolTaskEdit.vue';
import { workList, workDelete, updatetask } from '@/api/inspectionWork/inspector';
import { to } from 'await-to-js';
import { ElMessageBox } from 'element-plus';
const loading = ref(true);
const showSearch = ref(true);
const multiple = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const total = ref(0);
const tableData = ref([]);
const selectedRow = ref<PatrolVO | null>(null);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
export interface PatrolVO {
  task_number: number;
  business: string;
  task_time: string;
  cycle: number;
  id: number;
  inspection_range: number;
  task_status: number;
  create_time: string;
  create_by: string;
}
const initFormData = reactive({
  task_number: '',
  business: '',
  task_time: '',
  cycle: '',
  id: '',
  inspection_range: '',
  task_status: '',
  create_time: '',
  create_by: ''
});
const data = reactive({
  form: { ...initFormData },
  queryParams: {
    page: 1,
    pageSize: 10,
    business: '',
    cycle: ''
  }
});
const { queryParams, form } = toRefs(data);
// 巡查业务选项
const businessOptions = [
  { value: '', label: '全部' },
  { value: '0', label: '城市隐患巡查' },
  { value: '1', label: '森林防火巡查' },
  { value: '2', label: '重点危化企业巡查' },
  { value: '3', label: '重点水库水位巡查' }
];

// 巡查周期选项
const cycleOptions = [
  { value: '', label: '全部' },
  { value: '0', label: '每年' },
  { value: '1', label: '每月' },
  { value: '2', label: '每周' },
  { value: '3', label: '每日' },
  { value: '4', label: '一次' }
];
// 转换状态的方法
function convertStatus(value, type) {
  const statusMapping = {
    business: {
      '0': '城市隐患巡查',
      '1': '森林防火巡查',
      '2': '重点危化企业巡查',
      '3': '重点水库水位巡查'
    },
    cycle: {
      '0': '每年',
      '1': '每月',
      '2': '每周',
      '3': '每日',
      '4': '一次'
    },
    inspection_range: {
      '0': '市级',
      '1': '区县级',
      '2': '镇街级',
      '3': '村居级'
    },
    task_status: {
      '0': '未开始',
      '1': '进行中',
      '2': '未完成',
      '3': '已完结'
    }
  };

  return statusMapping[type]?.[value] || value;
}
let patrolSubTasksState = reactive({
  show: false,
  eventId: ''
});
let patrolTaskAddState = reactive({
  show: false
});
let patrolTaskEditState = reactive({
  show: false,
  eventId: ''
});
const handleCancel = () => {
  patrolSubTasksState.show = false;
  patrolTaskAddState.show = false;
  patrolTaskEditState.show = false;
};
const openPatrolSubTasks = (row) => {
  if (row) {
    patrolSubTasksState.eventId = row.id + ""; // 假设eventId是id字段
    patrolSubTasksState.show = true;
  }
};
const handleAdd = () => {
  patrolTaskAddState.show = true;
};
const handleUpdate = (row) => {
  if (row) {
    patrolTaskEditState.eventId = row.id + ""; // 假设eventId是id字段
    patrolTaskEditState.show = true;
  }
};
const handleDelete = async (row) => {
  let id = [];
  if (row) {
    id = [row.id];
  } else {
    id = ids.value;
  }
  const [err] = await to(proxy?.$modal.confirm('是否确认删除选择的数据项？') as any);
  if (!err) {
    await workDelete(id);
    proxy.$modal.msgSuccess('删除成功');
    fetchWorkrData();
  }
};

const fetchWorkrData = () => {
  loading.value = true;
  workList(queryParams.value)
    .then((res) => {
      tableData.value = res.data;
      total.value = res.total;
    })
    .finally(() => {
      loading.value = false;
    });
};
const handleQuery = () => {
  queryParams.value.page = 1;
  fetchWorkrData();
};
// 重置查询条件
const resetQuery = () => {
  queryParams.value = { page: 1, pageSize: 10, business: '', cycle: '' };
  handleQuery();
};
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  selectedRow.value = selection.length === 1 ? selection[0] : null;
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
const handleWork = 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} 已完结`);
        fetchWorkrData();
      } catch (error) {
        console.error(`任务 ${row.id} 完结失败:`, error);
      }
    } else {
      console.log(`任务 ${row.id} 未完结`);
    }
  } catch (error) {
    console.error('确认对话框处理失败:', error);
  }
};
onMounted(() => {
  fetchWorkrData();
});
</script>
