<template>
  <div>
    <DarkLayout :query-form="queryForm">
      <!-- 查询表单插槽 -->
      <template #query-form>
        <el-form-item label="方案名称">
          <el-input
            v-model="queryForm.taskName"
            placeholder="请输入方案名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="方案代号">
          <el-input
            v-model="queryForm.taskCode"
            placeholder="请输入任务代号"
            clearable
          />
        </el-form-item>
      </template>

      <!-- Header右侧操作按钮 -->
      <template #header-actions>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button class="blue-btn" @click="resetQuery">重置</el-button>
        <el-button class="blue-btn" @click="handleAdd">新增</el-button>
      </template>

      <!-- 主要内容 -->
      <template #main>
        <OverallCard
          v-if="plans.length > 0"
          v-for="plan in plans"
          :key="plan.id"
          :plan="plan"
          @view-detail="handleViewDetail"
          @export-plan="handleExportPlan"
          @link-to="(val) => linkTo(val, plan)"
        />
        <el-empty v-else description="暂无方案数据" />
      </template>

      <!-- 底部右侧分页 -->
      <template #footer-actions>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </template>

    </DarkLayout>

    <!-- 干扰方案上传弹窗 -->
    <DarkDialog
        :visible.sync="showInteUpload"
        title="上传干扰方案"
        width="50%">
      <el-upload
          class="upload-demo"
          ref="inteUpload"
          action="#"
          :file-list="inteFileList"
          accept=".doc,.docx,.pdf,.xlsx,.xls"
          :auto-upload="false"
          :on-change="handleInteFileChange"
          :limit="1"
      >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitInteUpload">
          上传到服务器
        </el-button>
        <div slot="tip" class="el-upload__tip">
          只能上传doc、docx、pdf、xlsx、xls格式的文件
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showInteUpload = false">取消</el-button>
      </span>
    </DarkDialog>

    <!-- 靶标方案上传弹窗 -->
    <DarkDialog
        :visible.sync="showTargetUpload"
        title="上传靶标方案"
        width="50%">
      <el-upload
          class="upload-demo"
          ref="targetUpload"
          action="#"
          :file-list="targetFileList"
          accept=".doc,.docx,.pdf,.xlsx,.xls"
          :auto-upload="false"
          :on-change="handleTargetFileChange"
          :limit="1"
      >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitTargetUpload">
          上传到服务器
        </el-button>
        <div slot="tip" class="el-upload__tip">
          只能上传doc、docx、pdf、xlsx、xls格式的文件
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showTargetUpload = false">取消</el-button>
      </span>
    </DarkDialog>
    <!-- 任务详情弹窗 -->
    <DarkDialog title="任务详情"
                :visible.sync="dialogVisible"
                width="50%"
                :before-close="handleClose">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="方案名称">{{ currentPlan.planName }}</el-descriptions-item>
        <el-descriptions-item label="任务名称">{{ currentPlan.taskName }}</el-descriptions-item>
        <el-descriptions-item label="任务代号">{{ currentPlan.taskCode }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ currentPlan.startTime }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ currentPlan.endTime }}</el-descriptions-item>
        <el-descriptions-item label="编制状态">{{ currentPlan.compileStatus }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ currentPlan.status }}</el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </DarkDialog>

  </div>
</template>

<script>
import DarkLayout from '@/components/GlobalComponents/DarkLayout.vue'
import InterferenceCard from '@/components/Components/InterferenceCard.vue'
import DarkDialog from "@/components/Components/DarkDialog.vue";
import {
  planningSchemePage,
  planningSchemeUpdate, planningSchemeUpdateInte,
  planningSchemeUpdateTarget,
  planningSchemeUploadTarget
} from "@/api/planningScheme";
import {exportSolutionToWord} from "@/views/planningSchem/comprehensive/wordExporter";
import { baseURL,contentType,tokenName } from "@/config";
import store from "@/store";
import {doUpload} from "@/api/tool/ossTool";

export default {
  components: {
    DarkDialog,
    DarkLayout,
    InterferenceCard
  },
  data() {
    return {
      tableData: [
        {
          date: '2023-06-01',
          name: '张三',
          address: '北京市海淀区'
        },
        {
          date: '2023-06-02',
          name: '李四',
          address: '上海市浦东新区'
        }
      ],
      dialogVisible: false,
      currentPlan: {}, // 当前选中的任务数据
      queryForm: {
        taskName: '',
        taskCode: ''
      },
      plans:[],
      planss: [
        {
          id: '1',
          fightAway:"对陆",
          planName: '新型导弹打击试验',
          taskName: '新型导弹打击试验',
          taskCode: 'TASK-2023-001',
          startTime: '2023-01-01',
          endTime: '2023-12-31',
          status: '有效',
          interferenceSchemeStatus: '已导入',
          measurementSchemeStatus: '已编制',
          targetSchemeStatus: '已导入',
          version: 'V1.0.0'
        },
        {
          id: '2',
          fightAway:"对陆",
          planName: '电子对抗演练',
          taskName: '电子对抗演练',
          taskCode: 'TASK-2023-002',
          startTime: '2023-02-01',
          endTime: '2023-11-30',
          status: '待审核',
          interferenceSchemeStatus: '已导入',
          measurementSchemeStatus: '已编制',
          targetSchemeStatus: '未导入',
          version: 'V1.1.0'
        },
        {
          id: '4',
          fightAway:"对陆",
          planName: '电子对抗演练',
          taskName: '电子对抗演练',
          taskCode: 'TASK-2023-003',
          startTime: '2023-03-01',
          endTime: '2023-10-31',
          status: '草稿',
          interferenceSchemeStatus: '未导入',
          measurementSchemeStatus: '未编制',
          targetSchemeStatus: '未导入',
          version: 'V0.9.0'
        },

        {
          id: '3',
          fightAway:"对陆",
          planName: '新型导弹打击试验',
          taskName: '新型导弹打击试验',
          taskCode: 'TASK-2023-003',
          startTime: '2023-03-01',
          endTime: '2023-10-31',
          status: '草稿',
          interferenceSchemeStatus: '已导入',
          measurementSchemeStatus: '未编制',
          targetSchemeStatus: '未导入',
          version: 'V0.9.0'
        },
        {
          id: '9',
          fightAway:"对陆",
          planName: '电子对抗演练',
          taskName: '电子对抗演练',
          taskCode: 'TASK-2023-001',
          startTime: '2023-01-01',
          endTime: '2023-12-31',
          status: '有效',
          interferenceSchemeStatus: '已导入',
          measurementSchemeStatus: '已编制',
          targetSchemeStatus: '未导入',
          version: 'V1.0.0'
        },
      ],
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      selectPlan:null,
      showAdvancedSearch: false,
      showInteUpload: false,    // 干扰方案上传弹窗
      showTargetUpload: false,  // 靶标方案上传弹窗
      inteFileList: [],         // 干扰方案文件列表
      targetFileList: []        // 靶标方案文件列表
    }
  },
  mounted() {
    this.handleQuery();
  },
  methods: {

    // 页面导航方法
    navigateTo(type, isOk) {
      if (type === "inte") {
        console.log("跳转至干扰方案", {isOk})
        this.$router.push({path: "/childPlan/intePlan", query: {isOk}})
      } else if (type === "target") {
        this.$router.push({path: "/childPlan/targetPlan", query: {isOk}})
      }
    },

    // 干扰方案上传成功处理
    async handleInteUploadSuccess(response, file, fileList) {
      if(response.code !==200){
        this.$message.success('干扰方案上传失败');
        return;
      }
      this.$message.success('干扰方案上传成功');

      const fileJson = JSON.stringify(
          fileList.map(item => ({
            fileName: item.name,
            fileHttp: item.response?.data?.url || '',
            fileType: item.response?.data?.type || '',
            type: 1
          })).filter(item => item.fileHttp)
      );

      try {
        await planningSchemeUpdate({
          id: this.selectPlan.id,
          interferenceSchemeStatus: '已导入',
          schemeSubPlan: fileJson
        });

        this.showInteUpload = false;
        this.inteFileList = [];
        this.handleQuery();
      } catch (err) {
        console.error('更新方案失败:', err);
        this.$message.error('方案更新失败');
      }
    },



    // 靶标方案上传成功处理
    async handleTargetUploadSuccess(response, file, fileList) {
      if(response.code !==200){
        this.$message.success('靶标方案上传失败');
        return;
      }
      this.$message.success('靶标方案上传成功');

      // 1. 将 fileList 转为 JSON（和干扰方案保持一致）
      const fileJson = JSON.stringify(
          fileList.map(item => ({
            fileName: item.name,
            fileHttp: item.response?.data?.url || '',
            fileType: item.response?.data?.type || '',
            type: 2
          })).filter(item => item.fileHttp) // 过滤掉上传失败的文件
      );

      try {
        // 2. 调用 API 更新靶标方案
        await planningSchemeUpdate({
          id: this.selectPlan.id,
          schemeSubPlan: fileJson
        });

        // 3. 更新 UI 状态
        this.showTargetUpload = false;
        this.targetFileList = [];

        // 4. 刷新数据
        this.handleQuery();
      } catch (err) {
        console.error('靶标方案更新失败:', err);
        this.$message.error('靶标方案保存失败，请重试');
      }
    },

    // 同步干扰方案文件列表
    handleInteFileChange(file, fileList) {
      this.inteFileList = fileList; // ✅ 手动同步
    },

    // 同步靶标方案文件列表
    handleTargetFileChange(file, fileList) {
      this.targetFileList = fileList; // ✅ 手动同步
    },

    // 上传失败处理
    handleUploadError(err, file, fileList) {
      this.$message.error('文件上传失败，请重试');
    },

    /**
     * 合并 schemeSubPlan
     * @param {Array} existingList - 已有的文件列表（解析后的）
     * @param {Object} newFile - 新上传的文件信息 { fileName, fileHttp, fileType, type }
     * @returns {Array} 合并后的列表
     */
    mergeSchemeSubPlan(existingList, newFile) {
      // 1. 先过滤掉同 type 的旧文件（保证每个 type 只有一个）
      const filtered = existingList.filter(item => item.type !== newFile.type);

      // 2. 添加新文件
      return [...filtered, newFile];
    },

    /**
     * 解析 schemeSubPlan 字符串为数组
     * @returns {Array} 解析后的文件列表
     */
    parseSchemeSubPlan() {
      try {
        console.log(this.selectPlan.schemeSubPlan)
        const str = this.selectPlan.schemeSubPlan;
        return str ? JSON.parse(str) : [];
      } catch (error) {
        console.error('解析 schemeSubPlan 失败:', error);
        return [];
      }
    },

    // 提交干扰方案上传
    async submitInteUpload() {
      if (this.inteFileList.length === 0) {
        this.$message.warning('请先选择文件');
        return;
      }

      const formData = new FormData();
      this.inteFileList.forEach(file => {
        if (file.raw) {
          formData.append('files', file.raw);
        }
      });

      try {
        const response = await doUpload(formData);
        if (response.code !== 0) {
          this.$message.error(`上传失败: ${response.msg || '未知错误'}`);
          return;
        }

        // ✅ 1. 构造新文件对象
        const newFile = {
          fileName: this.inteFileList[0].name,
          fileHttp: response.data.fileStoragePath,
          fileType: response.data.suffix,
          type: 1 // 干扰方案
        };

        // ✅ 2. 解析已有数据
        const existingList = this.parseSchemeSubPlan();

        // ✅ 3. 合并
        const mergedList = this.mergeSchemeSubPlan(existingList, newFile);

        // ✅ 4. 转为 JSON 字符串
        const fileJson = JSON.stringify(mergedList);

        // ✅ 5. 更新干扰方案
        await planningSchemeUpdateInte({
          id: this.selectPlan.id,
          schemeSubPlan: fileJson
        });

        // ✅ 6. 成功后清空
        this.showInteUpload = false;
        this.inteFileList = [];
        this.$refs.inteUpload?.clearFiles(); // 注意：是 inteUpload，不是 targetUpload

        // ✅ 7. 刷新
        this.handleQuery();
        this.$message.success('干扰方案上传并更新成功');

      } catch (error) {
        console.error('上传或更新失败:', error);
        this.$message.error('操作失败：' + (error.message || '请重试'));
      }
    },

    // 提交靶标方案上传
    async submitTargetUpload() {
      if (this.targetFileList.length === 0) {
        this.$message.warning('请先选择文件');
        return;
      }

      const formData = new FormData();
      this.targetFileList.forEach(file => {
        if (file.raw) {
          formData.append('files', file.raw);
        }
      });

      try {
        const response = await doUpload(formData);
        if (response.code !== 0) {
          this.$message.error(`上传失败: ${response.msg || '未知错误'}`);
          return;
        }

        // ✅ 1. 构造新文件对象
        const newFile = {
          fileName: this.targetFileList[0].name,
          fileHttp: response.data.fileStoragePath,
          fileType: response.data.suffix,
          type: 2 // 靶标方案
        };

        // ✅ 2. 解析已有数据
        const existingList = this.parseSchemeSubPlan();

        // ✅ 3. 合并
        const mergedList = this.mergeSchemeSubPlan(existingList, newFile);

        // ✅ 4. 转为 JSON 字符串
        const fileJson = JSON.stringify(mergedList);

        // ✅ 5. 更新靶标方案
        await planningSchemeUpdateTarget({
          id: this.selectPlan.id,
          schemeSubPlan: fileJson
        });

        // ✅ 6. 成功后清空
        this.showTargetUpload = false;
        this.targetFileList = [];
        this.$refs.targetUpload?.clearFiles();

        // ✅ 7. 刷新
        this.handleQuery();
        this.$message.success('靶标方案上传并更新成功');

      } catch (error) {
        console.error('上传或更新失败:', error);
        this.$message.error('操作失败：' + (error.message || '请重试'));
      }
    },

    handleClose(done) {
      done();
    },

    handleViewDetail(plan) {
      this.$router.push({ path: '/planningSchem/overallPlanDesign',query:{batchId:plan.batchId} })
    },
    //导出
    async handleExportPlan(plan) {
      try {
        await exportSolutionToWord(plan.batchId);
        this.$message.success('导出Word成功');
      } catch (error) {
        this.$message.error(error.message || '导出Word失败');
      }
      // this.$message.success("导出成功！")
    },
    // 子方案跳转，增加plan参数用于获取方案状态
    linkTo(val, plan) {
      console.log('linkTo参数:', val, '方案状态:', plan)
      // 根据不同类型和状态判断显示上传还是跳转
      if (val.type === "inte" && plan.interferenceSchemeStatus === '未导入') {
        console.log("干扰方案未导入，显示上传组件")
        this.selectPlan = plan;
        this.showInteUpload = true;
      } else if (val.type === "target" && plan.targetSchemeStatus === '未导入') {
        console.log("靶标方案未导入，显示上传组件")
        this.selectPlan = plan;
        this.showTargetUpload = true;
      } else if (val.type === "meas") {
        this.$router.push({path: "/childPlan/measPlan", query: {val, plan}})
      } else {
        // 已导入/已编制状态正常跳转
        this.navigateTo(val.type, val.isOk);
      }
    },

    async handleQuery() {
      // 查询逻辑
      const res = await planningSchemePage({
        ...this.queryForm,
        pageNo:this.pagination.currentPage,
        pageSize:this.pagination.pageSize,
      })
      this.plans = res.data.records
      this.pagination.total = res.data.total
    },
    resetQuery() {
      this.queryForm = {
        taskName: '',
        taskCode: ''
      }
      this.handleQuery()
    },
    handleAdd() {
      this.$router.push({path: '/childPlans/associationTask'})
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchData()
    },
    fetchData() {
      // 获取数据逻辑
    }
  }
}
</script>

<style scoped>

</style>
