<template>
  <div>
    <!--顶部卡片-->
    <el-card style="max-width: 100vw;margin: 1.5vw;">
      <template #header>
        <div class="card-header">
          <span>子系统{{projectId}}</span>
        </div>
      </template>
      <div style="display: flex; gap: 100px">
        <el-input
            style="width: 550px"
            placeholder="请输入"
            v-model="searchData.name"

        >
          <template #prepend>名称</template>
        </el-input>
        <el-input
            style="width: 550px"
            placeholder="请输入"
        >
          <template #prepend>状态</template>
        </el-input>
        <div>
          <el-button-group>
            <el-button type="primary" @click="SearchSystemByName()">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="reset()">
              <el-icon><RefreshRight /></el-icon>
              重置
            </el-button>
          </el-button-group>
        </div>
      </div>
      <template #footer>Footer content</template>
    </el-card>
    <!--表格卡片-->
    <el-card  style="max-width: 100vw;margin: 1.5vw;">
      <template #header>
        <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
          <span>子系统列表</span>
          <div style="display: flex;">
            <el-button type="primary" @click="toggleAddDialog()">
              <el-icon><Plus /></el-icon>
              新增
            </el-button>
            <el-button type="danger" @click="toggleMulDeleteDialog()">
              <el-icon><DeleteFilled /></el-icon>
              删除
            </el-button>
          </div>
        </div>
      </template>

      <!--表格内容-->
      <el-table :data="tableData" ref="multipleTableRef" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="序号">
          <template v-slot="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name"  label="子系统名称">
          <template v-slot="{row}">
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="workLoad" label="工作量">
          <template v-slot="{row}">
            <span>{{ row.workLoad}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="cycle" label="周期">
          <template v-slot="{row}">
            <span>{{ row.cycle }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="principalName" label="负责人">
          <template v-slot="{row}">
            <span>{{ row.principalName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template v-slot="{row}">
            <span>{{ row.status }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="子系统简介">
          <template v-slot="{row}">
            <span>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="deadLine" label="截止时间">
          <template v-slot="{row}">
            <span>{{ row.deadLine }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="{ row }">
            <div style="display: flex; justify-content: flex-start; margin-bottom: 4px;">
              <el-button link type="primary" size="small" @click="toggleEditDialog(row)">编辑</el-button>
              <el-button link type="primary" size="small" @click="toggleDeleteDialog(row)">删除</el-button>
            </div>
            <div style="margin-bottom: 4px">
              <el-button link type="primary" size="small" @click="toggleAppointDialog(row)">指定子系统负责人</el-button>
            </div>
            <div style="margin-bottom: 4px">
              <el-button link type="primary" size="small" @click="toChildModule(row.id)">查看详情</el-button>
            </div>
          </template>
        </el-table-column>

      </el-table>

      <!--分页-->
      <div style="display: flex; justify-content: center;margin-top: 2vh">
        <el-pagination
            background
            layout="prev, pager, next"
        />
      </div>
    </el-card>

    <!--新增子系统对话框-->
    <el-dialog v-model="AddDialogVisible" title="新增子系统" width="500">
      <el-form label-width="auto" style="max-width: 600px">
        <el-form-item
            label="子系统名称"
            :rules="{
              required: true,
              message: 'domain can not be null',
              trigger: 'blur',
            }"
        >
          <el-input v-model="AddFormData.name"/>
        </el-form-item>
        <el-row>
          <el-col :span="15">
            <el-form-item
                label="截止时间"
                :rules="{
                required: true,
                message: 'domain can not be null',
                trigger: 'blur',
          }"
            >
              <div class="block">
                <el-date-picker
                    type="date"
                    placeholder="选择"
                    v-model="AddFormData.deadLine"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item
                label="周期"
                :rules="{
                required: true,
                message: 'domain can not be null',
                trigger: 'blur',
          }"
            >
              <el-input  v-model="AddFormData.cycle"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
                label="负责人id"
                :rules="{
            message: 'domain can not be null',
            trigger: 'blur',
          }"
            >
              <el-input v-model="AddFormData.principalId"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
                label="项目id"
                :rules="{
            message: 'domain can not be null',
            trigger: 'blur',
          }"
            >
              <el-input  v-model="AddFormData.projectId" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
                label="工作量"
                :rules="{
                required: true,
                message: 'domain can not be null',
                trigger: 'blur',
          }"
            >
              <el-input  v-model="AddFormData.workLoad"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
                label="状态"
                :rules="{
                  required: true,
                  trigger: 'blur',
          }"
            >
              <el-select v-model="AddFormData.status">
                <el-option value="未开始">未开始</el-option>
                <el-option value="进行中">进行中</el-option>
                <el-option value="已完成">已完成</el-option>
                <el-option value="已暂停">已暂停</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item
            label="描述"
            :rules="{
            trigger: 'blur',
          }"
        >
          <el-input type="textarea" v-model="AddFormData.description"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="CancelAdd()">取消</el-button>
          <el-button type="primary" @click="addChildSystem() ">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!--删除多个子系统对话框-->
    <el-dialog
        title="删除子系统"
        width="450"
        align-center
        v-model="DeleteMulDialogVisible"
    >
      <span>确认删除该项目吗?</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="deleteMulChildSystem()">删除</el-button>
          <el-button @click="CancelMulDelete()">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--删除单个子系统对话框-->
    <el-dialog
        title="删除子系统"
        width="450"
        align-center
        v-model="DeleteDialogVisible"
    >
      <span>确认删除该子系统吗?</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="deleteChildSystem()">删除</el-button>
          <el-button @click="CancelDelete()">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--编辑子系统对话框-->
    <el-dialog v-model="EditDialogVisible" title="编辑子系统" width="500">
      <el-form label-width="auto" style="max-width: 600px">
        <el-form-item
            label="子系统名称"
            :rules="{
              required: true,
              message: 'domain can not be null',
              trigger: 'blur',
            }"
        >
          <el-input v-model="EditFormData.name"/>
        </el-form-item>
        <el-row>
          <el-col :span="15">
            <el-form-item
                label="截止时间"
                :rules="{
                required: true,
                message: 'domain can not be null',
                trigger: 'blur',
          }"
            >
              <div class="block">
                <el-date-picker
                    type="date"
                    placeholder="选择"
                    v-model="EditFormData.deadLine"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item
                label="周期"
                :rules="{
         required: true,
        trigger: 'blur',
      }"
            >
              <el-input v-model="EditFormData.cycle"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item
                  label="工作量"
                  :rules="{
            required: true,
            trigger: 'blur',
          }"
              >
                <el-input v-model="EditFormData.workLoad"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                  label="状态"
                  :rules="{
                  required: true,
                  message: 'Please select a status',
                  trigger: 'blur',
          }"
              >
                <el-select v-model="EditFormData.status">
                  <el-option value="未开始">未开始</el-option>
                  <el-option value="进行中">进行中</el-option>
                  <el-option value="已完成">已完成</el-option>
                  <el-option value="已暂停">已暂停</el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item
            label="描述"
            :rules="{
            message: 'domain can not be null',
            trigger: 'blur',
          }"
        >
          <el-input type="textarea" v-model="EditFormData.description"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="CancelEdit()">取消</el-button>
          <el-button type="primary" @click="editChildSystem()">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!--指定子系统负责人对话框-->
    <el-dialog v-model="AppointDialogVisible" title="指定子系统负责人">
      <el-table :data="[currentRowData]" style="width: 100%">
        <el-table-column prop="id" label="序号"></el-table-column>
        <el-table-column prop="principalName" label="子系统负责人"></el-table-column>
        <el-table-column label="选择新负责人">
          <el-select v-model="selectedPrincipal" placeholder="请选择子系统负责人">
            <el-option v-for="option in appointOptions.option" :value="option.username">
              {{option.username}}
            </el-option>
          </el-select>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="CancelAppoint()">取消</el-button>
          <el-button type="primary" @click="confirmAppointment()">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import {
  AddChildSystem,
  DeleteChildSystem,
  DeleteProject,
  EditChildSystem, EditProject, GetAppointOptions,
  GetChildSysById,
  GetProjectByName
} from '@/api/project';
import { getToken } from '@/utils/auth';
import { DeleteFilled, Plus, RefreshRight, Search } from '@element-plus/icons-vue';
import router from '@/router';
import { ElButton, ElMessage, ElTableColumn } from 'element-plus'; // 确保导入你的 API 函数

const listLoading = ref(false);
const AddDialogVisible = ref(false);
const DeleteDialogVisible = ref(false);
const DeleteMulDialogVisible = ref(false);
const EditDialogVisible = ref(false);
const AppointDialogVisible = ref(false);
const tableData = ref([]);
const token = getToken();
const searchData = reactive({ name:'', });
const editId = reactive({ id:'', })
const deleteDatas = reactive({ ids: '' });
const deleteData = reactive({ id: '' });
const currentRowData = ref([]);
let appointOptions = reactive({option:''});
const selectedPrincipal = ref('');


//获取项目id
const route = useRoute();
const projectId = route.query.projectId

const AddFormData = reactive({
  deadLine:'',
  name: '',
  status: '',
  description: '',
  principalId: '',
  projectId:projectId,
  cycle: '',
  workLoad: '',
});

const EditFormData = reactive({
  name:'',
  description:'',
  principalId:'',
  workLoad:'',
  status:'',
  deadLine:'',
  cycle:'',
})

//跳转到子模块
const toChildModule = (systemId) => {
  router.push({ name: 'ChildModCharge', query: { systemId: systemId } });//目前只有4有数据
};


//根据项目id获取子系统
  async function getChildSysById(){
  if (projectId) {
    try {
      const response = await  GetChildSysById(projectId, token);
      tableData.value = response.data;
    } catch (error) {
      console.error('获取子系统数据失败:', error);
    }
  }
};

//查询子系统
async function SearchSystemByName() {
  try {
    const response = await GetProjectByName(searchData.name, token);
    if (response.data) {
      tableData.value = response.data;
    } else {
      console.error("未获取到预期数据，响应内容:", response);
    }
  } finally {
    listLoading.value = false;
  }
}




//新增子系统
function toggleAddDialog() {
  AddFormData.projectId = projectId;
  AddDialogVisible.value = !AddDialogVisible.value;
}

async function addChildSystem() {
  try {
    const res = await AddChildSystem(AddFormData, token);
    if (res.code===200) {
      listLoading.value = true;
      ElMessage({
        message: '新增成功',
        type: 'success',
      })
      getChildSysById();
    } else {
      console.error("未获取到预期数据，响应内容:", res);
    }
  } finally {
    listLoading.value = false;
    AddDialogVisible.value = false;
  }
}

function CancelAdd() {
  AddDialogVisible.value = false;
}

//删除多个子系统
function handleSelectionChange(selection) {
  deleteDatas.ids = selection.map(item => item.id);
}

function toggleMulDeleteDialog() {
  if (deleteDatas.ids.length === 0) {
    ElMessage({
      message: '请选择要删除的子系统',
      type: 'warning',
      duration: 2500
    });
  } else {
    DeleteMulDialogVisible.value = true;
  }
}

async function deleteMulChildSystem() {
  try {
    const res = await DeleteChildSystem(deleteDatas.ids, token);
    if (res.code === 200) {
      ElMessage({
        message: '删除成功',
        type: 'success',
      });
      console.log("多个子系统删除成功");
      DeleteMulDialogVisible.value = false;
      getChildSysById();
    } else {
      console.error("'多个子系统删除失败:", res);
    }
  } finally {
    listLoading.value = false;
  }
}

function CancelMulDelete() {
  DeleteMulDialogVisible.value = false;
}

//删除单个子系统
function toggleDeleteDialog(row) {
  deleteData.id = row.id;
  DeleteDialogVisible.value = true;
}


async function deleteChildSystem() {
  try {
    const res = await DeleteChildSystem(deleteData.id, token);
    if (res.code === 200) {
      ElMessage({
        message: '删除成功',
        type: 'success',
      });
      console.log("单个子系统删除成功");
      DeleteDialogVisible.value = false;
      getChildSysById();
    } else {
      console.error("单个子系统删除失败:", res);
    }
  } finally {
    listLoading.value = false;
  }
}

function CancelDelete() {
  DeleteDialogVisible.value = false;
}


//编辑子系统
function toggleEditDialog(row) {
  EditFormData.name = row.name;
  EditFormData.description = row.description;
  EditFormData.status = row.status;
  EditFormData.workLoad = row.workLoad;
  EditFormData.deadLine = row.deadLine;
  EditFormData.cycle = row.cycle;
  editId.id = row.id
  EditDialogVisible.value = true;  // 显示编辑对话框
}

function CancelEdit() {
  EditDialogVisible.value = false;
}

async function editChildSystem() {
  try {
    const response = await EditChildSystem(editId, EditFormData, token);
    if (response.code === 200) {
      EditDialogVisible.value = false;
      listLoading.value = true;
      getChildSysById();
      ElMessage({
        message: '编辑成功',
        type: 'success',
      });
    } else {
      console.error("编辑失败，响应内容:", response);
    }
  } finally {
    listLoading.value = false;
    AddDialogVisible.value = false;
  }
}

function reset() {
  searchData.name = '';
  getChildSysById();
}

//指定子系统负责人
async function getAppointOptions() {
  try {
    const response = await GetAppointOptions(token);
    if (response.code === 200) {
      appointOptions.option = response.data;
    } else {
      console.error("无数据");
    }
  } catch (error) {
    console.error('Error fetching status options:', error);
  }
};

function toggleAppointDialog(row) {
  currentRowData.value = row;
  AppointDialogVisible.value = true;
  editId.id = row.id
}

//TODO 指定负责人id，我写死了，你替换为选择的负责人就行了
const principalUser = reactive({
  principalId: selectedPrincipal.value
})

async function confirmAppointment() {
  console.log("指定新负责人:", selectedPrincipal.value);
  //TODO 项目id，我也写死了。你自行修改
  //editId.id = '27'
  const response = await EditChildSystem(editId, principalUser, token);
  console.log("指定负责人Result:", response);

  if (response.code===200){
    AppointDialogVisible.value = false;
    ElMessage({
      message: '子系统负责人更新成功',
      type: 'success',
      duration: 3000
    });
    getChildSysById();
  } else {
    ElMessage({
      message:'子系统负责人更新失败',
      type: 'warning',
      duration: 3000
    })
  }
}


function CancelAppoint() {
  AppointDialogVisible.value = false;
}

onMounted(async () => {
  await  getChildSysById();
  await getAppointOptions();
});

</script>

