<script setup>
import { ref,computed,reactive,watch } from "vue";
import {ElMessage,ElMessageBox} from "element-plus"
import { useRoute } from "vue-router";
import { InfoFilled } from "@element-plus/icons-vue";
import moment from "moment"

import { roadshowInterence } from "@/api/api.js";
import calendar from "@/components/calendar.vue";
import { getTabs,tableColums,handleArr,ENUM_RESEARCHLIST,sellerList } from "./roleConfig/myCalendarConfig";
import addMatterDia from "./compononts/addMatterDia.vue";
import addActivityCellDia from "./compononts/addActivityCellDia.vue";
import addActivityBtnDia from "./compononts/addActivityBtnDia.vue";
import mPage from "@/components/mPage.vue";

const $route = useRoute()

const tabs=ref(getTabs(localStorage.getItem("Role")))
const default_tab=ref(0)
const tableColumsV=ref([])//默认列
const handleArrV=ref([])//操作栏
const tableLoading=ref(false)
const statusMap=new Map([
  [1, '待接受'],
  [2, '已接受'],
  [3, '已拒绝'],
  [4, '已删除'],
  [5, '已撤回'],
  [6, '已结束'],
])
const tableData=ref([])//表格数据
const total=ref(0)
const page_no=ref(1)
// 添加事项弹窗显示
const isAddMatterDiaShow=ref(false)
// 拒绝弹窗显示
const isRefuseDiaShow=ref(false)
// 删除弹窗显示
const isDeleteDiaShow=ref(false)
// 当前行信息
const rowInfo=ref(null)
// 拒绝理由
const refuseReason=ref("")
// 删除原因
const deleteReason=ref("")
// 修改活动弹窗(修改重提)
const isActivityBtnDiaShow=ref(false)
// 研究员列表
const researcherList=ref([])
// 日历日程列表
const eventList=ref([])
// 重提初始数据
const resubmitData=ref(null)

const companyInfo=ref(null)
const edit_matter_id=ref(0)
const matter_form=ref({})
const matter_date=ref(new Date())
const isActivityCellDiaShow=ref(false)
const sonData=ref(null)
const edit_id=ref(0)//编辑日历id
const edit_rs_id=ref(0)

const modifyReason=reactive({
    text:'',
    time:''
})
const isReasonDiaShow=ref(false)

const calendarRef=ref(null)

const Role=computed(()=>{
  return localStorage.getItem("Role");
})

watch(default_tab,(newval)=>{
  tableColumsV.value = tableColums(newval).filter(it => !it.hidden)
  handleArrV.value = handleArr(newval);
  page_no.value = 1;
  newval && getCalendarList();
})


// 添加事项按钮
const addMatterBtn=()=>{
  const { currentStart } = calendarRef.value.calendarApi.view;
  matter_date.value=currentStart
  edit_matter_id.value = 0;
  matter_form.value = {};
  isAddMatterDiaShow.value = true;
}
// 获取日历表格列表数据
const getCalendarList=async()=>{
  tableLoading.value = true;
  // 发送请求
  const { Ret,Data } = default_tab.value === 5 ? await roadshowInterence.mattersList({
    PageSize: 10,
    CurrentIndex: page_no.value
  }) : await roadshowInterence.getCalendarList({
    PageSize: 10,
    CurrentIndex: page_no.value,
    CalendarType: default_tab.value,
  });

  tableLoading.value = false;
  if(Ret !== 200) return;
  
  total.value = Data.Paging.Totals;
  tableData.value = default_tab.value === 5 ? Data.List&&Data.List.map(item => ({...item, ActivityType: '事项'})) : Data.List;
}

// 页码改变事件
const handleCurrentChange=(page, index)=>{
  page_no.value = page;
  getCalendarList();
}
    
/* 获取客户信息 */
const getCompanyInfo=async ({CompanyId,EnglishCompany})=>{
  const { Data }  = await roadshowInterence.componyDetail({ CompanyId,EnglishCompany });
  companyInfo.value = Data;
}

// 撤回操作
const revocation=async (row)=>{
  await ElMessageBox.confirm("确定要撤回该活动申请吗？", "撤回", {
    confirmButtonName: "确定",
    cancelButtonName: "取消",
    type: "warning",
  });
  const { Ret } = await roadshowInterence.revocationRoadshow({
    RsCalendarId: row.RsCalendarId,
    RsCalendarResearcherId: row.RsCalendarResearcherId,
  });

  if(Ret !== 200) return;
  ElMessage.success('撤回成功');

  page_no.value = tableData.value.length === 1 ? page_no.value -1 : page_no.value;

  refreshData()
}

// 接受操作
const accept=async (row)=>{
  await ElMessageBox.confirm("接受申请后会加入您的日历，请确认", "接受", {
    confirmButtonName: "确定",
    cancelButtonName: "取消",
    type: "warning",
  });
  const { Ret } =  await roadshowInterence.acceptRoadshow({
    RsCalendarId: row.RsCalendarId,
    RsCalendarResearcherId: row.RsCalendarResearcherId,
  });
  
  if( Ret !== 200) return;
  ElMessage.success('加入成功');

  page_no.value = tableData.value.length === 1 ? page_no.value -1 : page_no.value;

  refreshData()
}
// 拒绝操作
const refuse=(row)=>{
  rowInfo.value = row;
  isRefuseDiaShow.value = true;
}
// 拒绝弹窗取消操作
const refuseDiaCancel=()=>{
  refuseReason.value = "";
  rowInfo.value = null;
  isRefuseDiaShow.value = false;
}
// 拒绝弹窗确定操作
const refuseDiaConfirm=async ()=>{
  if (!refuseReason.value) return ElMessage.warning("拒绝理由不能为空");
  const { Ret } =  await roadshowInterence.refuseRoadshow({
    RsCalendarId: rowInfo.value.RsCalendarId,
    RsCalendarResearcherId: rowInfo.value.RsCalendarResearcherId,
    RefuseReason: refuseReason.value,
  });
  
  if(Ret !== 200) return

  page_no.value = tableData.value.length === 1 ? page_no.value -1 : page_no.value;
  
  refuseDiaCancel();
  getCalendarList();
}
// 拒绝理由
const showRefuseReason=(row)=>{
  ElMessageBox.alert(row.RefuseReason || "拒绝理由", "拒绝理由", {
    confirmButtonText: "知道了",
  });
}
// 图标点击事件
const iconClick=(row)=>{
  if (row.Status === 4) {
    // 删除原因
    ElMessageBox.alert(row.DeleteReason || "删除原因", "删除原因", {
      confirmButtonText: "知道了",
    });
  } else if (row.Status === 3) {
    // 拒绝理由
    showRefuseReason(row);
  }
}

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

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

/* 非审核删除 气泡确认 内部会议 电话会 事项*/
const delNormalHandle=({RsCalendarId,RsCalendarResearcherId,RsMattersId})=>{

  ElMessageBox.confirm("删除该活动后，将从日历中移除，确定继续吗?", "删除", {
    type: "warning"
  }).then( async() => {
    //删除事项
    let { Ret } = RsMattersId ? await roadshowInterence.delMatters({ RsMattersId }) 
    //删除活动
    : await roadshowInterence.deleteRoadshow({ RsCalendarId, RsCalendarResearcherId });

    if(Ret !== 200) return;
    
    ElMessage.success('删除成功');
    
    page_no.value = tableData.value.length === 1 ? page_no.value -1 : page_no.value;

    refreshData()

    })
    .catch(() => {});
}

/* 编辑活动 或事项 */
const editActivityHandle=(row)=>{

  const { RsCalendarId,RsCalendarResearcherId,RsMattersId,MatterContent,StartDate,StartTime,EndTime,EndDate } = row;
  //编辑活动
  if(!RsMattersId) {
    resubmitData.value = editInfoBack(row,2);
    edit_id.value = RsCalendarId;
    edit_rs_id.value = RsCalendarResearcherId;
    isActivityBtnDiaShow.value = true;
  } else {
    //编辑事项
    editMatterHandle({ RsMattersId,StartDate,StartTime,EndDate,EndTime,MatterContent });
  }
}

// 删除弹窗取消操作
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();
  refreshData();
}
// 修改重提
const resubmit=(row)=>{
  resubmitData.value = editInfoBack(row);
  edit_id.value = row.RsCalendarId;
  edit_rs_id.value = row.RsCalendarResearcherId;
  isActivityBtnDiaShow.value = true;
}

const refreshData=()=>{
  getCalendarList();
  getEventList();
}

/* 回显表单 type回显的研究员是[]还是'' */
const editInfoBack=({ ActivityType,RoadshowType,RoadshowPlatform,City,Province,CompanyId,CompanyName,
                    ResearcherId,Theme,CooperationName,ActivityCategory,StartDate,EndDate,StartTime,
                    EndTime,EnglishCompany},type = 1)=>{
  return {
    activityType: ActivityType, // 活动类型
    roadshowType: RoadshowType, // 路演形式
    roadshowPlatform: RoadshowPlatform, // 路演平台
    roadshowCity: Province ? [Province,City] : [], // 路演城市
    companyId: CompanyId, // 客户id
    companyName: CompanyName, // 客户名称
    englishCompany:EnglishCompany,// 是否是海外客户
    meetingType: RoadshowType, // 会议形式
    meetingPlatform: RoadshowPlatform, // 会议平台
    meetingCity: Province ? [Province,City] : [], // 会议城市
    meetingTheme: Theme, // 会议主题
    partnersName: CooperationName, // 合作方名称
    activityClass: ActivityCategory, // 活动类别
    selectResearchers: [
      // 选择的研究员
      {
        researcherId: type === 2 ? ResearcherId.split(',').map(item => Number(item)) : Number(ResearcherId),
        startDate: new Date(StartDate),
        startTime: new Date(`${StartDate} ${StartTime}`),
        endDate: new Date(EndDate),
        endTime: new Date(`${EndDate} ${EndTime}`),
      },
    ],
  };
}

// 获取日历日程列表
const getEventList=async ()=>{

  if(Role.value === 'admin') return;
    //当前的起始日期
  const { currentStart,currentEnd } = calendarRef.value.calendarApi.view;

  const { formateDate } = calendarRef.value;
  const res = await roadshowInterence.myCalendarDetail({
    StartDate: formateDate(currentStart),
    EndDate: formateDate(new Date(currentEnd.getTime()- 24*60*60*1000)),
  });
  // 赋值
  eventList.value = [
    ...(res.Data.CalendarList || []),
    ...(res.Data.RsMattersList || []),
  ].map((item, index) => {
    return { ...item, id: index };
  });
}

/* 日历入口 编辑活动时 回显内容 */
const editCallback=({ ActivityType,RoadshowType,RoadshowPlatform,City,Province,CompanyId,
                    CompanyName,ResearcherId,RsCalendarResearcherId,Theme,CooperationName,ActivityCategory,
                    StartDate,EndDate,RsCalendarId,RsMattersId,StartTime,EndTime,MatterContent,EnglishCompany})=>{
  if(RsCalendarId) { // 编辑活动
    sonData.value = {
      activityType: ActivityType, // 活动类型
      roadshowType: RoadshowType, // 路演形式
      roadshowPlatform: RoadshowPlatform, // 路演平台
      roadshowCity: Province ? [Province,City] : [], // 路演城市
      companyId: CompanyId, // 客户id
      companyName: CompanyName, // 客户名称
      englishCompany:EnglishCompany,// 是否是海外客户
      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 { //编辑事项
    editMatterHandle({ RsMattersId,StartDate,StartTime,EndDate,EndTime,MatterContent });
  }
}

/* 编辑事项 */
const editMatterHandle=({ RsMattersId,StartDate,StartTime,EndDate,EndTime,MatterContent })=>{
  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 showReason=(row)=>{
  modifyReason.text=row.EditReason
  modifyReason.time=row.ModifyTime
  
  isReasonDiaShow.value = true
}

/* 初始化默认tab 表格列和操作  */
const init=()=>{

  default_tab.value = $route.query.act_tab ? $route.query.act_tab : Role.value === 'admin' ? 3 : 1;
  tableColumsV.value = tableColums(default_tab.value).filter(it => !it.hidden)
  handleArrV.value = handleArr(default_tab.value);

}



init();

</script>

<template>
  <div class="my-calendar">
    <el-card class="my-calendar-list">
      <ul class="tabs-type">
        <li :class="['type-item',{ 'act': default_tab === tab.key }]" v-for="tab in tabs" :key="tab.key"  @click="default_tab=tab.key">{{tab.label}}</li>
      </ul>
      <el-table
				:data="tableData"
        v-loading="tableLoading"
        element-loading-text="数据加载中..." 
				style="box-shadow: 0px 3px 6px rgba(155, 170, 219, 0.2);margin-top:20px;"
				border>
        <el-table-column
          v-for="item in tableColumsV"
          :key="item.label"
          :label="item.label"
          :width="item.widthsty"
          :min-width="item.minwidthsty"
          align="center"
        >
          <template #default="{row}">

            <!-- 时间处理 -->
            <span v-if="item.key === 'time'">
              {{
                row.StartDate === row.EndDate
                ? (moment(new Date(row.StartDate + " " + row.StartTime)).format(
                  "MM.DD(ddd) HH:mm") + '~' +  moment(new Date(row.EndDate + " " + row.EndTime)).format("HH:mm"))
                : (
                  moment(new Date(row.StartDate + " " + row.StartTime)).format(
                  "MM.DD(ddd) HH:mm") + '~' + moment(new Date(row.EndDate + " " + row.EndTime)).format("MM.DD(ddd) HH:mm")
                )
              }}
            </span>

            <!-- 活动形式 -->
            <span v-else-if="item.key === 'RoadshowType'">
              {{row.RoadshowType}} {{ row.RoadshowType === '线上' ? `(${row.RoadshowPlatform}  )` : `(${row.Province}${row.City})`}}
            </span>

            <!-- 状态 -->
            <span v-else-if="item.key === 'Status'" 
            :class="row.Status === 2 ? 'successty' : row.Status === 3 ? 'deletesty' : '' ">
              {{statusMap.get(row.Status)}}
              <el-icon style="color:#666;vertical-align: text-top" v-if="[3,4].includes(row.Status) && ENUM_RESEARCHLIST.includes(Role)"
              @click="iconClick(row)"><InfoFilled /></el-icon>
            </span>

            <!-- 客户拼接 -->
            <span v-else-if="item.key === 'company'">
              {{ row.CooperationName || row.CompanyName }}

              <el-tooltip effect="dark" placement="top-start" v-if="row.CompanyId"  popper-class="company-tip-poper">
                <el-icon style="vertical-align: text-top" @mouseenter.native="getCompanyInfo(row)" ><InfoFilled /></el-icon>
                <template #content v-if="companyInfo">
                  <template v-if="companyInfo.EnglishCompany===1">
                    <p style="margin: 6px 0;">所属国家：{{companyInfo.EnglishCountry}}</p>
                    <p style="margin: 6px 0;">累计点击量：{{companyInfo.EnglishViewTotal}}</p>
                  </template>
                  <template v-else>
                    <p style="margin: 6px 0;">客户状态：{{companyInfo.Status}}</p>
                    <p style="margin: 6px 0;">所属行业：{{companyInfo.IndustryName}}</p>
                    <p style="margin: 6px 0;text-indent: -70px;margin-left: 70px;">开通品种：{{companyInfo.PermissionName}}</p>
                    <p style="margin: 6px 0;">累计报告阅读次数：{{companyInfo.ReportReadTotal}}</p>
                  </template>
                </template>

              </el-tooltip>
            </span>

            <span v-else>{{ row[item.key] || '——' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" v-if="handleArrV.length">
          <template #default="{ row }" >
          
          <template  v-if="![4,6].includes(row.Status) && (moment(new Date(`${row.StartDate} ${row.StartTime}`)).valueOf() > new Date().getTime())">
            <template v-if="default_tab === 1">
              <span
                class="editsty"
                v-if="handleArrV.includes('撤回')"
                @click="revocation(row)"
                >撤回</span>
              <span
                class="editsty"
                v-if="handleArrV.includes('接受')"
                @click="accept(row)"
                >接受</span>
              <span
                class="editsty"
                v-if="handleArrV.includes('拒绝')"
                @click="refuse(row)"
                >拒绝</span>
            </template>

            <template v-if="default_tab === 2">
              <span
                class="deletesty"
                v-if="handleArrV.includes('删除') && row.Status === 2"
                @click="deleteRoadshow(row)"
                >删除</span
              >
              <span
                class="editsty"
                v-if="handleArrV.includes('拒绝理由') && row.Status === 3"
                @click="showRefuseReason(row)"
                >拒绝理由</span>
              <span
                class="editsty"
                v-if="handleArrV.includes('修改重提') &&  [3,5].includes(row.Status)"
                @click="resubmit(row)"
                >修改重提</span>
            </template>

            <template v-if="[3,4].includes(default_tab)">
              <span
                class="editsty"
                v-if="handleArrV.includes('修改')"
                @click="editActivityHandle(row)"
                >修改</span>
              <span
                class="deletesty"
                @click="delNormalHandle(row)"
                v-if="handleArrV.includes('删除')"
                >删除</span>
            </template>
          </template>
          <!-- 事项的操作栏由后端控制 -->
          <template v-if="default_tab===5">
              <span class="editsty" v-if="row.EditReason" @click="showReason(row)">最近修改记录</span>
              <span
                class="editsty"
                v-if="!row.ButtonAuth?.EditDisabled"
                @click="editActivityHandle(row)"
                >修改</span>
              <span
                class="deletesty"
                @click="delNormalHandle(row)"
                v-if="!row.ButtonAuth?.RemoveDisabled"
                >删除</span>
          </template>


          </template>
        </el-table-column>
        <template #empty >
          <div style="padding: 20px 0;">
            <img src="~@/assets/img/data_m/table_no.png" alt="" style="display:block;width:135px;height:90px;margin: 0 auto;">
            <span>暂无数据</span>
          </div>
        </template>
      </el-table>
      <el-col :span="24" class="toolbar">
        <m-page
          :total="total"
          :page_no="page_no"
          :pageSize="10"
          @handleCurrentChange="handleCurrentChange"
        />
      </el-col>
    </el-card>
    <el-card class="my-calendar-context" v-if="Role!=='admin'">
      <!-- 日程组件 -->
      <calendar
        ref="calendarRef"
        :eventList="eventList"
        @weekChange="getEventList"
        @editCallback="editCallback"
        @delAuthHandle="deleteRoadshow"
      >
        <template #left>
          <p class="left-title">我的日历</p>
        </template>
        <template #right>
          <el-button type="primary" @click="addMatterBtn" v-if="ENUM_RESEARCHLIST.includes(Role)||sellerList.includes(Role)">添加事项</el-button>
        </template>
      </calendar>
    </el-card>
    <!-- 添加事项弹窗 -->
    <addMatterDia 
      v-model:isShow="isAddMatterDiaShow" 
      :edit_matter_id="edit_matter_id" 
      :matter_form="matter_form"
      :matter_date="matter_date"
      @ensureCallback="refreshData"
    />
    <!-- 修改活动弹窗(修改重提) -->
    <addActivityBtnDia
      v-model:isShow="isActivityBtnDiaShow"
      :initData="resubmitData"
      :edit_id="edit_id"
      :edit_rs_id="edit_rs_id"
      @ensureCallback="refreshData"
    />

    <!-- 表格活动弹窗 -->
    <addActivityCellDia
      v-model:isShow="isActivityCellDiaShow"
      :initData="sonData"
      :edit_id="edit_id"
      :edit_rs_id="edit_rs_id"
      @ensureCallback="refreshData"
    />


    <!-- 拒绝弹窗 -->
    <el-dialog
      title="拒绝"
      v-model="isRefuseDiaShow"
      :modal-append-to-body="false"
      width="500px"
      @close="refuseDiaCancel"
    >
      <el-input
        type="textarea"
        v-model.trim="refuseReason"
        :autosize="{ minRows: 4, maxRows: 8 }"
        placeholder="请输入拒绝理由"
        resize="none"
      ></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="refuseDiaCancel">取消</el-button>
          <el-button type="primary" @click="refuseDiaConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 删除弹窗 -->
    <el-dialog
      title="删除"
      v-model="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>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDiaCancel">取消</el-button>
          <el-button type="primary" @click="deleteDiaConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 最近变更记录弹窗 -->
    <el-dialog
      title="最近修改记录"
      v-model="isReasonDiaShow"
      :modal-append-to-body="false"
      width="500px"
      @close="isReasonDiaShow=false"
    >
        <div class="reason-dialog-container">
            <div class="form-item">
                <p>修改原因</p>
                <div class="reason">
                    <textarea  rows="10" disabled v-model="modifyReason.text" placeholder="修改原因描述"></textarea>
                    <span class="hint">最近变更时间：{{modifyReason.time||''}}</span>
                </div>
                
            </div>
        </div>
    </el-dialog>
  </div>
</template>

<style lang="scss">
.my-calendar {
  .my-calendar-list {
    .tabs-type {
      display: flex;
      align-items: center;
      .type-item {
        border-bottom: 3px solid transparent;
        font-size: 16px;
        margin-right: 40px;
        padding: 4px 0;
        cursor: pointer;

        &.act {
          font-size: 18px;
          color: #000;
          font-weight: 600;
          border-color: #409EFF;
        }
      }
    }
  }
  .my-calendar-context {
    margin-top: 20px;
    .left-title {
      font-weight: 700;
      line-height: 40px;
      font-size: 16px;
    }
  }
  .reason-dialog-container{
      .form-item{
          display: flex;
          justify-content: space-between;
          margin:0 30px 30px;
          p{
              margin-top: 15px;
              word-break: keep-all;
          }
          .reason{
              margin-left: 15px;
              textarea{
                width:100%;
                resize: none;
                padding:5px;
                box-sizing: border-box;
                color: #999;
              }
              .hint{
                  display: inline-block;
                  margin-top: 5px;
                  color:#999;
              }
          }
          
      }
  }
}

.company-tip-poper {
  max-width: 400px;
}
</style>