<script setup>
import { ref, reactive,toRefs,onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { Icon, Toast,TreeSelect,Popup,Cascader } from 'vant';
import moment from 'moment';
import 'moment/dist/locale/zh-cn';
moment.locale('zh-cn');

import { researcherList,researchEvents } from '@/api/ssbg/api';
import { isWxprogram } from '../utils';
import { findParentByid } from './common-calendar';
import Calendar from '../components/calendar.vue';


const route = useRoute();
localStorage.setItem('ssbg-token',route.query.token ||  '5e532bc5fa7281aebaa6d89960b54c4ab22f1ab18e969258c634a7940fdb0922');

const actionsList = ref([
  { label: '添加活动', key: 'add', icon: 'add-o' },
  {
    label: '今天',
    key: 'weeknow',
    img: import("@/assets/ssbg/calendar_ico.png"),
  },
  {
    label: '选择研究员',
    key: 'choose',
    img: import("@/assets/ssbg/choose_ico.png"),
  },
]);

const calendarRef = ref(null);

const state = reactive({
  selectResearcher: '', // 选中的研究员
  eventList: [],//日程信息
});

/* 获取日历日程列表 */
const getEventList = async () => {
  if(!state.selectResearcher) return

  const { currentStart } = calendarRef.value.calendarApi.view;

  const { code,data } = await researchEvents({
    StartDate: moment(currentStart).format('YYYY-MM-DD'),
    EndDate: moment(currentStart).format('YYYY-MM-DD'),
    ResearcherId: Number(state.selectResearcher)
  })

  if(code !== 200) return

  state.eventList = [
    ...(data.CalendarList || []),
    ...(data.RsMattersList || []),
  ].map((item, index) => ( { ...item, id: index }));
};

/* 点击日历表格添加活动 */
const cellClickHandle = (date) => {

  if (!state.selectResearcher) return Toast.fail('请先选择研究员');

  const endDate = new Date(date.getTime() + 1000 * 60 * 60).getTime();
  const defaultResearcher = [
    {
      researcherId: state.selectResearcher,
      startTime: date.getTime(),
      endTime: endDate,
    }
  ]

  wx.miniProgram.navigateTo({
    url: `/pages-roadshow/addActivity/byCell?defaultOpt=${JSON.stringify(defaultResearcher)}`,
  });
};

/* 底部操作 */
const dealActionHandler = (type) => {
  const deal_methods_handles = {
    add: addActivityHandleByBtn,
    weeknow: toogeCurrentWeek,
    choose: slectResearcherHandle,
  };
  deal_methods_handles[type]();
};

/* 点击按钮添加活动 */
const addActivityHandleByBtn = () => {
  wx.miniProgram.navigateTo({
    url: '/pages-roadshow/addActivity/index',
  });
};

/* 切换为今天 */
const toogeCurrentWeek = () => {
  calendarRef.value.toogeCurrentWeek();
};

/* ==========选择研究员picker============ */
const researcherArr = ref([]);
const isResearcherPicker = ref(false);

const rs_picker = ref({
  firstindex: 0,
  id: ''
})

/* 获取研究员列表 */
const getResearcherList = async() => {
  const { code,data } = await researcherList();
  if(code !== 200) return;

  /* researcherArr.value = data.map(group => ({
    ...group,
    text: group.GroupName,
    value:group.GroupId,
    children: group.ResearcherList ? group.ResearcherList.map(child => ({
      ...child,
      text: child.RealName,
      id: child.AdminId,
      value:child.AdminId
    })) : []
  })); */
    const ficcList = formatResearcherList(data.find(i=>i.GroupName==='ficc').ResearcherList||[]);
    const raiList = formatResearcherList(data.find(i=>i.GroupName==='权益').ResearcherList||[]);
    researcherArr.value = [{
        text:'ficc',
        value:-1,
        children:ficcList
    },{
        text:'权益',
        value:-2,
        children:raiList
    }]
}
function formatResearcherList(list){
    list.forEach((group) => {
        // 对组做处理
        group.text = group.GroupName
        group.value = group.GroupId
        // 如果有列表
        group.ResearcherList && group.ResearcherList.forEach((item) => {
          // 对研究员做处理
          item.text = item.RealName
          item.value = item.AdminId
        })
        group.children = group.ResearcherList||[]
      })
      // 去掉ficc全体选项
      return list.filter((group) => group.GroupName !== "ficc全体");
}
onMounted(() => {
  getResearcherList();
})

/* 选择研究员 */
const slectResearcherHandle = () => {
  // console.log('slect');
  /* if(state.selectResearcher) {
    rs_picker.value = {
      firstindex: findParentByid(state.selectResearcher,researcherArr.value),
      id: state.selectResearcher
    }
  } */
  isResearcherPicker.value = true;
};

/* 点击第一项索引 */
const clickFirstHandle = (index) => {
  rs_picker.value.firstindex = index;
}
/* 点击选择研究员 */
const clickItemHandle = ({AdminId}) => {
  rs_picker.value.id  = AdminId;
}
/* 取消 */
const cancelResearcher = () => {

  isResearcherPicker.value = false;
}
/* 确认 */
const confirmResearcher = () => {
  state.selectResearcher = rs_picker.value.id;
			
	isResearcherPicker.value = false;
  getEventList();
}

const { eventList } = toRefs(state);

document.title = '研究员日历';

function chooseResearcher(){
    getEventList();
    isResearcherPicker.value = false;
}
</script>

<!--  -->
<template>
  <div class="rs-container">
    <Calendar 
      ref="calendarRef"
      :eventList="eventList"
      :selectUserValue="Number(state.selectResearcher)"
      @dateChange="getEventList" 
      @cellClick="cellClickHandle" 
    />
    <!-- v-if="isWxprogram()" -->
    <div class="fix-action" >
      <ul class="action-ul">
        <li
          v-for="item in actionsList"
          key="item.key"
          @click="dealActionHandler(item.key)"
        >
          <Icon :name="item.icon" class="item-icon" v-if="item.icon" />
          <img
            class="item-img"
            src="@/assets/ssbg/calendar_ico.png"
            alt=""
            v-else-if="item.key === 'weeknow'"
          />
          <img
            class="item-img"
            src="@/assets/ssbg/choose_ico.png"
            alt=""
            v-else-if="item.key === 'choose'"
          />
          {{ item.label }}
        </li>
      </ul>
    </div>
    
    

    <!-- 选择研究员picker -->
    <Popup v-model:show="isResearcherPicker" position="bottom">
			<!-- <view class="select-rs-header">
				<text class="cancel" @click="cancelResearcher">取消</text>
				<text class="ensure" @click="confirmResearcher">确认</text>
			</view> -->
			<!-- <TreeSelect 
				:items="researcherArr" 
				:main-active-index="rs_picker.firstindex" 
				:active-id="rs_picker.id"
				@click-nav="clickFirstHandle" 
				@click-item="clickItemHandle" 
			/> -->
            <Cascader
                title="请选择研究员"
                active-color="#3385FF"
                v-model="state.selectResearcher"
                :options="researcherArr"
                @close="cancelResearcher"
                @finish="chooseResearcher"
            />
		</Popup>
  </div>
</template>

<style scoped lang="scss">
.rs-container {
  .fix-action {
    height: 160px;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 99;
    background-color: #fff;
    box-shadow: 0px -3px 6px rgba(172, 172, 172, 0.16);
    padding-top: 20px;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    .action-ul {
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: space-around;
      color: #3385ff;
      li:hover {
        opacity: 0.8;
      }
      .item-icon {
        font-size: 52px;
        display: block;
        text-align: center;
        margin: 0 auto 10px;
      }
      .item-img {
        display: block;
        width: 46px;
        height: 46px;
        margin: 0 auto 10px;
      }
    }
  }

  .select-rs-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30px 20px;

    .cancel {
      color: #969799;
    }

    .ensure {
      color: #576b95;
    }
  }

  .van-tree-select {
		::v-deep(.van-sidebar-item--select:before) {
			background-color: #1989fa;
		}

		::v-deep(.van-tree-select__item--active) {
			color: #1989fa;
		}

    ::v-deep(.van-tree-select__selected) {
      position: absolute !important;
    }

	}
}
</style>
