<template>
  <div class="researcher-calendar">
    <el-card class="researcher-calendar-context">
      <!-- 日程组件 -->
      <calendar
        ref="calendarRef"
        :eventList="eventList"
        @eventClick="eventClick"
        @cellClick="cellClick"
        @weekChange="getEventList"
        @editCallback="editCallback"
        @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
      :isShow.sync="isActivityBtnDiaShow"
      :start_date="activityStartDate"
      ref="addActivityBtnDia"
      @ensureCallback="addCallback"
    ></addActivityBtnDia>
    <!-- 日历活动弹窗 -->
    <addActivityCellDia
      :isShow.sync="isActivityCellDiaShow"
      :initData="sonData"
      :edit_id="edit_id"
      :edit_rs_id="edit_rs_id"
      ref="addActivityCellDia"
      @ensureCallback="addCallback"
    ></addActivityCellDia>

    <!-- 事项弹窗  -->
    <addMatterDia 
      :isShow.sync="isAddMatterDiaShow" 
      :edit_matter_id="edit_matter_id" 
      :matter_form="matter_form"
      @ensureCallback="addCallback"
    />

    <!-- 删除确认弹窗 -->
    <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>

<script>
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 addMatterDia from "./compononts/addMatterDia.vue";
import { researcherCalendarConfig } from "./roleConfig";
export default {
  components: {
    calendar,
    addActivityBtnDia,
    addActivityCellDia,
    addMatterDia
  },
  data() {
    return {
      // 活动列表
      eventList: [],
      // 研究员列表
      researcherList: [],
      // 选择的研究员
      selectResearcher: "",
      // 按钮添加活动弹窗是否显示
      isActivityBtnDiaShow: false,
      activityStartDate:new Date(),
      // 日历添加活动弹窗是否显示
      isActivityCellDiaShow: false,
      // 点击单元格对应日期时间
      cellDate: null,
      // 子组件默认数据
      sonData: null,
      edit_id:0,
      edit_rs_id: 0,

      // 删除弹窗显示
      isDeleteDiaShow: false,
      // 删除原因
      deleteReason: "",
      rowInfo:'',

      edit_matter_id: 0,
      isAddMatterDiaShow: false,
      matter_form: {}
      
    };
  },
  methods: {
    // 获取研究员列表
    async getResearcherList() {
      // 发送请求
      const res = await roadshowInterence.getResearcherList();
      if (res.Ret === 200) {
        // this.researcherList=res.Data
        const ficcList = this.formatResearcherList(res.Data.find(i=>i.GroupName==='ficc').ResearcherList||[]);
        const raiList = this.formatResearcherList(res.Data.find(i=>i.GroupName==='权益').ResearcherList||[]);
        this.researcherList = [{
            label:'ficc',
            ResearcherList:ficcList
        },{
            label:'权益',
            ResearcherList:raiList
        }]
      }
    },
    
    // 获取活动列表
    async getEventList() {

      //当前的起始日期
      const { currentStart,currentEnd } = this.$refs.calendarRef.calendarApi.view;

      const { formateDate } = this.$refs.calendarRef;

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

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

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

    // 添加说明弹窗
    addActivityBtn() {
      //当前的起始日期
      const { currentStart } = this.$refs.calendarRef.calendarApi.view;
      this.edit_id = 0;
      this.edit_rs_id = 0;
      this.activityStartDate = currentStart
      this.isActivityBtnDiaShow = true;
    },
    
    // 单元格添加说明事件
    cellClick(startDate) {
      if (!this.selectResearcher)
        return this.$message.warning("请先选择研究员");
      const endDate = new Date(startDate.getTime() + 1000 * 60 * 60);
      this.sonData = {
        selectResearchers: [
          {
            researcherId: this.selectResearcher,
            startDate: startDate,
            startTime: startDate,
            endDate: endDate,
            endTime: endDate,
          },
        ],
      };
      this.edit_id = 0;
      this.edit_rs_id = 0;
      this.isActivityCellDiaShow = true;
    },

    /* 编辑事项时 回显内容 */
    editCallback({ ActivityType,RoadshowType,RoadshowPlatform,City,Province,CompanyId,CompanyName,ResearcherId,RsCalendarResearcherId,Theme,CooperationName,ActivityCategory,StartDate,EndDate,RsCalendarId,RsMattersId,StartTime,EndTime,MatterContent  }) {
      if(RsCalendarId) { // 编辑活动
        this.sonData = {
          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}`),
            },
          ],
        };
        this.edit_id = RsCalendarId;
        this.edit_rs_id = RsCalendarResearcherId;
        this.isActivityCellDiaShow = true;
      }else { //编辑事项
        this.edit_matter_id = RsMattersId;
        this.matter_form = { 
          startDate: new Date(`${StartDate} ${StartTime}`),
          startTime: new Date(`${StartDate} ${StartTime}`),
          endDate: new Date(`${EndDate} ${EndTime}`),
          endTime: new Date(`${EndDate} ${EndTime}`),
          matterContent: MatterContent,
        };
        this.isAddMatterDiaShow = true;
      }
    },

    // 添加活动后刷新
    addCallback() {
      this.getEventList();
    },


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

      this.rowInfo = row;
      this.isDeleteDiaShow = true;
      
    },

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

    // 删除弹窗确定操作
    async deleteDiaConfirm() {
      if (!this.deleteReason) return this.$message.warning("删除原因不能为空");

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

      this.deleteDiaCancel();
      this.getEventList();
    },
    // 处理从出差日历过来的参数
    dealwithFromBusiness(){
      if(sessionStorage.getItem('businessToResearcherParams')){
        let fromBusinessParams=JSON.parse(sessionStorage.getItem('businessToResearcherParams'))
        let nowDate = this.$moment(new Date()).startOf('week').diff(this.$moment(new Date(fromBusinessParams.date)),'weeks')
        this.selectResearcher=fromBusinessParams.researcherId
        if(nowDate>0){
          // 前一周
          this.$refs.calendarRef.toogelDate('prev')
        }else if(nowDate<0){
          // 后一周
          this.$refs.calendarRef.toogelDate('next')
        }else{
          //为零，没有改变
          this.getEventList()
        }
        // 用完即弃
        sessionStorage.removeItem('businessToResearcherParams')
      }
    }
  },
  computed: {
    // 是否显示添加按钮
    isShowAddActivityBtn() {
      const role = localStorage.getItem("Role");
      return researcherCalendarConfig.showAddActivityBtnList.includes(role);
    },
  },
  mounted() {
    this.getResearcherList();

    this.dealwithFromBusiness()
  }
};
</script>

<style>
</style>