<!--任务详情页-->
<template>
  <div class="detail-container">
      <div >
        <div class="common-back-box" @click="goBack">
          <i class="common-back" />
          返回上一级
        </div>
        <div class="common-header">
          <div class="common-header-left">
            <i class="common-title-icon" />
            <template v-if="detailData.type === '0'">
              <div>风险源排查</div>
            </template>
            <template v-if="detailData.type === '1'">
              <div>隐患源排查</div>
            </template>
            <template v-if="detailData.type === '2'">
              <div>危险源排查</div>
            </template>
          </div>
          <div class="common-header-right">
            <el-button class="common-btn-text-primary" type="primary" @click="planUpdate()">
              <i class="edit-icon2" />
              编辑
            </el-button>
            <el-button type="primary" @click="handlefinal">
              <i class="close-icon" />
              完结任务
            </el-button>
            <el-button type="danger" @click="handleDelete"> 删除 </el-button>
          </div>
        </div>
        <div class="common-info-box">
          <div class="common-info-header">
            <i class="line-icon" />
            <div class="common-info-title">基础信息</div>
          </div>
          <div class="common-info-content">
            <div class="common-info-item" >任务编号：{{ detailData.task_number }}</div>
            <div class="common-info-item" >风险源类型：
              <dict-tag :options="risk_type" :value="detailData.type" style="display: inline-block" />
            </div>
            <div class="common-info-item" >创建时间：{{ detailData.create_time }}</div>
            <div class="common-info-item"  >创建人：{{ detailData.create_by }}</div>
            <div class="common-info-item"  >排查时间范围：{{ detailData.task_time }}</div>
            <div class="common-info-item"  >排查周期：
              <dict-tag :options="risk_cycle" :value="detailData.cycle" style="display: inline-block" />
            </div>
            <div class="common-info-item" >排查范围：
              <dict-tag :options="risk_range" :value="detailData.task_range" style="display: inline-block" />
            </div>
            <div class="common-info-item" >任务状态：
              <dict-tag :options="risk_status" :value="detailData.task_status" style="display: inline-block" />
            </div>
          </div>
        </div>
      </div>
    <div class="common-info-box">
      <div class="common-info-header">
        <i class="line-icon" />
        <div class="common-info-title">子任务记录</div>
      </div>
        <el-table ref="multipleTable" v-loading="loading" :data="subtaskData" style="width: 100%">
          <el-table-column label="风险源类型" align="center" prop="type" width="150">
            <template #default="scope">
              <dict-tag :options="risk_type" :value="scope.row.type" style="display: inline-block" />
            </template>
          </el-table-column>
          <el-table-column prop="task_time" label="要求排查时间" width="150" />
          <el-table-column label="排查周期" align="center" prop="cycle" width="150">
            <template #default="scope">
              <dict-tag :options="risk_cycle" :value="scope.row.cycle" style="display: inline-block" />
            </template>
          </el-table-column>
          <el-table-column label="排查范围" align="center" prop="task_range" width="150">
            <template #default="scope">
              <dict-tag :options="risk_range" :value="scope.row.task_range" style="display: inline-block" />
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="执行日期" width="150" />
          <el-table-column prop="completed_num" label="已完成" width="100">
            <template #default="scope">
              <el-text class="common-btn-text-primary" @click="handleCompletedClick(scope.row)">{{ scope.row.completed_num }}</el-text>
            </template>
          </el-table-column>
          <el-table-column prop="incomplete_num" label="未完成" width="100">
            <template #default="scope">
              <el-text class="common-btn-text-primary" @click="handleIncompletedClick(scope.row)">{{ scope.row.incomplete_num }}</el-text>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-text class="common-btn-text-primary" @click="handleResult(scope.row)">巡查结果</el-text>
            </template>
          </el-table-column>
        </el-table>
    </div>
    <!-- 修改弹窗 -->
    <el-dialog v-model="visible" title="修改任务"  class="common-dialog">
      <el-form ref="demoFormRef" :model="form" :rules="rules" label-width="80px">
        <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 v-if="form.cycle === '0'" label="选择时间：" prop="corn_query">
          <el-date-picker v-model="form.corn_query" type="date" placeholder="选择日期时间" value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>
        <el-form-item v-if="form.cycle === '1'" label="选择时间：" prop="corn_query">
          <el-date-picker v-model="form.corn_query" type="month" placeholder="选择日期时间" value-format="MM"></el-date-picker>
        </el-form-item>
        <el-form-item v-if="form.cycle === '2'" label="选择时间：" prop="corn_query">
          <div class="weekday-selector">
            <el-radio-group v-model="form.corn_query">
              <el-radio label="1">周一</el-radio>
              <el-radio label="2">周二</el-radio>
              <el-radio label="3">周三</el-radio>
              <el-radio label="4">周四</el-radio>
              <el-radio label="5">周五</el-radio>
              <el-radio label="6">周六</el-radio>
              <el-radio label="7">周日</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item v-if="form.cycle === '3'" label="选择时间：" prop="corn_query">
          <el-date-picker v-model="form.corn_query" type="datetime" placeholder="选择日期时间" format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
        </el-form-item>
        <el-form-item v-if="form.cycle === '4'" label="选择时间：" prop="corn_query">
          <el-date-picker v-model="form.corn_query" type="datetime" placeholder="选择日期时间" format="HH:mm:ss"></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 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>
    </el-dialog>
  </div>
  <RiskResult v-if="riskResultState.show" :event-id="riskResultState.eventId" @close="handleCancel" />
  <RiskCompleted v-if="risk_completedState.show" :event-id="risk_completedState.eventId" @close="handleCancel" />
  <RiskIncomplete v-if="risk_incompleteState.show" :event-id="risk_incompleteState.eventId" @close="handleCancel" />
</template>

<script setup name="planList" lang="ts">
import { to } from 'await-to-js';
import { ElMessage, ElMessageBox } from 'element-plus';
import { deleteRisk, getRiskDetail, updatetask, getSubtaskList, getSubtaskResultList } from '@/api/inspectionWork/riskManagement';
import { reactive, ref } from 'vue';
import RiskResult from './riskResult.vue';
import RiskCompleted from './risk_completed.vue';
import RiskIncomplete from './risk_incomplete.vue';
const divisionSelectedId = ref(null);
const formattedDivisionData = ref([]);
const onDivisionChange = (value) => {
  // 确认选中的项存在
  const selectedDivision = findNode(formattedDivisionData.value, value);
  if (!selectedDivision) {
    ElMessage.warning('未找到匹配的责任区划。');
    // 将选中的值重置为 null 或空字符串，防止后续逻辑错误
    divisionSelectedId.value = null;
  } else {
    console.log('Selected Division:', selectedDivision); // 调试输出
  }
};
const queryParams = reactive({
  page: 1,
  pageSize: '10',
  inspection_result: '',
  area_code: '',
  nick_name: ''
});
const { page, pageSize } = toRefs(queryParams);
const router = useRouter();
const goBack = () => {
  proxy?.$tab.closePage();
};

const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { risk_type, risk_range, risk_cycle, risk_status, risk_result } = toRefs<any>(
  proxy?.useDict('risk_type', 'risk_range', 'risk_cycle', 'risk_status', 'risk_result')
);
const subtaskData = ref([]);
const SubtaskResultList = ref([]);

//已完成/未完成的页面跳转
const handleClick = (value: number, type: string) => {
  if (type === 'completed') {
    router.push({
      name: 'CompletedDetails', // 替换为实际的路由名称
      params: { value }
    });
  } else if (type === 'uncompleted') {
    router.push({
      name: 'UncompletedDetails', // 替换为实际的路由名称
      params: { value }
    });
  }
};

// 预案编辑
const detailData = ref({
  // id: '',
  type: '',
  start_time: '',
  end_time: '',
  cycle: '',
  corn_query: '',
  task_range: ''
});

let id = ref();
let task_number = ref();
let visible = ref(false);
const demoFormRef = ref(null);
const buttonLoading = ref(false);

let form = ref({
  id: '',
  task_number: '',
  type: '',
  start_time: '',
  end_time: '',
  cycle: '',
  corn_query: '',
  task_range: ''
});
let riskResultState = reactive({
  show: false,
  eventId: ''
});
let risk_completedState = reactive({
  show: false,
  eventId: ''
});
let risk_incompleteState = reactive({
  show: false,
  eventId: ''
});
const handleCancel = () => {
  riskResultState.show = false;
  risk_completedState.show = false;
  risk_incompleteState.show = false;
};
const handleResult = (row) => {
  if (row) {
    riskResultState.eventId = row.id; // 假设eventId是id字段
    riskResultState.show = true;
  }
};
const handleCompletedClick = (row) => {
  if (row) {
    risk_completedState.eventId = row.id; // 假设eventId是id字段
    risk_completedState.show = true;
  }
};
const handleIncompletedClick = (row) => {
  if (row) {
    risk_incompleteState.eventId = row.id; // 假设eventId是id字段
    risk_incompleteState.show = true;
  }
};
/** 编辑按钮操作 */
const planUpdate = async () => {
  resetForm();
  const res = await getRiskDetail(route.query.id);
  form.value = res.data;
  visible.value = true;
};

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

const resetForm = () => {
  form.value = {
    id: '',
    type: '',
    start_time: '',
    end_time: '',
    cycle: '',
    corn_query: '',
    task_range: ''
  };
  demoFormRef.value?.resetFields();
};
/** 删除按钮操作 */
const handleDelete = async () => {
  const [err] = await to(proxy?.$modal.confirm('是否确认删除该条预案？') as any);
  if (!err) {
    await deleteRisk([detailData.value.id]);
    proxy?.$modal.msgSuccess('删除成功');
    router.go(-1);
  }
};
const cancel = () => {
  resetForm();
  visible.value = false;
};

/** 提交修改 */
const submitForm = () => {
  demoFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        buttonLoading.value = true;
        await updatetask(form.value);
        proxy?.$modal.msgSuccess('修改成功');
        visible.value = false;
        getRiskDetail(route.query.id).then((res) => {
          detailData.value = res.data;
        });
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

onMounted(() => {
  task_number.value = route.query.id;
  getRiskDetail(task_number.value).then((res) => {
    detailData.value = res.data;
  });
  getSubtaskList(task_number.value).then((res) => {
    subtaskData.value = res.data;
  });
  // getSubtaskResultList(subtaskData.value[0]?.id).then((res) => {
  //   SubtaskResultList.value = res.data;
  // });
});
</script>

<style lang="scss" scoped>
.clickable-number {
  color: blue;
  cursor: pointer;
}
</style>
