<template>
  <div class="application-form-container">
    <!-- 表单内容 -->
    <div class="form-content">
      <!-- 只读状态 -->
      <div v-if="!isEditing" class="readonly-form">
        <div class="form-item">
          <label>申请人：</label>
          <div class="readonly-value">{{ form.applicantName }}</div>
        </div>

        <div class="form-item">
          <label>申请日期：</label>
          <div class="readonly-value">{{ form.determineDate }}</div>
        </div>

        <div class="form-item">
          <label>项目开始日期：</label>
          <div class="readonly-value">{{ form.executeDate }}</div>
        </div>

        <div class="form-item">
          <label>项目结束日期：</label>
          <div class="readonly-value">{{ form.harvestDate }}</div>
        </div>

        <div class="form-item">
          <label>主要技术经济目标：</label>
          <div class="readonly-value">{{ form.target }}</div>
        </div>

        <div class="form-item">
          <label>项目主要研究内容：</label>
          <div class="readonly-value" style="white-space: pre-line;">{{ form.content }}</div>
        </div>

        <div class="form-item">
          <label>项目计划任务书：</label>
          <div class="readonly-value">
            <div v-if="form.planFile">{{ form.planFile }}</div>
            <div v-else class="empty-text">未上传</div>
          </div>
        </div>

        <div class="form-item">
          <label>项目立项决议书：</label>
          <div class="readonly-value">
            <div v-if="form.resolutionFile">{{ form.resolutionFile }}</div>
            <div v-else class="empty-text">未上传</div>
          </div>
        </div>
      </div>

      <!-- 编辑状态 -->
      <el-form v-else :model="form" :rules="rules" ref="formRef" label-width="150px" label-position="top">
        <el-form-item label="申请人：" prop="applicantName">
          <el-select v-model="form.applicantName" placeholder="请选择项目负责人" filterable remote
            :remote-method="filterLeaders" :loading="leaderLoading" @change="handleLeaderChange">
            <el-option v-for="item in filteredLeaders" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请日期：" prop="determineDate">
          <el-date-picker v-model="form.determineDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
        </el-form-item>

        <el-form-item label="项目开始日期：" prop="executeDate">
          <el-date-picker v-model="form.executeDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
        </el-form-item>

        <el-form-item label="项目结束日期：" prop="harvestDate">
          <el-date-picker v-model="form.harvestDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
        </el-form-item>

        <el-form-item label="主要技术经济目标：" prop="target">
          <el-select v-model="form.target" placeholder="请选择技术经济目标">
            <el-option v-for="item in technicalGoalOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="项目主要研究内容：" prop="content">
          <el-input v-model="form.content" type="textarea" :rows="8" placeholder="请输入项目主要研究内容" resize="vertical" />
        </el-form-item>

        <el-form-item label="项目计划任务书：" prop="planFile">
          <el-upload :on-preview="(e: any) => $emit('preview', e)" :file-list="taskDocumentList"
            :on-remove="(a: any) => handFileRemove(a)" :before-upload="beforeUpload" class="upload-demo"
            :http-request="(event: any) => handUpload(event)">
            <el-button type="primary">
              <el-icon>
                <Upload />
              </el-icon>
              上传
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                上传证书附件扫描件，支持pdf格式，大小不超过5MB。
              </div>
              <div class="download-link" @click="downloadTemplate">
                <el-icon>
                  <Download />
                </el-icon>
                下载计划任务书模版
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="项目立项决议书：" prop="resolutionDocument">
          <el-upload :on-preview="(e: any) => $emit('preview', e)" :file-list="resolutionDocumentList"
            :on-remove="(a: any) => handFileRemove(a)" :before-upload="beforeUpload" class="upload-demo"
            :http-request="(event: any) => handUpload2(event)">
            <el-button type="primary">
              <el-icon>
                <Upload />
              </el-icon>
              上传
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                上传证书附件扫描件，支持pdf格式，大小不超过5MB。
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>

    <!-- 底部按钮 -->
    <div class="form-actions">
      <el-button v-if="!isEditing" type="primary" @click="startEditing">
        编辑
      </el-button>

      <template v-else>
        <el-button @click="cancelEditing">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload, Download } from '@element-plus/icons-vue'
import { get, update, add } from "@/api/public/basic.js";
import CryptoJS from 'crypto-js';
import { HOST_R } from '@/api/evn';

const props = defineProps({
  projectId: {
    type: String,
    required: true
  }
})
const state = reactive({
  // 弹出层标题
  title: '',
  // 是否显示弹出层
  open: false,
  loading: false,
  // 总条数
  total: 0,
  currentProject: {},
  leaderOptions: [],
  queryParams: {
    // 页码
    pageNum: 1,
    // 每页大小
    pageSize: 10,
    projectId: '',
  },
  queryParamsStaff: {
    // 页码
    pageNum: 1,
    // 每页大小
    pageSize: 10,
  },
  projectIdmain: '',
})
const handleQuery = () => {
  // 清空现有查询参数
  state.queryParams = {
    pageNum: 1,
    pageSize: 10,
    id: [],
    status: '',
    managerName: '',
  };
  state.loading = true;
  const params = state.queryParams;
  state.loading = true;
  // 如果state.queryParams中有空值，则删除
  Object.keys(params).forEach((key) => {
    if (!params[key]) {
      delete params[key];
    }
  });
  // state.queryParams.projecrId=props.projectId
  get(props.projectId, 'i1XuaQDK9zw').then((response: any) => {
    state.currentProject = response.data[0];
    console.log(response.data[0].name)
    console.log(state.currentProject.name + ",,,,,,,,,,," + state.currentProject.code + ",,," + state.currentProject.planFile)
    state.total = response.data.count;
    state.loading = false;
    Object.assign(form, state.currentProject);
  });
};

onMounted(() => {
  state.projectIdmain = props.projectId
  handleQuery()
  hanldAllMembers()
})

const hanldAllMembers = async () => {
  try {
    const response = await get(state.queryParamsStaff, 'i272x8hCGVw')
    state.leaderOptions = response.data.result || []
    totalMembers.value = response.data.count || 0
  } catch (error) {
    ElMessage.error('获取项目成员失败')
    console.error(error)
  }
}
const totalMembers = ref(0)
const handleLeaderChange = (id) => {
  if (id) {
    form.applicantId = id
    form.applicantName = filteredLeaders.value.find((item:any) => item.id === id)?.name || ''
  } else {
    form.applicantId = ''
    form.applicantName = ''
  }
}
// 筛选相关的状态
const leaderLoading = ref(false)
const leaderSearchQuery = ref('')
const filteredLeaders = computed(() => {
  if (!leaderSearchQuery.value) {
    return state.leaderOptions
  }
  return state.leaderOptions.filter(item =>
    item.name.includes(leaderSearchQuery.value) ||
    (item.code && item.code.includes(leaderSearchQuery.value))
  )
})
// 筛选方法
const filterLeaders = (query) => {
  leaderSearchQuery.value = query
}

// 表单数据
const form = reactive({})

// 表单验证规则
const rules = reactive({
  applicantName: [{ required: true, message: '请选择申请人', trigger: 'change' }],
  determineDate: [{ required: true, message: '请选择申请日期', trigger: 'change' }],
  executeDate: [{ required: true, message: '请选择项目开始日期', trigger: 'change' }],
  harvestDate: [{ required: true, message: '请选择项目结束日期', trigger: 'change' }],
  target: [{ required: true, message: '请选择技术经济目标', trigger: 'change' }],
  content: [{ required: true, message: '请输入研究内容', trigger: 'blur' }],
  planFile: [{ required: true, message: '请上传计划任务书', trigger: 'change' }],
  resolutionFile: [{ required: true, message: '请上传立项决议书', trigger: 'change' }]
})


const technicalGoalOptions = ref([
  { value: '科学原理的探索、发现', label: '科学原理的探索、发现' },
  { value: '技术原理的研究', label: '技术原理的研究' },
  { value: '开发全新产品', label: '开发全新产品' },
  { value: '增加产品功能或提高性能', label: '增加产品功能或提高性能' },
  { value: '提高劳动生产率', label: '提高劳动生产率' },
  { value: '减少能源消耗或提高能源使用效率', label: '减少能源消耗或提高能源使用效率' },
  { value: '节约原材料', label: '节约原材料' },
  { value: '减少环境污染', label: '减少环境污染' }
])

// 文件上传
const taskDocumentList = computed(() => {
  return form.planFile ? [{ name: form.planFile }] : [];
});
const resolutionDocumentList = computed(() => {
  return form.resolutionFile ? [{ name: form.resolutionFile }] : [];
});
const handUpload = (event: any) => {
  // 计算hash值
  console.log(event.file.name)
  var reader = new FileReader();
  reader.onload = (e: any) => {
    var fileData = e.target.result;
    var wordArray = CryptoJS.lib.WordArray.create(fileData);
    var hash = CryptoJS.SHA1(wordArray).toString();
    fetch(`/api/upload/${event.file.name}?privacy=0&isFolder=0&parentId=0&signature=${hash}`, {
      method: 'POST',
      body: fileData,
    })
      .then(response => {
        if (!response.ok) {
          throw new Error('文件上传失败！');
        }
        return response.text();
      })
      .then(responseText => {
        const data = JSON.parse(responseText);  // 手动解析 JSON
        console.log('文件 ID：', data.data.id);
        console.log('文件名称：', data.data.name);
        console.log('文件上传成功：', responseText);
        // console.log('文件上传成功：', responseText.data.id);
        // console.log(responseText.id)
        form.planFile = data.data.name
        form.planId = data.data.id
        ElMessage.success('文件上传成功！');
      })
      .catch(error => {
        console.log('文件上传失败4！', error);
      });
  };
  reader.readAsArrayBuffer(event.file);
};
const handUpload2 = (event: any) => {
  // 计算hash值
  console.log(event.file.name)
  var reader = new FileReader();
  reader.onload = (e: any) => {
    var fileData = e.target.result;
    var wordArray = CryptoJS.lib.WordArray.create(fileData);
    var hash = CryptoJS.SHA1(wordArray).toString();
    fetch(`/api/upload/${event.file.name}?privacy=0&isFolder=0&parentId=0&signature=${hash}`, {
      method: 'POST',
      body: fileData,
    })
      .then(response => {
        if (!response.ok) {
          throw new Error('文件上传失败！');
        }
        return response.text();
      })
      .then(responseText => {
        const data = JSON.parse(responseText);  // 手动解析 JSON
        console.log('文件 ID：', data.data.id);
        console.log('文件名称：', data.data.name);
        console.log('文件上传成功：', responseText);
        // console.log('文件上传成功：', responseText.data.id);
        // console.log(responseText.id)
        form.resolutionFile = data.data.name
        form.resolutionId = data.data.id
        ElMessage.success('文件上传成功！');
      })
      .catch(error => {
        console.log('文件上传失败4！', error);
      });
  };
  reader.readAsArrayBuffer(event.file);
};
const handFileRemove = (event: any) => {
  form.planFile = ''
  form.planId = ''
}
const handleTaskDocumentChange = (file, fileList) => {
  console.log('任务书文件：', file);
  form.taskDocument = file
}

const handleResolutionDocumentChange = (file, fileList) => {
  form.resolutionDocument = file
}

const beforeUpload = (file) => {

  const isPDF = file.type === 'application/pdf'
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isPDF) {
    ElMessage.error('只能上传PDF格式的文件!')
  }
  if (!isLt5M) {
    ElMessage.error('文件大小不能超过5MB!')
    return isPDF && isLt5M
  }

}

const downloadTemplate = () => {
  ElMessage.success('开始下载模板文件')
  // 实际项目中这里应该是下载文件的逻辑
  window.open(`${HOST_R}/uploads/项目计划任务书模板.docx`, '_blank')
}
// const downloadPlanfile = () => {
//   if (!form.planFile) {
//     ElMessage.warning('没有可下载的文件');
//     return;
//   }
//
//   const fileName = form.planFile; // 直接获取文件名
//   console.log('文件名：', fileName);
//
//   ElMessage.success('下载开始')
//   window.open(`${HOST_R}/uploads/项目计划任务书模板.pdf`, '_blank') // 模拟下载链接
// }
// 编辑状态
const isEditing = ref(false)
const formRef = ref()

// 方法
const startEditing = () => {
  isEditing.value = true
}

const cancelEditing = () => {
  isEditing.value = false
  // 这里可以添加重置表单的逻辑
}
const formaddmilestone = reactive({})
function getCurrentDateTime() {
  const now = new Date();

  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份补零
  const day = String(now.getDate()).padStart(2, '0'); // 日期补零

  return `${year}-${month}-${day}`;
}
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      update(state.projectIdmain, form, 'i1XuaQDK9zw').then((response) => {
        ElMessage.success('修改成功');
        state.loading = false;
      });
      formaddmilestone.name = '项目开始'
      formaddmilestone.date = form.executeDate
      formaddmilestone.projectId = state.projectIdmain
      await add(formaddmilestone, 'i2xCgpiXXNh');
      formaddmilestone.name = '项目结束'
      formaddmilestone.date = form.harvestDate
      await add(formaddmilestone, 'i2xCgpiXXNh');
      formaddmilestone.name = '今日'
      formaddmilestone.date = getCurrentDateTime()
      await add(formaddmilestone, 'i2xCgpiXXNh');
      handleQuery();
      isEditing.value = false
    } else {
      ElMessage.error('请填写完整信息');
    }
  })
}
</script>

<style scoped>
.application-form-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
  position: relative;
  padding-bottom: 80px;
  /* 为底部按钮留出空间 */
}

.form-content {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.readonly-form {
  padding: 20px;
}

.form-item {
  margin-bottom: 20px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
}

.readonly-value {
  padding: 10px;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-height: 40px;
}

.empty-text {
  color: #c0c4cc;
  font-style: italic;
}

.upload-demo {
  margin-top: 10px;
}

.el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.download-link {
  color: #409eff;
  font-size: 12px;
  margin-top: 5px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
}

.download-link:hover {
  text-decoration: underline;
}

.download-link .el-icon {
  margin-right: 5px;
}

.form-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 15px 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  text-align: center;
  z-index: 1000;
}
</style>
