<script setup>
import { getCurrentInstance, onMounted, ref, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import tools from '@/tools'
const {
  proxy
} = getCurrentInstance()

const projectDictList = ref([])
const caseTypeColumns = ref([])
const caseSourceColumns = ref([])

// 定义生成编号的函数
const generateCode = () => {
  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');
  const formattedDate = `${year}${month}${day}`;
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  const formattedTime = `${hours}${minutes}${seconds}`;
  const sequenceNumber = Math.floor(Math.random() * 1000);
  const paddedSequence = String(sequenceNumber).padStart(3, '0');
  return `XMAL${formattedDate}${formattedTime}${paddedSequence}`;
};

// 获取字典数据
const getProjectDicList = () => {
  tools.dic.getDicList(['sgsafe_project_case_type', 'sgsafe_project_case_source']).then((response => {
    console.log(JSON.stringify(response.data.data))
    projectDictList.value = response.data.data
    
    caseTypeColumns.value = projectDictList.value.sgsafe_project_case_type?.map(item => ({
      text: item.dicName,
      value: item.dicCode
    })) || [];
    
    caseSourceColumns.value = projectDictList.value.sgsafe_project_case_source?.map(item => ({
      text: item.dicName,
      value: item.dicCode
    })) || [];
    
    console.log('案例类型:', caseTypeColumns.value)
  }))
}

const caseTypeFlag = ref(false)
const caseSourceFlag = ref(false)
let title = '新增项目案例'

/* 返回上一级页面 */
const router = useRouter()
const onClickLeft = () => {
  router.go(-1)
}

const guid = () => {
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4())
}

const route = useRoute()
let planInfo = {}
const isEdit = ref(route.query.mark === '1');
const isReadOnly = ref(route.query.readOnly === 'true');
const isCaseSubmitted = computed(() => isReadOnly.value && isEdit.value);
const result = ref('')
const fromVue = ref({})

if (route.query.mark) {
  planInfo = JSON.parse(route.query.mark)
}


// 新增模式
if (planInfo == -1) {
  const caseNumber = generateCode();
  result.value = caseNumber;
  
  fromVue.value = {
    caseNumber: caseNumber,
    projectName: '',
    caseType: '',
    caseSource: '',
    startTime: '',
    endTime: '',
    tags: '',
    caseSummary: '',
    highLights: '',
    resultsValue: '',
    fileId: caseNumber,
    viewCount: '0',
    downloadCount: '0'
  };
  
}

// 编辑模式
if (planInfo == 1) {
  title = '查看项目案例'
  fromVue.value = JSON.parse(route.query.data)
  
  // 清理微秒格式
  if (fromVue.value.startTime && String(fromVue.value.startTime).includes('.')) {
    fromVue.value.startTime = String(fromVue.value.startTime).split('.')[0];
  }
  if (fromVue.value.endTime && String(fromVue.value.endTime).includes('.')) {
    fromVue.value.endTime = String(fromVue.value.endTime).split('.')[0];
  }
  
  // fileId 与 caseNumber 保持一致
  if (!fromVue.value.fileId || fromVue.value.fileId !== fromVue.value.caseNumber) {
    fromVue.value.fileId = fromVue.value.caseNumber;
  }
  result.value = fromVue.value.fileId;
}

// 时间选择器
const showStartTimePicker = ref(false);
const showEndTimePicker = ref(false);
const currentStartDate = ref([2025, 1, 1])
const currentEndDate = ref([2025, 1, 1])
const currentStartTime = ref([0, 0, 0]);
const currentEndTime = ref([0, 0, 0]);
const minDate = ref(new Date(1900, 0, 1));
const maxDate = ref(new Date(2100, 11, 31));

const startDateOrTime = ref(false);
const endDateOrTime = ref(false);

// 开始时间选择
const onStartDateConfirm = () => {
  startDateOrTime.value = true;
};

const onConfirmStartDatetime = () => {
  const year = currentStartDate.value[0];
  const month = currentStartDate.value[1].toString().padStart(2, '0');
  const day = currentStartDate.value[2].toString().padStart(2, '0');
  const hours = currentStartTime.value[0].toString().padStart(2, '0');
  const minutes = currentStartTime.value[1].toString().padStart(2, '0');
  const seconds = currentStartTime.value[2].toString().padStart(2, '0');

  fromVue.value.startTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  showStartTimePicker.value = false;
  startDateOrTime.value = false;
};

const cancelStartDatePicker = () => {
  showStartTimePicker.value = false;
  startDateOrTime.value = false;
};

const cancelStartTimePicker = () => {
  showStartTimePicker.value = false;
  startDateOrTime.value = false;
};

// 结束时间选择
const onEndDateConfirm = () => {
  endDateOrTime.value = true;
};

const onConfirmEndDatetime = () => {
  const year = currentEndDate.value[0];
  const month = currentEndDate.value[1].toString().padStart(2, '0');
  const day = currentEndDate.value[2].toString().padStart(2, '0');
  const hours = currentEndTime.value[0].toString().padStart(2, '0');
  const minutes = currentEndTime.value[1].toString().padStart(2, '0');
  const seconds = currentEndTime.value[2].toString().padStart(2, '0');

  fromVue.value.endTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  showEndTimePicker.value = false;
  endDateOrTime.value = false;
};

const cancelEndDatePicker = () => {
  showEndTimePicker.value = false;
  endDateOrTime.value = false;
};

const cancelEndTimePicker = () => {
  showEndTimePicker.value = false;
  endDateOrTime.value = false;
};

// 标签选择
const addTag = (item) => {
  if (isCaseSubmitted.value) return;
  
  const valueToStore = item.value?.trim() || '';
  if (!valueToStore) return;

  const currentTags = fromVue.value.tags
    ? fromVue.value.tags.split(',').map(t => t.trim()).filter(Boolean)
    : [];

  if (currentTags.includes(valueToStore)) return;

  currentTags.push(valueToStore);
  fromVue.value.tags = currentTags.join(', ');
};

/* 组织树选择 */
import { showFailToast, showLoadingToast, showSuccessToast } from 'vant';

// 保存
const addEmergencyDrillPlan = async () => {
  const loadingToast = showLoadingToast({
    duration: 0,
    message: '加载中',
    forbidClick: true
  })
  
  fromVue.value.fileId = result.value

  var url = '/sgsafe/Manager/saveProject';
  const params = {
    json: JSON.stringify(fromVue.value)
  }
  proxy.$axios.post(url, params).then(res => {
    if (res.data.code === 0 || res.data.code === '0') {
      loadingToast.close()
      showSuccessToast('保存成功')
      onClickLeft()
    } else {
      loadingToast.close()
      showFailToast('操作失败!' + res.data.msg)
    }
  }).catch(error => {
    loadingToast.close()
    showFailToast('保存失败: 网络错误')
    console.error('保存失败:', error)
  })
}

onMounted(() => {
  getProjectDicList()
  const today = new Date()
  const year = today.getFullYear()
  const month = today.getMonth() + 1
  const day = today.getDate()
  currentStartDate.value = [year, month, day]
  currentEndDate.value = [year, month, day]
  currentStartTime.value = [today.getHours(), today.getMinutes(), today.getSeconds()];
  currentEndTime.value = [today.getHours(), today.getMinutes(), today.getSeconds()];
  
  // 如果是编辑模式且有已有的时间，解析并初始化
  if (isEdit.value) {
    if (fromVue.value.startTime) {
      try {
        const timeStr = fromVue.value.startTime;
        const [datePart, timePart] = timeStr.split(' ');
        if (datePart && timePart) {
          const [year, month, day] = datePart.split('-').map(Number);
          const [hours, minutes, seconds] = timePart.split(':').map(Number);
          currentStartDate.value = [year, month, day];
          currentStartTime.value = [hours || 0, minutes || 0, seconds || 0];
        }
      } catch (error) {
        // 解析失败，使用默认值
      }
    }
    
    if (fromVue.value.endTime) {
      try {
        const timeStr = fromVue.value.endTime;
        const [datePart, timePart] = timeStr.split(' ');
        if (datePart && timePart) {
          const [year, month, day] = datePart.split('-').map(Number);
          const [hours, minutes, seconds] = timePart.split(':').map(Number);
          currentEndDate.value = [year, month, day];
          currentEndTime.value = [hours || 0, minutes || 0, seconds || 0];
        }
      } catch (error) {
        // 解析失败，使用默认值
      }
    }
  }
})

/* 文件上传 */
import AttachmentS3 from '@/components/AttachmentS3.vue';

const onSubmit = (values) => {
  addEmergencyDrillPlan()
}

const onCaseTypeConfirm = ({ selectedOptions }) => {
  caseTypeFlag.value = false;
  fromVue.value.caseType = selectedOptions[0].text;
};

const onCaseSourceConfirm = ({ selectedOptions }) => {
  caseSourceFlag.value = false;
  fromVue.value.caseSource = selectedOptions[0].text;
};

</script>

<template>

  <div class="page-container">
    <van-sticky class="header">
      <van-nav-bar
        :title="title"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft" >
      </van-nav-bar>
    </van-sticky>
    <div class="scroll-container">
      <van-form @submit="onSubmit">
        <van-field
            v-model="fromVue.caseNumber"
            label="案例编号"
            name="caseNumber"
            readonly
            :rules="[{required: true, message: '编号生成失败'}]"
        />

        <van-field
          v-model="fromVue.projectName"
          label="项目名称"
          name="projectName"
          :readonly="isCaseSubmitted"
          required
          placeholder="请输入项目名称"
          :rules="[{required: true, message: '请输入项目名称'}]"
        />

        <van-field
          v-model="fromVue.caseType"
          readonly
          label="案例类型"
          name="caseType"
          required
          placeholder="请选择案例类型"
          :rules="[{required: true, message: '请选择案例类型'}]"
          @click="!isCaseSubmitted && (caseTypeFlag = true)"
        />
        
        <van-field
          v-model="fromVue.caseSource"
          readonly
          label="案例来源"
          name="caseSource"
          placeholder="请选择案例来源"
          @click="!isCaseSubmitted && (caseSourceFlag = true)"
        />

        <!-- 开始时间 -->
        <van-field
            v-model="fromVue.startTime"
            is-link
            readonly
            name="startTime"
            label="开始时间"
            :colon="true"
            placeholder="点击选择开始时间"
            @click="!isCaseSubmitted && (showStartTimePicker = true)"
        />

        <!-- 结束时间 -->
        <van-field
            v-model="fromVue.endTime"
            is-link
            readonly
            name="endTime"
            label="结束时间"
            :colon="true"
            placeholder="点击选择结束时间"
            @click="!isCaseSubmitted && (showEndTimePicker = true)"
        />

        <!-- 关键词/标签 -->
        <van-field
            v-model="fromVue.tags"
            label="关键词/标签"
            name="tags"
            placeholder="请手动输入标签，多个标签用逗号分隔"
            :readonly="isCaseSubmitted"
        />
        
        <!-- 标签按钮 -->
        <!-- 整个 van-cell 删除 -->

        <van-field
            v-model="fromVue.caseSummary"
            label="案例摘要"
            name="caseSummary"
            rows="3"
            autosize
            type="textarea"
            placeholder="请输入案例摘要"
            :readonly="isCaseSubmitted"
        />
        
        <van-field
            v-model="fromVue.highLights"
            label="创新点与亮点"
            name="highLights"
            rows="3"
            autosize
            type="textarea"
            placeholder="请输入创新点与亮点"
            :readonly="isCaseSubmitted"
        />
        
        <van-field
            v-model="fromVue.resultsValue"
            label="应用成效与价值"
            name="resultsValue"
            rows="3"
            autosize
            type="textarea"
            placeholder="请输入应用成效与价值"
            :readonly="isCaseSubmitted"
        />

        <van-field label="附件上传" >
          <template #input>
            <AttachmentS3 :f-id="result" :readonly="isCaseSubmitted" />
          </template>
        </van-field>
        
        <div style="margin: 16px;">
          <van-button v-if="!isReadOnly" round block type="primary" native-type="submit">
            {{ isEdit ? '保存' : '提交' }}
          </van-button>
        </div>
      </van-form>

      <!-- 案例类型选择器 -->
      <van-popup v-model:show="caseTypeFlag" round position="bottom">
        <van-picker
            :columns="caseTypeColumns"
            @cancel="caseTypeFlag = false"
            @confirm="onCaseTypeConfirm"
        />
      </van-popup>

      <!-- 案例来源选择器 -->
      <van-popup v-model:show="caseSourceFlag" round position="bottom">
        <van-picker
            :columns="caseSourceColumns"
            @cancel="caseSourceFlag = false"
            @confirm="onCaseSourceConfirm"
        />
      </van-popup>

      <!-- 开始时间选择器 -->
      <van-popup
          v-model:show="showStartTimePicker"
          position="bottom"
          round
          style="max-height: 50vh;"
      >
        <van-date-picker
            v-if="!startDateOrTime"
            v-model="currentStartDate"
            title="选择开始日期"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="onStartDateConfirm"
            @cancel="cancelStartDatePicker"
        >
          <template #confirm>
            <van-button type="primary" @click="onStartDateConfirm">下一步</van-button>
          </template>
          <template #cancel>
            <van-button type="danger" @click="cancelStartDatePicker">取消</van-button>
          </template>
        </van-date-picker>

        <van-time-picker
            v-if="startDateOrTime"
            v-model="currentStartTime"
            title="选择开始时间"
            :columns-type="['hour', 'minute', 'second']"
            @confirm="onConfirmStartDatetime"
            @cancel="cancelStartTimePicker"
        >
          <template #confirm>
            <van-button type="primary" @click="onConfirmStartDatetime">确定</van-button>
          </template>
          <template #cancel>
            <van-button type="danger" @click="cancelStartTimePicker">取消</van-button>
          </template>
        </van-time-picker>
      </van-popup>

      <!-- 结束时间选择器 -->
      <van-popup
          v-model:show="showEndTimePicker"
          position="bottom"
          round
          style="max-height: 50vh;"
      >
        <van-date-picker
            v-if="!endDateOrTime"
            v-model="currentEndDate"
            title="选择结束日期"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="onEndDateConfirm"
            @cancel="cancelEndDatePicker"
        >
          <template #confirm>
            <van-button type="primary" @click="onEndDateConfirm">下一步</van-button>
          </template>
          <template #cancel>
            <van-button type="danger" @click="cancelEndDatePicker">取消</van-button>
          </template>
        </van-date-picker>

        <van-time-picker
            v-if="endDateOrTime"
            v-model="currentEndTime"
            title="选择结束时间"
            :columns-type="['hour', 'minute', 'second']"
            @confirm="onConfirmEndDatetime"
            @cancel="cancelEndTimePicker"
        >
          <template #confirm>
            <van-button type="primary" @click="onConfirmEndDatetime">确定</van-button>
          </template>
          <template #cancel>
            <van-button type="danger" @click="cancelEndTimePicker">取消</van-button>
          </template>
        </van-time-picker>
      </van-popup>
    </div>
  </div>
</template>

<style scoped>
.page-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.scroll-container {
  flex: 1;
  overflow: auto;
  -webkit-overflow-scrolling: touch;
}

.scroll-container::-webkit-scrollbar {
  display: none;
}

.header, .footer {
  flex-shrink: 0;
  background: #f5f5f5;
  padding: 12px;
}
</style>
