<template>
  <view class="con-body">
    <view class="con-bg">
      <!-- 头部 -->
      <customHeader ref="customHeaderRef" :title="title" :leftFlag="true" :rightFlag="true">
        <template #right>
          <view class="head-right" @click="submitForm" v-if="userInfo.nickName || userInfo.userName">
            <uni-icons custom-prefix="iconfont" type="icon-phonebaocun" size="22"
                       color="#B7D2FF"></uni-icons>
            保存
          </view>
        </template>
      </customHeader>
      <!-- 高度来避免头部遮挡 -->
      <view class="top-height"></view>

      <!-- 正文内容 -->
      <view class="week-plan-title">
        <view>姓名：<strong>{{ userInfo.nickName || userInfo.userName }}</strong></view>
        <view>{{ currentEditDate.yearMonth }} 第 <strong>{{ currentEditDate.weekNum }}</strong> 周</view>
      </view>
      <uni-forms ref="formRef" :model="weekPlanFormData" :rules="rules" label-width="100px" label-position="top">
        <block v-for="(item, index) in OrdinalDate">
          <view class="white-bg" :class="index==0?'white-bg-2':'white-bg-3'">
            <view class="w-b-title" @click="handleExpand(index)">
              {{ weekPlanFormData[item] }} {{ WeekCN[index] }}
              <text>{{ expandFlag[index] ? '收起' : '展开' }}
                <i :class="{iconfont:true,'icon-up':expandFlag[index],'icon-down':!expandFlag[index]}"></i>
              </text>
            </view>

            <view v-show="expandFlag[index]" class="form-con">
              <uni-forms-item label="工作类型" :name="getTypeField(index)" :required="index < workDays">
                <view class="form-picker">
                  <picker @change="handleTypeChange" :range="WORK_TYPE" :data-field="getTypeField(index)">
                    <view class="flex">
                      {{ weekPlanFormData[getTypeField(index)] }}
                      <uni-icons type="down" size="20" color="#A0A0A0"></uni-icons>
                    </view>
                  </picker>
                </view>
              </uni-forms-item>
              <uni-forms-item label="内容" :name="getEventField(index)" :required="index < workDays">
                <uni-easyinput type="textarea" autoHeight v-model="weekPlanFormData[getEventField(index)]"
                               placeholder="请输入" class="form-texarea"/>
              </uni-forms-item>
            </view>

          </view>
        </block>
      </uni-forms>

    </view>
  </view>
</template>

<script setup>
import {ref, reactive, onMounted, getCurrentInstance, computed} from 'vue'
import {OrdinalDate, WorkEvent, WorkType, WORK_TYPE, WeekCN} from "./dataMap";
import customHeader from '@/components/customHeader.vue'
import {useRoute} from "vue-router"
import {useMessage} from "@/utils/message";
import {onLoad} from "@dcloudio/uni-app";
import {updateWeekPlanList, addPlan} from "@/api/crm/plan/updatePlan";
import {getUserInfo} from "@/api/crm/plan/getPlan";
import {getDate} from "@/utils/datetime";
import {getWeek2, getCurrentWeekNum} from "./dateTimeUtils";

const message = useMessage();
// 当前页面路由
const route = useRoute();
// 当前编辑周期
const currentEditDate = ref({
  yearMonth: '',
  weekNum: 0
});
// 用户信息
const userInfo = ref({nickName: null, userName: null});
// 编辑模式
const isAdd = ref(true);
// 标题
const title = ref("修改周计划");
// 表单项展开状态
const expandFlag = ref([true, true, true, true, true, true, true]);
// 表单ref
const formRef = ref(null);
// 工作类型的index
const workTypeIndex = ref({});
// 表单数据
const weekPlanFormData = ref({
  // planId: 0, // 主键ID
  // planDateId: 0, // 周计划ID

  year: 0, // 年
  month: 0, // 月
  date: 0, // 周

  firstDayOfTheWeek: null, // 周一日期
  secondDayOfThisWeek: null, // 周二日期
  thirdDayOfTheWeek: null, // 周三日期
  fourthDayOfTheWeek: null, // 周四日期
  fifthDayOfTheWeek: null, // 周五日期
  sixthDayOfTheWeek: null, // 周六日期
  seventhDayOfTheWeek: null, // 周日日期

  typeOfMonday: null, // 周一工作类型
  typeOfTuesday: null, // 周二工作类型
  typeOfWednesday: null, //周三工作类型
  typeOfThursday: null, // 周四工作类型
  typeOfFriday: null, // 周五工作类型
  typeOfSaturday: null, // 周六工作类型
  typeOfSunday: null, // 周日工作类型

  eventOfMonday: null, // 周一工作内容
  eventOfTuesday: null, // 周二工作内容
  eventOfWednesday: null, // 周三工作内容
  eventOfThursday: null, // 周四工作内容
  eventOfFriday: null, // 周五工作内容
  eventOfSaturday: null, // 周六工作内容
  eventOfSunday: null // 周日工作内容
});

// 校验规则
const rules = reactive({});
// 工作日数量
const workDays = 5;
// const instance = getCurrentInstance().proxy;
let instance = null;
// 初始化创建任务
let initCreate = (params)=>{
  const {itemList, selectIndex} = params;
  // 获取用户信息
  getUserInfo().then(res => {
    userInfo.value = res.user;
    console.log(route.path, "：用户信息获取成功");
  }).catch(err => {
    console.warn(err, "用户信息获取失败")
  });
  console.log(route.path,`：创建${itemList[selectIndex]}计划`);
  title.value="创建周计划";
  currentEditDate.value.yearMonth = getDate({format: true}).substring(0, 7); // 只要年月
  currentEditDate.value.weekNum = getCurrentWeekNum() + selectIndex; // 取巧做法，当期周则selectIndex为0，下周则selectIndex为1，用加法处理
  const week = getWeek2(itemList[selectIndex]); // 获取本周/下周一周日期
  // weekPlanFormData.value.year = getDate({format:true}).substring(0, 4); // 年份
  // weekPlanFormData.value.month = parseInt(currentEditDate.value.yearMonth.substring(5, 7)); // 月份
  weekPlanFormData.value.date = getCurrentWeekNum() + selectIndex; // 第几周
  const {year, month} = week;
  weekPlanFormData.value.year = year;
  weekPlanFormData.value.month = month;
  for(let index in OrdinalDate){
    let dateField = getDateField(index);
    weekPlanFormData.value[dateField] = week[dateField];
    // console.log(week[dateField]);
    if(index>=workDays){
      let typeField = getTypeField(index);
      weekPlanFormData.value[typeField] = "法定假日"; // TODO: 换成更规范代码
      workTypeIndex.value[typeField] = WORK_TYPE.indexOf("法定假日");
    }
  }
  console.log(weekPlanFormData.value);
}
onLoad((options) => {
  // console.log(options); // 参数
  // console.log(route.path, "：计划编辑页面");
  instance = getCurrentInstance().proxy;
  const eventChannel = instance.getOpenerEventChannel();
  eventChannel.on('editPlanData', (data) => {
    isAdd.value = data.isAdd;
    if (!data.isAdd) {
      let {userName, formData, editFields} = data.param;
      console.log(route.path, userName, formData, editFields, "计划编辑页读取到参数");
      weekPlanFormData.value = formData;
      userInfo.value.userName = userName;
      currentEditDate.value.yearMonth = formData.firstDayOfTheWeek.substring(0, 7);
      currentEditDate.value.weekNum = formData.date; // 周数
      // for(let typeField of WorkType){
      //   workTypeIndex.value[typeField] = WORK_TYPE.indexOf(formData[typeField]);
      // }
      for (let index in OrdinalDate) {
        expandFlag.value[index] = editFields.includes(getTypeField(index)) || editFields.includes(getEventField(index));
        // console.log(index, expandFlag.value[index], "展开状态");
      }
    }else{
      initCreate(data.param);
    }

  })
});

// 工作日期的field
function getDateField(index) {
  return OrdinalDate[index]
}

// 工作类型的field
function getTypeField(index) {
  return WorkType[index]
}

// 工作内容的field
function getEventField(index) {
  return WorkEvent[index];
}

// 初始化校验规则
(function bindRules(){
  for (let i in WorkType) {
    if (i < workDays) {
      rules[getTypeField(i)] = {
        rules: [{
          required: true,
          errorMessage: '请选择工作类型',
          trigger: 'blur'
        }]
      }
    }
  }
  for (let i in WorkEvent) {
    if (i < workDays) {
      rules[getEventField(i)] = {
        rules: [{
          required: true,
          errorMessage: '请输入工作内容',
          trigger: 'blur'
        }]
      }
    }
  }
  // console.log(rules, '初始化校验规则完成');
})();

// 展开事件
function handleExpand(index) {
  expandFlag.value[index] = !expandFlag.value[index];
}

// 选择工作类型
const handleTypeChange = (e) => {
  const {field} = e.target.dataset;
  console.log("选中工作类型: ", WORK_TYPE[e.detail.value], "，更新类型字段: ", field);
  workTypeIndex.value[field] = e.detail.value;
  weekPlanFormData.value[field] = WORK_TYPE[e.detail.value];
};

// 保存
const submitForm = async () => {
  try {
    // 验证表单
    await formRef.value.validate()

    // 验证通过后的操作

    // console.log('表单数据:', weekPlanFormData.value);

    // 这里可以添加提交到服务器的代码
    if(!isAdd.value){ // 请求修改
      let res = await updateWeekPlanList(weekPlanFormData.value).catch(err=>{
        message.error('操作失败!');
        console.warn(err, "更新周计划失败");
      })
      message.success('修改成功!');
      setTimeout(()=>{
        const eventChannel = instance.getOpenerEventChannel();
        eventChannel.emit('refreshData');
        uni.navigateBack()
      }, 500);
    }else{ // 请求新增
      console.log(weekPlanFormData.value,"新增计划");
      let res = await addPlan(weekPlanFormData.value).catch(err=>{
        message.error('操作失败!');
        console.error(err, "周计划新增失败");
      })
      message.success('保存成功!');
      setTimeout(()=>{
        const eventChannel = instance.getOpenerEventChannel();
        eventChannel.emit('refreshData');
        uni.navigateBack()
      }, 500);
    }
  } catch (err) {
    uni.showToast({
      icon:'none',
      title:"请完善内容",
      duration: 1500
    })
    console.log('表单验证失败:', err);
  }
};


</script>

<style scoped>
.week-plan-title {
  color: #fff;
  padding: 0 30rpx 30rpx;
  display: flex;
  justify-content: space-between;
}

.white-bg {
  width: 690rpx;
  margin: 0;
  border-radius: 8px 8px 0 0;
}

.white-bg.white-bg-2 {
  /*margin-bottom: 20rpx;*/
}

.white-bg.white-bg-3 {
  border-top:  1rpx solid #E5E5E5;
  border-radius: 0
}

.white-bg .w-b-title {
  color: #3384DF;
  font-size: 38rpx;
}

.form-con {
  padding: 30rpx 0 0;
}

:deep(.form-con .uni-forms-item) {
  margin-bottom: 22px !important;
}

</style>