<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.projectName"
          label="课程名称"
          name="projectName"
          required
          placeholder="请输入课程名称"
          :readonly="ifReadOnly"
          :rules="[{required: true, message: '请输入课程名称'}]"
        />

        <van-field
          v-model="selectedYearText"
          readonly
          is-link
          label="培训年份"
          placeholder="请选择年份"
          :readonly="ifReadOnly"
          @click="!ifReadOnly && (showYearPicker = true)"
        />

        <van-field
          v-model="selectedTypeText"
          readonly
          is-link
          label="培训类别"
          placeholder="请选择培训类别"
          :readonly="ifReadOnly"
          @click="!ifReadOnly && (showTypePicker = true)"
        />

        <van-field
          v-model="fromVue.trainLeader"
          readonly
          is-link
          label="培训负责人"
          placeholder="请选择培训负责人"
          :readonly="ifReadOnly"
          @click="!ifReadOnly && handleDepartmentLeaderNameOne()"
        />

        <van-field
          v-model="selectedPlanYonText"
          readonly
          is-link
          label="是否计划内"
          placeholder="请选择"
          :readonly="ifReadOnly"
          @click="!ifReadOnly && (showPlanYonPicker = true)"
        />

        <van-field
          v-if="planWhyShow"
          v-model="fromVue.planWhy"
          label="计划外原因"
          name="planWhy"
          placeholder="请输入计划外原因"
          :readonly="ifReadOnly"
        />

        <van-field
          v-model="fromVue.trainHours"
          label="培训学时"
          name="trainHours"
          type="number"
          placeholder="请输入培训学时"
          :readonly="ifReadOnly"
        />

        <van-field
          v-model="selectedPlanNameText"
          readonly
          is-link
          label="计划名称"
          placeholder="请选择计划"
          :readonly="ifReadOnly"
          @click="!ifReadOnly && (showPlanNamePicker = true)"
        />

        <van-field
          v-model="fromVue.fromDate"
          readonly
          is-link
          label="开始时间"
          placeholder="请选择开始时间"
          :readonly="ifReadOnly"
          @click="!ifReadOnly && (showStartDatePicker = true)"
        />

        <van-field
          v-model="fromVue.toDate"
          readonly
          is-link
          label="结束时间"
          placeholder="请选择结束时间"
          :readonly="ifReadOnly"
          @click="!ifReadOnly && (showEndDatePicker = true)"
        />

        <van-field
          v-model="fromVue.trainContent"
          label="培训内容"
          name="trainContent"
          type="textarea"
          rows="3"
          autosize
          placeholder="请输入培训内容"
          :readonly="ifReadOnly"
        />

        <van-field label="附件上传">
          <template #input>
            <AttachmentS3 :f-id="result" />
          </template>
        </van-field>

        <div style="margin: 16px;" v-if="!ifReadOnly">
          <van-button round block type="primary" native-type="submit">
            {{ isEdit ? '保存' : '提交' }}
          </van-button>
        </div>
      </van-form>

      <!-- 年份选择器 -->
      <van-popup v-model:show="showYearPicker" round position="bottom">
        <van-picker
          :columns="yearOptions"
          @confirm="onYearConfirm"
          @cancel="showYearPicker = false"
        />
      </van-popup>

      <!-- 培训类别选择器 -->
      <van-popup v-model:show="showTypePicker" round position="bottom">
        <van-picker
          :columns="typeOptions"
          @confirm="onTypeConfirm"
          @cancel="showTypePicker = false"
        />
      </van-popup>

      <!-- 是否计划内选择器 -->
      <van-popup v-model:show="showPlanYonPicker" round position="bottom">
        <van-picker
          :columns="planYonOptions"
          @confirm="onPlanYonConfirm"
          @cancel="showPlanYonPicker = false"
        />
      </van-popup>

      <!-- 计划名称选择器 -->
      <van-popup v-model:show="showPlanNamePicker" round position="bottom">
        <van-picker
          :columns="planNameOptions"
          @confirm="onPlanNameConfirm"
          @cancel="showPlanNamePicker = false"
        />
      </van-popup>

      <!-- 开始日期选择器 -->
      <van-popup v-model:show="showStartDatePicker" round position="bottom">
        <van-date-picker
          v-model="currentStartDate"
          @confirm="onStartDateConfirm"
          @cancel="showStartDatePicker = false"
        />
      </van-popup>

      <!-- 结束日期选择器 -->
      <van-popup v-model:show="showEndDatePicker" round position="bottom">
        <van-date-picker
          v-model="currentEndDate"
          @confirm="onEndDateConfirm"
          @cancel="showEndDatePicker = false"
        />
      </van-popup>
    </div>
  </div>

  <!-- 人员选择组件 -->
  <OrganizationalWithLeafUserForCourse ref="PopupDepartmentLeaderNameRef2"
    @receiveFromChild="getDepartmentLeaderNameOne" />
</template>

<script setup>
import { getCurrentInstance, onMounted, ref, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import tools from '@/tools';
import OrganizationalWithLeafUserForCourse from '@/components/OrganizationalWithLeafUserForCourse.vue';
import AttachmentS3 from '@/components/AttachmentS3.vue';
import { showFailToast, showLoadingToast, showSuccessToast } from 'vant';

const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();

let title = '新增课程';

const onClickLeft = () => {
  router.go(-1);
};

const currentYear = ref(new Date().getFullYear());
const years = Array.from({ length: 5 }, (_, i) => {
  const year = new Date().getFullYear();
  return year - 4 + i;
});

const yearOptions = years.map(year => ({
  text: String(year),
  value: String(year)
}));

const jsonArray = localStorage.getItem('dept');
const deptInformation = ref([]);
try {
  deptInformation.value = jsonArray ? JSON.parse(jsonArray) : [];
} catch (error) {
  deptInformation.value = [];
}
const deptName = deptInformation.value[0]?.deptName || '';
const deptCode = deptInformation.value[0]?.deptCode || '';

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 `XJXX${formattedDate}${formattedTime}${paddedSequence}`;
};

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

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

if (planInfo == -1) {
  const fileId = generateCode();
  result.value = fileId;
  fromVue.value = {
    id: '',
    projectName: '',
    projectNo: '',
    trainYear: String(currentYear.value),
    projectType: '',
    trainLeader: localStorage.getItem('userDesc') || '',
    planYon: '',
    planName: '',
    planWhy: '',
    fromDate: '',
    toDate: '',
    trainContent: '',
    trainHours: '',
    fileId: fileId
  };
}

if (planInfo == 1) {
  title = '修改课程';
  fromVue.value = JSON.parse(route.query.data);
  if (fromVue.value.fileId) {
    result.value = fromVue.value.fileId;
  } else {
    result.value = generateCode();
    fromVue.value.fileId = result.value;
  }
}

const dicList = ref([]);
const getDicList = () => {
  tools.dic.getDicList(['SGSAFE_CLASS']).then((response => {
    dicList.value = response.data.data.SGSAFE_CLASS || [];
  }));
};

const PlantableData = ref([]);
const getDeptPlanData = () => {
  const url = '/sgsafe/Plan/query';
  const param = {
    page: 1,
    rows: 100,
    params: JSON.stringify({ deptCode: deptCode })
  };
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      PlantableData.value = response.data.data.records.map(item => item.planName);
    }
  });
};

const selectedYearText = ref('');
const selectedTypeText = ref('');
const selectedPlanYonText = ref('');
const selectedPlanNameText = ref('');
const planWhyShow = ref(false);

const showYearPicker = ref(false);
const showTypePicker = ref(false);
const showPlanYonPicker = ref(false);
const showPlanNamePicker = ref(false);
const showStartDatePicker = ref(false);
const showEndDatePicker = ref(false);

const currentStartDate = ref([new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()]);
const currentEndDate = ref([new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()]);

const typeOptions = computed(() => {
  return dicList.value.map(item => ({
    text: item.dicName,
    value: item.dicCode
  }));
});

const planYonOptions = [
  { text: '是', value: '是' },
  { text: '否', value: '否' }
];

const planNameOptions = computed(() => {
  return PlantableData.value.map(name => ({
    text: name,
    value: name
  }));
});

const onYearConfirm = ({ selectedOptions }) => {
  fromVue.value.trainYear = selectedOptions[0].value;
  selectedYearText.value = selectedOptions[0].text;
  showYearPicker.value = false;
};

const onTypeConfirm = ({ selectedOptions }) => {
  fromVue.value.projectType = selectedOptions[0].value;
  selectedTypeText.value = selectedOptions[0].text;
  showTypePicker.value = false;
};

const onPlanYonConfirm = ({ selectedOptions }) => {
  fromVue.value.planYon = selectedOptions[0].value;
  selectedPlanYonText.value = selectedOptions[0].text;
  if (selectedOptions[0].value === '是') {
    planWhyShow.value = false;
  } else {
    planWhyShow.value = true;
  }
  showPlanYonPicker.value = false;
};

const onPlanNameConfirm = ({ selectedOptions }) => {
  fromVue.value.planName = selectedOptions[0].value;
  selectedPlanNameText.value = selectedOptions[0].text;
  showPlanNamePicker.value = false;
};

const onStartDateConfirm = ({ selectedValues }) => {
  fromVue.value.fromDate = `${selectedValues[0]}-${String(selectedValues[1]).padStart(2, '0')}-${String(selectedValues[2]).padStart(2, '0')}`;
  showStartDatePicker.value = false;
};

const onEndDateConfirm = ({ selectedValues }) => {
  fromVue.value.toDate = `${selectedValues[0]}-${String(selectedValues[1]).padStart(2, '0')}-${String(selectedValues[2]).padStart(2, '0')}`;
  showEndDatePicker.value = false;
};

const PopupDepartmentLeaderNameRef2 = ref();
const handleDepartmentLeaderNameOne = () => {
  if (PopupDepartmentLeaderNameRef2.value) {
    PopupDepartmentLeaderNameRef2.value.open();
  }
};

const getDepartmentLeaderNameOne = (item) => {
  fromVue.value.trainLeader = item.user.userDesc;
};

const addEmergencyDrillPlan = async () => {
  const loadingToast = showLoadingToast({
    duration: 0,
    message: '加载中',
    forbidClick: true
  });

  fromVue.value.addDeptCode = deptCode;
  if (!fromVue.value.fileId) {
    fromVue.value.fileId = result.value;
  }

  const url = '/sgsafe/Class/save';
  const params = {
    json: JSON.stringify(fromVue.value)
  };

  try {
    const res = await proxy.$axios.post(url, params);
    if (res.data.code === 0 || res.data.code == '0') {
      loadingToast.close();
      showSuccessToast('保存成功');
      onClickLeft();
    } else {
      loadingToast.close();
      showFailToast('操作失败!' + (res.data.msg || '未知错误'));
    }
  } catch (error) {
    loadingToast.close();
    console.error('保存失败：', error);
    showFailToast('保存失败：' + (error.message || '网络错误，请稍后重试'));
  }
};

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

onMounted(() => {
  getDicList();
  getDeptPlanData();

  if (fromVue.value.trainYear) {
    selectedYearText.value = fromVue.value.trainYear;
  } else {
    selectedYearText.value = String(currentYear.value);
    fromVue.value.trainYear = String(currentYear.value);
  }

  if (fromVue.value.projectType) {
    const typeItem = dicList.value.find(item => item.dicCode === fromVue.value.projectType);
    if (typeItem) {
      selectedTypeText.value = typeItem.dicName;
    }
  }

  if (fromVue.value.planYon) {
    selectedPlanYonText.value = fromVue.value.planYon;
    planWhyShow.value = fromVue.value.planYon === '否';
  }

  if (fromVue.value.planName) {
    selectedPlanNameText.value = fromVue.value.planName;
  }

  if (fromVue.value.fromDate) {
    const dateParts = fromVue.value.fromDate.split('-');
    currentStartDate.value = [parseInt(dateParts[0]), parseInt(dateParts[1]), parseInt(dateParts[2])];
  }

  if (fromVue.value.toDate) {
    const dateParts = fromVue.value.toDate.split('-');
    currentEndDate.value = [parseInt(dateParts[0]), parseInt(dateParts[1]), parseInt(dateParts[2])];
  }
});
</script>

<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 {
  flex-shrink: 0;
  background: #f5f5f5;
  padding: 12px;
}
</style>
