<template>
  <div class="activity-cell-dia">
    <el-dialog
      v-dialogDrag
      :title="edit_id ? '修改活动' : '添加活动'"
      :visible.sync="isShow"
      :modal-append-to-body="false"
      @close="cancel"
      width="500px"
    >
      <el-form
        ref="form"
        :model="formData"
        :rules="rules"
        label-width="100px"
        label-position="left"
      >
        <!-- 第一个研究员 -->
        <el-form-item
          label="研究员"
          prop="selectResearchers[0].researcherId"
          v-if="formData.selectResearchers[0].researcherId"
          :rules="[
            { required: true, message: '请选择研究员', trigger: 'change' },
          ]"
          
        >
          <el-cascader
            v-model="formData.selectResearchers[0].researcherId"
            :options="researcherList"
            :show-all-levels="false"
            :disabled="isEditType !='RaiEdit'"
            :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="formData.selectResearchers[0].startDate"
              style="width: 100% !important"
              :clearable="false"
              :editable="false"
            >
              <template #icon-calendar>
                <i class="el-icon-date"></i>
              </template>
            </date-picker>
          </el-col>
          <el-col :span="12">
            <date-picker
              format="HH:mm"
              type="time"
              :show-second="false"
              v-model="formData.selectResearchers[0].startTime"
              style="width: 100% !important"
              :clearable="false"
              :editable="false"
            >
              <template #icon-calendar>
                <i class="el-icon-time"></i>
              </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="formData.selectResearchers[0].endDate"
              style="width: 100% !important"
              :clearable="false"
              :editable="false"
            >
              <template #icon-calendar>
                <i class="el-icon-date"></i>
              </template>
            </date-picker>
          </el-col>
          <el-col :span="12">
            <date-picker
              format="HH:mm"
              type="time"
              :show-second="false"
              v-model="formData.selectResearchers[0].endTime"
              style="width: 100% !important"
              :clearable="false"
              :editable="false"
            >
              <template #icon-calendar>
                <i class="el-icon-time"></i>
              </template>
            </date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="活动类型" prop="activityType">
          <el-select
            v-model="formData.activityType"
            placeholder="请选择活动类型"
            :disabled="isEditType =='RaiEdit'"
            @change="activityTypeChange"
          >
            <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="`${formData.activityType}形式`"
          v-if="formData.activityType === '路演' || formData.activityType === '沙龙'"
          prop="roadshowType"
          :rules="{ required: true, message: `请选择${formData.activityType}形式`, trigger: 'change' }"
        >
          <el-select
            v-model="formData.roadshowType"
            :placeholder="`请先选择${formData.activityType}形式`"
          >
            <el-option value="线上"></el-option>
            <el-option value="线下"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          :label="`${formData.activityType}平台`"
          v-if="formData.roadshowType === '线上' && (formData.activityType === '路演' || formData.activityType === '沙龙')"
          prop="roadshowPlatform"
          :rules="{ required: true, message: `请选择${formData.activityType}平台`, trigger: blur }"
        >
          <el-input
            v-model="formData.roadshowPlatform"
            :placeholder="`请输入${formData.activityType}平台(eg：进门财经、腾讯会议)`"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          :label="`${formData.activityType}城市`"
          v-if="formData.roadshowType === '线下' && (formData.activityType === '路演' || formData.activityType === '沙龙')"
          prop="roadshowCity"
          :rules="{ required: true, message: `请选择${formData.activityType}城市`, trigger: blur }"
        >
          <!-- <v-distpicker
            ref="roadshowCity"
            :province-source="province_sorce"
            :city-source="city_sorce"
            @selected="onChangeCity($event, 'roadshow')"
            hide-area
          ></v-distpicker> -->
          <search-dist-picker 
            :provinceInfo="formData.roadshowCity[0]"
            :cityInfo="formData.roadshowCity[1]"
            :areaInfo="formData.District||''"
            :showArea="isRaiRole"
            @selected="onChangeCity($event,'roadshow')"/>
        </el-form-item>
        <el-form-item
          label="客户名称"
          v-if="formData.activityType === '路演'"
          prop="companyName"
        >
          <el-autocomplete
            v-model="formData.companyName"
            popper-class="company-autocomplete"
            :fetch-suggestions="companySearch"
            :trigger-on-focus="false"
            placeholder="请输入客户名称"
            @select="companySelect"
            clearable
          >
            <template slot-scope="{ 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="formData.activityType === '路演' && formData.companyId && companyInfo">
            <!-- ficc角色看ficc信息 -->
            <template v-if="!isRaiRole">
                <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>
            </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="formData.activityType === '公开会议'"
          prop="meetingType"
        >
          <el-select
            v-model="formData.meetingType"
            placeholder="请先选择会议形式"
          >
            <el-option value="线上"></el-option>
            <el-option value="线下"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="会议平台"
          v-if="formData.meetingType === '线上' && formData.activityType === '公开会议'"
          prop="meetingPlatform"
        >
          <el-input
            v-model="formData.meetingPlatform"
            placeholder="请输入会议平台(eg：进门财经、腾讯会议)"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="会议城市"
          v-if="formData.meetingType === '线下' && formData.activityType === '公开会议'"
          prop="meetingCity"
        >
          <v-distpicker :province-source="province_sorce"
                :city-source="city_sorce" 
            ref="meetingCity"
            @selected="onChangeCity($event, 'meeting')"
            hide-area
          ></v-distpicker>
        </el-form-item>
        <el-form-item
          label="会议主题"
          v-if="formData.activityType === '公开会议' || formData.activityType === '沙龙'"
          prop="meetingTheme"
        >
          <el-input
            v-model="formData.meetingTheme"
            placeholder="请输入会议主题"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="合作方名称"
          v-if="formData.activityType === '公开会议'"
          prop="partnersName"
        >
          <el-input
            v-model="formData.partnersName"
            placeholder='请输入合作方名称（多个合作方用","隔开）'
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="活动类别"
          v-if="formData.activityType === '报告电话会'"
          prop="activityClass"
        >
          <!-- <el-select
            v-model="formData.activityClass"
            placeholder="请选择活动类别"
          >
            <el-option
              v-for="item in telTypeList"
              :key="item.ActivityTypeId"
              :label="item.ActivityTypeName"
              :value="item.ActivityTypeName"
            />
          </el-select> -->
          <el-cascader
                :props="activityClassProps"
                v-model="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
              v-model="
                formData.selectResearchers[researcherIdx].researcherId
              "
              :options="researcherList"
              :show-all-levels="false"
              :props="{
                expandTrigger: 'hover',
                children: 'ResearcherList',
                emitPath: false,
              }"
              clearable
              placeholder="请选择研究员"
              :key="cascaderIdx"
              @change="addUserCheckHandler"
            />
            <i class="el-icon-remove-outline" @click="delResearcher(researcherIdx)"/>
          </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="formData.selectResearchers[researcherIdx].startDate"
                style="width: 100% !important"
                :clearable="false"
                :editable="false"
              >
                <template #icon-calendar>
                  <i class="el-icon-date"></i>
                </template>
              </date-picker>
            </el-col>
            <el-col :span="12">
              <date-picker
                format="HH:mm"
                type="time"
                :show-second="false"
                v-model="formData.selectResearchers[researcherIdx].startTime"
                style="width: 100% !important"
                :clearable="false"
                :editable="false"
              >
                <template #icon-calendar>
                  <i class="el-icon-time"></i>
                </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="formData.selectResearchers[researcherIdx].endDate"
                style="width: 100% !important"
                :clearable="false"
                :editable="false"
              >
                <template #icon-calendar>
                  <i class="el-icon-date"></i>
                </template>
              </date-picker>
            </el-col>
            <el-col :span="12">
              <date-picker
                format="HH:mm"
                type="time"
                :show-second="false"
                v-model="formData.selectResearchers[researcherIdx].endTime"
                style="width: 100% !important"
                :clearable="false"
                :editable="false"
              >
                <template #icon-calendar>
                  <i class="el-icon-time"></i>
                </template>
              </date-picker>
            </el-col>
          </el-form-item>
        </div>
        <!-- 添加研究员按钮 -->
        <div @click="addResearcher" class="add-box" v-if="['路演','公开会议'].includes(formData.activityType) && !edit_id ">
          <i class="el-icon-circle-plus-outline" style="font-size: 18px;margin-right: 5px;"/>
          <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>

<script>
import { activityCellDiaConfig,confirmDiaLink,confirmDiaRai } from "../roleConfig";
import { roadshowInterence,ficcManageInterface } from "@/api/api.js";
import publicMixins from '../roleConfig/mixins';
import { constrainPoint } from "@fullcalendar/common";
//自定义省市数据
//import{province_sorce,city_sorce} from '@/utils/distpicker'; 
import searchDistPicker from '@/components/searchDistPicker.vue';
// 定义初始表单数据
let 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: '',
    },
  ],
};
export default {
  props: {
    isShow: {
      type: Boolean,
      require: true,
    },
    initData:{
      type: Object,
      default: null,
    },
    edit_id: {
      type: Number,
      default: 0,
    },
    edit_rs_id: {
      type: Number,
      default: 0,
    },
    isEditType:{
      type: String,
      default: '',
    }
  },
  mixins: [publicMixins],
  components:{searchDistPicker},
  data() {
    return {
      formData: { 
        ...initFormData,
        activityType: activityCellDiaConfig[localStorage.getItem("Role")].defaultActivityType,
        selectResearchers: [
          // 选择的研究员
          {
            researcherId: '',
            startDate: '',
            startTime: '',
            endDate: '',
            endTime: '',
          },
        ],
      },
      researcherList: [], // 研究员列表
      activityTypeList: [],//活动类型
      telTypeList: [],//电话会所有类别
      cascaderIdx: 0, // 解决报错
      permission: null, // 当前角色权限
      companyInfo: null,//选择的客户详情
/*       province_sorce:province_sorce,
      city_sorce:city_sorce */
    };
  },
  computed: {
    // 除去第一个研究员的其他研究员索引
    addResearchersIdx() {
      return this.formData.selectResearchers
        .map((item, index) => index)
        .slice(1);
    },
    // 将研究员列表中的研究员提取出来组成新数组
    allResearcher() {
      return [].concat.apply([], this.researcherList.map(item=>item.ResearcherList))
    },
  },
  methods: {
    // 获取研究员列表
    async getResearcherList() {
      // 发送请求
      const res = await roadshowInterence.getResearcherList();
      if (res.Ret === 200) {

        /* this.researcherList =  res.Data && res.Data.filter(item => item.GroupName !== 'ficc全体').map(group => ({
          ...group,
          label: group.GroupName,
          ResearcherList: group.ResearcherList ? group.ResearcherList.map(child => ({
            ...child,
            label: child.RealName,
            value: child.AdminId
          })) : []
        })) */
        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
        }]
      }
    },
    // 对获取到的研究员列表做处理
    formatResearcherList(list) {
      /* this.researcherList =  list && list.filter(item => item.GroupName !== 'ficc全体').map(group => ({
        ...group,
        label:group.GroupName,
        ResearcherList: group.ResearcherList && group.ResearcherList.map(child => ({
          ...child,
          label: child.RealName,
          value: child.AdminId
        }))
      })) */
      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.filter((group) => group.GroupName !== "ficc全体");

    },
    // 取消按钮
    cancel() {
      this.formData = { 
        ...initFormData,
        activityType: activityCellDiaConfig[localStorage.getItem("Role")].defaultActivityType
      };
      this.researcherList = [];
      this.cascaderIdx++;
      this.$refs.form.resetFields();
      this.$emit("update:isShow", false);
    },
    // 确认按钮
    async confirm() {
      // 校验表单
      await this.$refs.form.validate();

      if(this.formData.companyName && !this.formData.companyId) return this.$message.warning('请选择客户');
      if(this.isRaiRole&&this.formData.roadshowType==='线下'&&!this.formData.District) return this.$message.warning('请选择路演城市')
      // 设置参数
      let parmas = null;

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

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

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

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

      //this.edit_id ? this.$message.warning('提交成功') : confirmDiaLink(text, content, query);
      if(this.edit_id){
        this.$message.warning('提交成功')
      }else{
        if(this.formData.activityType!=='路演' && this.formData.activityType!=='沙龙'){
            confirmDiaLink(text, content, query)
            this.$emit('ensureCallback');
            this.cancel();
            return 
        }
        //判断所选研究员是否有权益
        const ResearcherIds = this.formData.selectResearchers.map(i=>i.researcherId)
        const ResearcherTypes = ResearcherIds.map(i=>this.findType(i))
        //既有权益研究员的路演，又有ficc研究员路演时，提示弹窗
        if(ResearcherTypes.includes('rai')&&ResearcherTypes.includes('ficc')){
            const { text, content, query } = this.setDynamicLink(
                'ficc&rai路演'
            );
            confirmDiaLink(text, content, query)
        //只提交权益研究员的路演时，提示弹窗：
        }else if(ResearcherTypes.includes('rai')){
            confirmDiaRai()
        //只提交ficc研究员的路演时，提示弹窗：（维持原来的不变）
        }else{
            confirmDiaLink(text, content, query)
        } 
      }
      this.$emit('ensureCallback');
      this.cancel();

    },

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

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

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

      this.$refs.form.clearValidate();
    },

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

    // 客户名称搜索
    async companySearch(query, cb) {
      cb([]);
      if (!query) return;
        const res = await roadshowInterence.searchRoadshowCompany({
          KeyWord: query,
        });
        if (res.Ret === 200) {
          let arr = res.Data || [];
          if (!arr.length) {
            cb([{ nodata: true }]);
          } else {
            cb(arr);
          }
        }
    },
    
    // 选择客户
    async companySelect(e) {
      if (e.nodata) return;
      this.formData.companyId = e.CompanyId;
      this.formData.companyName = e.CompanyName;
      this.formData.englishCompany = e.EnglishCompany

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

    },
    /* // 研究员id查找研究员名
    findResearcherById(id){
      return this.allResearcher.find(researcher => researcher.AdminId===id).RealName
    } */
  },
  created() {
    this.permission = activityCellDiaConfig[localStorage.getItem("Role")];
  },
  watch: {
    // 解决研究员列表,直接赋值时报错(原因:组件没有重新渲染)
    "formData.selectResearchers"() {
      this.cascaderIdx++;
    },
    // 默认数据改变时,重新赋值
    initData(val){
      this.formData={...this.formData,...val}
    },
    isShow(newval) {
      newval && this.getResearcherList();
      newval && this.getTypeList();
    }
  },
};
</script>

<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;
      }
      .el-icon-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>