<script setup>
import { ref,computed } from "vue";
import {ElMessage} from "element-plus"
import moment from "moment"

import { roadshowInterence } from "@/api/api.js";
import calendar from "@/components/calendar.vue";
import addActivityBtnDia from "./compononts/addActivityBtnDia.vue";
import addActivityCellDia from "./compononts/addActivityCellDia.vue";
import { researcherCalendarConfig } from "./roleConfig";

// 活动列表
const eventList=ref([])
// 研究员列表
const researcherList=ref([])
// 选择的研究员
const selectResearcher=ref("")
// 按钮添加活动弹窗是否显示
const isActivityBtnDiaShow=ref(false)
const activityStartDate=ref(new Date())
// 日历添加活动弹窗是否显示
const isActivityCellDiaShow=ref(false)
// 子组件默认数据
const sonData=ref(null)
const edit_id=ref(0)
const edit_rs_id=ref(0)

// 删除弹窗显示
const isDeleteDiaShow=ref(false)
// 删除原因
const deleteReason=ref("")
const rowInfo=ref('')

const edit_matter_id=ref(0)
// const isAddMatterDiaShow=ref(false)
const matter_form=ref({})

// 是否显示添加按钮
const isShowAddActivityBtn=computed(()=>{
  const role = localStorage.getItem("Role");
  return researcherCalendarConfig.showAddActivityBtnList.includes(role);
})

const calendarRef=ref(null)

// 获取研究员列表
const getResearcherList=async()=>{
  // 发送请求
  const res = await roadshowInterence.getResearcherList();
  if (res.Ret === 200) {
    // researcherList.value = formatResearcherList(res.Data);
    const ficcList = formatResearcherList(res.Data.find(i=>i.GroupName==='ficc').ResearcherList||[]);
    const raiList = formatResearcherList(res.Data.find(i=>i.GroupName==='权益').ResearcherList||[]);

    researcherList.value = [{
      label:'ficc',
      ResearcherList:ficcList
    },{
      label:'权益',
      ResearcherList:raiList
    }]
  }
}

// 获取活动列表
const getEventList=async()=>{

  //当前的起始日期
  const { currentStart,currentEnd } = calendarRef.value.calendarApi.view

  const { formateDate } = calendarRef.value

  // 获取本周日程
  const res = await roadshowInterence.getCalendarDetail({
    StartDate: formateDate(currentStart),
    EndDate: formateDate(new Date(currentEnd.getTime()- 24*60*60*1000)),
    ResearcherId: selectResearcher.value || -1
  });

  eventList.value = [
    ...(res.Data.CalendarList || []),
    ...(res.Data.RsMattersList || []),
  ].map((item, index) => {
    return { ...item, id: index };
  });
}

// 对获取到的研究员列表做处理
const formatResearcherList=(list)=>{
  list.forEach((group) => {
    // 对组做处理
    group.label = group.GroupName;
    // 如果有列表
    group.ResearcherList && group.ResearcherList.forEach((item) => {
      // 对研究员做处理
      item.label = item.RealName;
      item.value = item.AdminId
    });
  });
  // 去掉ficc全体选项
  return list.filter((group) => group.GroupName !== "ficc全体");
}

// 添加说明弹窗
const addActivityBtn=()=>{
  //当前的起始日期
  const { currentStart } = calendarRef.value.calendarApi.view;
  edit_id.value = 0;
  edit_rs_id.value = 0;
  activityStartDate.value = currentStart
  isActivityBtnDiaShow.value = true;
}

// 单元格添加说明事件
const cellClick=(startDate)=>{
  if (!selectResearcher.value)
    return ElMessage.warning("请先选择研究员");
  const endDate = new Date(startDate.getTime() + 1000 * 60 * 60);
  sonData.value = {
    selectResearchers: [
      {
        researcherId: selectResearcher.value,
        startDate: startDate,
        startTime: startDate,
        endDate: endDate,
        endTime: endDate,
      },
    ],
  };
  edit_id.value = 0;
  edit_rs_id.value = 0;
  isActivityCellDiaShow.value = true;
}

/* 编辑事项时 回显内容 */
// const editCallback=({ ActivityType,RoadshowType,RoadshowPlatform,City,Province,CompanyId,CompanyName,ResearcherId,RsCalendarResearcherId,
//   Theme,CooperationName,ActivityCategory,StartDate,EndDate,RsCalendarId,RsMattersId,StartTime,EndTime,MatterContent })=>{
//   if(RsCalendarId) { // 编辑活动
//     sonData.value = {
//       activityType: ActivityType, // 活动类型
//       roadshowType: RoadshowType, // 路演形式
//       roadshowPlatform: RoadshowPlatform, // 路演平台
//       roadshowCity: Province ? [Province,City] : [], // 路演城市
//       companyId: CompanyId, // 客户id
//       companyName: CompanyName, // 客户名称
//       meetingType: RoadshowType, // 会议形式
//       meetingPlatform: RoadshowPlatform, // 会议平台
//       meetingCity: Province ? [Province,City] : [], // 会议城市
//       meetingTheme: Theme, // 会议主题
//       partnersName: CooperationName, // 合作方名称
//       activityClass: ActivityCategory, // 活动类别
//       selectResearchers: [
//         // 选择的研究员
//         {
//           researcherId: Number(ResearcherId),
//           startDate: new Date(StartDate),
//           startTime: new Date(`${StartDate} ${StartTime}`),
//           endDate: new Date(EndDate),
//           endTime: new Date(`${EndDate} ${EndTime}`),
//         },
//       ],
//     };
//     edit_id.value = RsCalendarId;
//     edit_rs_id.value = RsCalendarResearcherId;
//     isActivityCellDiaShow.value = true;
//   }else { //编辑事项
//     edit_matter_id.value = RsMattersId;
//     matter_form.value = { 
//       startDate: new Date(`${StartDate} ${StartTime}`),
//       startTime: new Date(`${StartDate} ${StartTime}`),
//       endDate: new Date(`${EndDate} ${EndTime}`),
//       endTime: new Date(`${EndDate} ${EndTime}`),
//       matterContent: MatterContent,
//     };
//     isAddMatterDiaShow.value = true;
//   }
// }

// 添加活动后刷新
const addCallback=()=>{
  getEventList();
}


  // 审核删除
const deleteRoadshow=(row)=>{
  if(['内部会议'].includes(row.ActivityType)) return delNormalHandle(row);

  rowInfo.value = row;
  isDeleteDiaShow.value = true;
  
}

// 删除弹窗取消操作
const deleteDiaCancel=()=>{
  deleteReason.value = "";
  rowInfo.value = null;
  isDeleteDiaShow.value = false;
}

// 删除弹窗确定操作
const deleteDiaConfirm=async()=>{
  if (!deleteReason.value) return ElMessage.warning("删除原因不能为空");

  const { Ret } = await roadshowInterence.deleteRoadshow({
    RsCalendarId: rowInfo.value.RsCalendarId,
    RsCalendarResearcherId: rowInfo.value.RsCalendarResearcherId,
    DeleteReason: deleteReason.value,
  });
  
  if( Ret !== 200) return;
  ElMessage.success('删除成功');

  deleteDiaCancel();
  getEventList();
}
// 处理从出差日历过来的参数
const dealwithFromBusiness=()=>{
  if(sessionStorage.getItem('businessToResearcherParams')){
    let fromBusinessParams=JSON.parse(sessionStorage.getItem('businessToResearcherParams'))
    let nowDate = moment(new Date()).startOf('week').diff(moment(new Date(fromBusinessParams.date)),'weeks')
    selectResearcher.value=fromBusinessParams.researcherId
    if(nowDate>0){
      // 前一周
      calendarRef.value.toogelDate('prev')
    }else if(nowDate<0){
      // 后一周
      calendarRef.value.toogelDate('next')
    }else{
      //为零，没有改变
      getEventList()
    }
    // 用完即弃
    sessionStorage.removeItem('businessToResearcherParams')
  }
}

getResearcherList()
dealwithFromBusiness()
</script>

<template>
  <div class="researcher-calendar">
    <el-card class="researcher-calendar-context">
      <!-- 日程组件 -->
      <!-- @editCallback="editCallback" -->
      <calendar
        ref="calendarRef"
        :eventList="eventList"
        @cellClick="cellClick"
        @weekChange="getEventList"
        @delAuthHandle="deleteRoadshow"
      >
        <template #left>
          <el-cascader
            v-model="selectResearcher"
            :options="researcherList"
            :show-all-levels="false"
            :props="{
              expandTrigger: 'hover',
              children: 'ResearcherList',
              emitPath: false,
            }"
            clearable
            filterable
            placeholder="请选择研究员"
            @change="getEventList"
          />
        </template>
        <template #right>
          <el-button
            v-if="isShowAddActivityBtn"
            type="primary"
            @click="addActivityBtn"
            >添加活动</el-button
          >
        </template>
      </calendar>
    </el-card>
    <!-- 按钮活动弹窗 -->
    <addActivityBtnDia
      v-model:isShow="isActivityBtnDiaShow"
      :start_date="activityStartDate"
      @ensureCallback="addCallback"
    ></addActivityBtnDia>
    <!-- 日历活动弹窗 -->
    <addActivityCellDia
      v-model:isShow="isActivityCellDiaShow"
      :initData="sonData"
      :edit_id="edit_id"
      :edit_rs_id="edit_rs_id"
      @ensureCallback="addCallback"
    ></addActivityCellDia>

    <!-- 删除确认弹窗 -->
    <el-dialog
      title="删除"
      :visible.sync="isDeleteDiaShow"
      :modal-append-to-body="false"
      width="500px"
      @close="deleteDiaCancel"
    >
      <el-input
        type="textarea"
        v-model.trim="deleteReason"
        :autosize="{ minRows: 4, maxRows: 8 }"
        placeholder="请输入删除理由"
        resize="none"
      ></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDiaCancel">取消</el-button>
        <el-button type="primary" @click="deleteDiaConfirm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style>
</style>