<script setup>
import { ref,computed,reactive,watch } from "vue";
import {ElMessage} from "element-plus"
import moment from "moment"
import DatePicker from 'vue-datepicker-next';
import _ from 'lodash'
import { Calendar,Clock,CirclePlus,Remove } from '@element-plus/icons-vue'

import { activityCellDiaConfig,confirmDiaLink } from "../roleConfig";
import { roadshowInterence } from "@/api/api.js";
import searchDistPicker from '@/components/searchDistPicker.vue';
import {researcherActivityHook} from '../roleConfig/hook.js';

// 定义初始表单数据
const initFormData = {
  // 表单数据
  activityType: activityCellDiaConfig[localStorage.getItem("Role")].defaultActivityType, // 活动类型
  roadshowType: "", // 路演形式
  roadshowPlatform: "", // 路演平台
  roadshowCity: "", // 路演城市
  companyId: '', // 客户id
  companyName: "", // 客户名称
  meetingType: "", // 会议形式
  meetingPlatform: "", // 会议平台
  meetingCity: "", // 会议城市
  meetingTheme: "", // 会议主题
  partnersName: "", // 合作方名称
  activityClass: "", // 活动类别
  selectResearchers: [
    // 选择的研究员
    {
      researcherId: '',
      startDate: '',
      startTime: '',
      endDate: '',
      endTime: '',
    },
  ],
};

const props = defineProps({
  isShow: {
    type: Boolean,
    require: true,
  },
  initData:{
    type: Object,
    default: null,
  },
  edit_id: {
    type: Number,
    default: 0,
  },
  edit_rs_id: {
    type: Number,
    default: 0,
  }
})

const emits=defineEmits(['update:isShow','ensureCallback'])

const form=reactive({formData: { 
  ...initFormData,
  activityType: activityCellDiaConfig[localStorage.getItem("Role")].defaultActivityType,
  selectResearchers: [
    // 选择的研究员
    {
      researcherId: '',
      startDate: '',
      startTime: '',
      endDate: '',
      endTime: '',
    },
  ],
}})
const researcherList=ref([]) // 研究员列表
const telTypeList=ref([])//电话会所有类别
const cascaderIdx=ref(0) // 解决报错
const permission=ref(null) // 当前角色权限
const companyInfo=ref(null)//选择的客户详情

// 除去第一个研究员的其他研究员索引
const addResearchersIdx=computed(()=>{
  return form.formData.selectResearchers
  .map((item, index) => index)
  .slice(1);
})
// 将研究员列表中的研究员提取出来组成新数组
const allResearcher=computed(()=>{
  return [].concat.apply([], researcherList.value.map(item=>item.ResearcherList))
})

watch(()=>props.isShow,(newval)=>{
  newval && getResearcherList();
  newval && getTypeList();
})
// 解决研究员列表,直接赋值时报错(原因:组件没有重新渲染)
watch(()=>form.formData.selectResearchers,(newval)=>{
  cascaderIdx.value++
})
// 默认数据改变时,重新赋值
watch(()=>props.initData,(newval)=>{
  console.log(newval,'newval');
  form.formData={...form.formData,...newval}
  console.log(form.formData,'form.formData');
})


const formRef=ref(null)

// 获取研究员列表
const getResearcherList=async()=>{
  // 发送请求
  const res = await roadshowInterence.getResearcherList();
  if (res.Ret === 200) {

    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 formatResearcherList=(list)=>{
  list.forEach((group) => {
    // 对组做处理
    group.label = group.GroupName;
    // 如果有列表
    if (group.ResearcherList) {
      group.ResearcherList.forEach((item) => {
        // 对研究员做处理
        item.label = item.RealName;
        item.value = item.AdminId;
      });
    } else {
      // 没有列表
      group.value = group.GroupId;
    }
  });
  return list;
}
// 取消按钮
const cancel=()=>{
  form.formData = { 
    ...initFormData,
    activityType: activityCellDiaConfig[localStorage.getItem("Role")].defaultActivityType
  };
  researcherList.value = [];
  cascaderIdx.value++;
  formRef.value.resetFields();
  emits("update:isShow", false);
}
// 确认按钮
const confirm=async()=>{
  // 校验表单
  await formRef.value.validate();

  if(form.formData.companyName && !form.formData.companyId) return ElMessage.warning('请选择客户');
  // 设置参数
  let parmas = null;

  const param_research = form.formData.selectResearchers.map(item=>({
    ResearcherId: item.researcherId,
    ResearcherName: findResearcherName(item.researcherId),
    StartDate:moment(item.startDate).format('YYYY-MM-DD'),
    EndDate: moment(item.endDate).format('YYYY-MM-DD'),
    StartTime: moment(item.startTime).format('HH:mm:ss'),
    EndTime: moment(item.endTime).format('HH:mm:ss'),
    StartWeek: moment(item.startDate).format('ddd'),
    EndWeek: moment(item.endDate).format('ddd'),
  }));

  const dynaic_city_param = {
    '公开会议': form.formData.meetingCity,
    '路演': form.formData.roadshowCity,
  }

  parmas = {
    ActivityType: form.formData.activityType,
    ActivityCategory: form.formData.activityClass[form.formData.activityClass.length-1],
    City: ['公开会议','路演'].includes(form.formData.activityType) ? dynaic_city_param[form.formData.activityType][1] : '',
    Province: ['公开会议','路演'].includes(form.formData.activityType) ? dynaic_city_param[form.formData.activityType][0] : '',
    CooperationName: form.formData.partnersName,
    Theme: form.formData.meetingTheme,
    RoadshowType: form.formData.activityType === '路演' ? form.formData.roadshowType : form.formData.meetingType,
    RoadshowPlatform: form.formData.activityType === '路演' ? form.formData.roadshowPlatform : form.formData.meetingPlatform,
    CompanyId: form.formData.companyId || 0,
    CompanyName: form.formData.companyName || '',
    ResearcherList: param_research,
    EnglishCompany:form.formData.englishCompany
  };
  
  // 发送请求
  const res =  props.edit_id
  ? await roadshowInterence.editRoadshow({
      ...parmas,
      RsCalendarId: props.edit_id,
      RsCalendarResearcherId: props.edit_rs_id,
      EditType: ['公开会议', '路演'].includes(form.formData.activityType) ? 2 : 1
    }) : await roadshowInterence.addRoadshow(parmas);

  if (res.Ret !== 200) return
  const { text,content,query } = setDynamicLink(form.formData.activityType);

  props.edit_id ? ElMessage.warning('提交成功') : confirmDiaLink(text, content, query);

  emits('ensureCallback');
  cancel();

}

// 添加研究员点击
const addResearcher=()=>{

  const { startDate,startTime,endDate,endTime } = form.formData.selectResearchers[0];//默认添加时间同步

  form.formData.selectResearchers.push({
    researcherId: null,
    startDate,
    startTime,
    endDate,
    endTime,
  });
}
// 删除研究员点击
const delResearcher=(index)=>{
  form.formData.selectResearchers.splice(index, 1);
}
// 活动类型改变
const activityTypeChange=()=>{
  // 清空部分表单内容
  form.formData.roadshowType = "";
  form.formData.roadshowPlatform = "";
  form.formData.roadshowCity = "";
  form.formData.companyId = '';
  form.formData.companyName = "";
  form.formData.meetingType = "";
  form.formData.meetingPlatform = "";
  form.formData.meetingCity = "";
  form.formData.meetingTheme = "";
  form.formData.partnersName = "";
  form.formData.activityClass = "";
  form.formData.selectResearchers = form.formData.selectResearchers.splice(0,1);

  formRef.value.clearValidate();
}

//获取电话会所有类别
const getTypeList=async()=>{
  const res = await roadshowInterence.getTelList();
  if (res.Ret !== 200) return
  telTypeList.value=res.Data;
}

// 客户名称搜索
const companySearch=async(query, cb)=>{
  cb([]);
  if (!query) return;
    const res = await roadshowInterence.searchRoadshowCompany({
      KeyWord: query,
    });
    if (res.Ret === 200) {
      let arr = res.Data || [];
      console.log(arr);
      if (!arr.length) {
        cb([{ nodata: true }]);
      } else {
        cb(arr);
      }
    }
}

// 选择客户
const companySelect=async(e)=>{
  if (e.nodata) return;
  form.formData.companyId = e.CompanyId;
  form.formData.companyName = e.CompanyName;
  form.formData.englishCompany = e.EnglishCompany

  const { Data }  = await roadshowInterence.componyDetail({ 
    CompanyId: form.formData.companyId,
    EnglishCompany:e.EnglishCompany
  });
  companyInfo.value = Data;

}
// 研究员id查找研究员名
const findResearcherById=(id)=>{
  return allResearcher.value.find(researcher => researcher.AdminId===id).RealName
}

permission.value = activityCellDiaConfig[localStorage.getItem("Role")];

const HOOK = researcherActivityHook({form,companyInfo,formRef,researcherList})
const {rules,activityClassProps,setDynamicLink,addUserCheckHandler,onChangeCity,findResearcherName}=HOOK

</script>

<template>
  <div class="activity-cell-dia">
    <el-dialog
      v-dialogDrag
      :title="props.edit_id ? '修改活动' : '添加活动'"
      :model-value="props.isShow"
      :modal-append-to-body="false"
      @close="cancel"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form.formData"
        :rules="rules"
        label-width="100px"
        label-position="left"
      >
        <!-- 第一个研究员 -->
        <el-form-item
          label="研究员"
          prop="selectResearchers[0].researcherId"
          v-if="form.formData.selectResearchers[0].researcherId"
          :rules="[
            { required: true, message: '请选择研究员', trigger: 'change' },
          ]"
          
        >
          <el-cascader
            v-model="form.formData.selectResearchers[0].researcherId"
            :options="researcherList"
            :show-all-levels="false"
            disabled
            :props="{
              expandTrigger: 'hover',
              children: 'ResearcherList',
              emitPath: false,
            }"
            clearable
            placeholder="请选择研究员"
            :key="cascaderIdx"
          />
        </el-form-item>
        <el-form-item
          label="开始时间"
          prop="selectResearchers[0].startTime"
          :rules="[
            { required: true, message: '请选择开始时间', trigger: 'blur' },
          ]"
        >
          <el-col :span="12">
            <date-picker
              format="MM.DD(ddd)"
              v-model:value="form.formData.selectResearchers[0].startDate"
              style="width: 100% !important"
              :clearable="false"
              :editable="false"
            >
              <template #icon-calendar>
                <el-icon><Calendar /></el-icon>
              </template>
            </date-picker>
          </el-col>
          <el-col :span="12">
            <date-picker
              format="HH:mm"
              type="time"
              :show-second="false"
              v-model:value="form.formData.selectResearchers[0].startTime"
              style="width: 100% !important"
              :clearable="false"
              :editable="false"
            >
              <template #icon-calendar>
                <el-icon><Clock /></el-icon>
              </template>
            </date-picker>
          </el-col>
        </el-form-item>
        <el-form-item
          label="结束时间"
          prop="selectResearchers[0].endTime"
          :rules="[
            { required: true, message: '请选择结束时间', trigger: 'blur' },
          ]"
        >
          <el-col :span="12">
            <date-picker
              format="MM.DD(ddd)"
              v-model:value="form.formData.selectResearchers[0].endDate"
              style="width: 100% !important"
              :clearable="false"
              :editable="false"
            >
              <template #icon-calendar>
                <el-icon><Calendar /></el-icon>
              </template>
            </date-picker>
          </el-col>
          <el-col :span="12">
            <date-picker
              format="HH:mm"
              type="time"
              :show-second="false"
              v-model:value="form.formData.selectResearchers[0].endTime"
              style="width: 100% !important"
              :clearable="false"
              :editable="false"
            >
              <template #icon-calendar>
                <el-icon><Clock /></el-icon>
              </template>
            </date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="活动类型" prop="activityType">
          <el-select
            v-model="form.formData.activityType"
            placeholder="请选择活动类型"
            @change="activityTypeChange"
            :disabled="!!props.edit_id"
          >
            <el-option
              v-for="(type, index) in permission.activityTypeList"
              :key="index"
              :label="type"
              :value="type"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="路演形式"
          v-if="form.formData.activityType === '路演'"
          prop="roadshowType"
        >
          <el-select
            v-model="form.formData.roadshowType"
            placeholder="请先选择路演形式"
          >
            <el-option value="线上"></el-option>
            <el-option value="线下"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="路演平台"
          v-if="form.formData.roadshowType === '线上' && form.formData.activityType === '路演'"
          prop="roadshowPlatform"
        >
          <el-input
            v-model="form.formData.roadshowPlatform"
            placeholder="请输入路演平台(eg：进门财经、腾讯会议)"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="路演城市"
          v-if="form.formData.roadshowType === '线下' && form.formData.activityType === '路演'"
          prop="roadshowCity"
        >
          <search-dist-picker 
            @selected="onChangeCity($event,'roadshow')"/>
        </el-form-item>
        <el-form-item
          label="客户名称"
          v-if="form.formData.activityType === '路演'"
          prop="companyName"
        >
          <el-autocomplete
            v-model="form.formData.companyName"
            popper-class="company-autocomplete"
            :fetch-suggestions="companySearch"
            :trigger-on-focus="false"
            placeholder="请输入客户名称"
            @select="companySelect"
            clearable
          >
            <template #default="{ item }">
              <div v-if="item.nodata" style="text-align: center">暂无数据</div>
              <div v-else>
                <div>{{ item.CompanyName }}</div>
              </div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <!-- 客户信息 -->
        <div class="company-info" v-if="form.formData.activityType === '路演' && form.formData.companyId && companyInfo">
          <template v-if="companyInfo.EnglishCompany===1">
            <p>所属国家：{{companyInfo.EnglishCountry}}</p>
            <p>累计点击量：{{companyInfo.EnglishViewTotal}}</p>
          </template>
          <template v-else>
            <p>客户状态：{{ companyInfo.Status }}</p>
            <p>所属行业：{{ companyInfo.IndustryName }}</p>
            <p>开通品种：{{ companyInfo.PermissionName }}</p>
            <p>累计报告阅读次数：{{ companyInfo.ReportReadTotal }}</p> 
          </template>
        </div>
        <el-form-item
          label="会议形式"
          v-if="form.formData.activityType === '公开会议'"
          prop="meetingType"
        >
          <el-select
            v-model="form.formData.meetingType"
            placeholder="请先选择会议形式"
          >
            <el-option value="线上"></el-option>
            <el-option value="线下"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="会议平台"
          v-if="form.formData.meetingType === '线上' && form.formData.activityType === '公开会议'"
          prop="meetingPlatform"
        >
          <el-input
            v-model="form.formData.meetingPlatform"
            placeholder="请输入会议平台(eg：进门财经、腾讯会议)"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="会议城市"
          v-if="form.formData.meetingType === '线下' && form.formData.activityType === '公开会议'"
          prop="meetingCity"
        >
          <v-distpicker 
            ref="meetingCity"
            @selected="onChangeCity($event, 'meeting')"
            hide-area
          ></v-distpicker>
        </el-form-item>
        <el-form-item
          label="会议主题"
          v-if="form.formData.activityType === '公开会议'"
          prop="meetingTheme"
        >
          <el-input
            v-model="form.formData.meetingTheme"
            placeholder="请输入会议主题"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="合作方名称"
          v-if="form.formData.activityType === '公开会议'"
          prop="partnersName"
        >
          <el-input
            v-model="form.formData.partnersName"
            placeholder='请输入合作方名称（多个合作方用","隔开）'
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="活动类别"
          v-if="form.formData.activityType === '报告电话会'"
          prop="activityClass"
        >
          <el-cascader
                :props="activityClassProps"
                v-model="form.formData.activityClass"
                :options="telTypeList">
            </el-cascader>
        </el-form-item>
        <!-- 新增的研究员 -->
        <div
          v-for="researcherIdx in addResearchersIdx"
          :key="researcherIdx"
          class="add-researcher-box"
        >
          <el-form-item
            label="研究员"
            :prop="`selectResearchers[${researcherIdx}].researcherId`"
            :rules="[
              { required: true, message: '请选择研究员', trigger: 'change' },
            ]"
          >
            <el-cascader
              style="max-width: 340px;"
              v-model="
                form.formData.selectResearchers[researcherIdx].researcherId
              "
              :options="researcherList"
              :show-all-levels="false"
              :props="{
                expandTrigger: 'hover',
                children: 'ResearcherList',
                emitPath: false,
              }"
              clearable
              placeholder="请选择研究员"
              :key="cascaderIdx"
              @change="addUserCheckHandler"
            />
            <el-icon class="remove-outline" @click="delResearcher(researcherIdx)"><Remove /></el-icon>
          </el-form-item>
          <el-form-item label="开始时间"
          :prop="`selectResearchers[${researcherIdx}].startTime`"
          :rules="[
            { required: true, message: '请选择开始时间', trigger: 'change' },
          ]">
            <el-col :span="12">
              <date-picker
                format="MM.DD(ddd)"
                v-model:value="form.formData.selectResearchers[researcherIdx].startDate"
                style="width: 100% !important"
                :clearable="false"
                :editable="false"
              >
                <template #icon-calendar>
                  <el-icon><Calendar /></el-icon>
                </template>
              </date-picker>
            </el-col>
            <el-col :span="12">
              <date-picker
                format="HH:mm"
                type="time"
                :show-second="false"
                v-model:value="form.formData.selectResearchers[researcherIdx].startTime"
                style="width: 100% !important"
                :clearable="false"
                :editable="false"
              >
                <template #icon-calendar>
                  <el-icon><Clock /></el-icon>
                </template>
              </date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="结束时间"
          :prop="`selectResearchers[${researcherIdx}].endTime`"
          :rules="[
            { required: true, message: '请选择结束时间', trigger: 'change' },
          ]">
            <el-col :span="12">
              <date-picker
                format="MM.DD(ddd)"
                v-model:value="form.formData.selectResearchers[researcherIdx].endDate"
                style="width: 100% !important"
                :clearable="false"
                :editable="false"
              >
                <template #icon-calendar>
                  <el-icon><Calendar /></el-icon>
                </template>
              </date-picker>
            </el-col>
            <el-col :span="12">
              <date-picker
                format="HH:mm"
                type="time"
                :show-second="false"
                v-model:value="form.formData.selectResearchers[researcherIdx].endTime"
                style="width: 100% !important"
                :clearable="false"
                :editable="false"
              >
                <template #icon-calendar>
                  <el-icon><Clock /></el-icon>
                </template>
              </date-picker>
            </el-col>
          </el-form-item>
        </div>
        <!-- 添加研究员按钮 -->
        <div @click="addResearcher" class="add-box" v-if="['路演','公开会议'].includes(form.formData.activityType) && !props.edit_id ">
          <el-icon style="font-size: 18px; margin-right: 5px"><CirclePlus /></el-icon>
          <span>添加研究员</span>
        </div>
      </el-form>
      <div class="btn-group">
        <el-button type="primary" plain @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss">
.activity-cell-dia {
  .el-form {
    .el-cascader,
    .el-select,
    .el-autocomplete,
    .el-input {
      width: 100%;
    }
    .company-info {
      border: 1px solid #b3d8ff;
      background: #ecf5ff;
      padding: 10px;
      margin-bottom: 20px;
      p {
        margin: 6px 0;
        text-indent: -70px;
        margin-left: 70px;
      }
    }
    .distpicker-address-wrapper {
      display: flex;
      label:nth-child(-n + 2) {
        padding: 0 5px;
        flex: 50%;
        select {
          width: 100%;
        }
      }
    }
    .add-researcher-box .el-form-item .el-form-item__content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .el-cascader {
        padding-right: 20px;
      }
      .remove-outline {
        font-size: 20px;
        cursor: pointer;
        color: #f00;
      }
    }
    .el-col {
      padding: 0 5px;
    }
  }
  .add-box {
    width: 100px;
    display: flex;
    align-items: center;
    color: #5882ef;
    cursor: pointer;
    img {
      width: 16px;
      height: 16px;
      margin-right: 10px;
    }
  }
  .btn-group {
    margin: 20px 0;
    text-align: center;
    .el-button {
      width: 140px;
    }
  }
}
</style>