import { useCallback, useReducer } from 'react';
import {
  addMsgResStrategy,
  editMsgResStrategy,
  getMsgResStrategy,
  searchMsgResStrategy,
  getMpClickMenuList,
  searchImMsgResStrategy,
  delMsgResStrategy,
  searchDetails,
  Params,
  editEnabled,
  editMsgResStrategyIm,
  replyStrategyPreview,
  importPushExcle,
} from '@/services/operating/interact';
import { useAjax } from '@/Hook/useAjax';
type State = {
  msgContents: any[]; //当前出入的数据
  textKey: string; //关键字
  resDelayHours: number; //时
  resDelayMinutes: number; //分
  resDelaySecond: number; //秒
  strategyDesc: string; //策略描述
  textKeyStrategy: number; //全匹配 半匹配
  msgStrategy: number; //推送方式
  eventType: number; //触发条件
  delId: number[]; //上次删除的ID集合
  menuKeys: string[];
  fansSelectValue?: any;
  fansType:0|1
};
export type Action = {
  type:
    | 'addList'
    | 'delList'
    | 'edit'
    | 'up'
    | 'down'
    | 'setTextKey'
    | 'setMenuKeys'
    | 'setTime'
    | 'setStrategyDesc'
    | 'setMsgStrategy'
    | 'setTextKeyStrategy'
    | 'setEventType'
    | 'initData'
    | 'setFansSelectValue'
    | 'setFansType'
  params: any;
};
export function reducer(state: State, action: Action) {
  let { msgContents } = state;
  let { type, params } = action;
  let newArr: any[] = [];
  let newState = JSON.parse(JSON.stringify(state));
  switch (type) {
    case 'addList':
      newArr = [...msgContents];
      console.log('ADDLIST', msgContents);
      let indexId: number;
      let newIds: any[] = [];
      if (state?.delId?.length > 0) {
        //假如delId存在代表删除过数据，取删除的数据的Id做为新素材的ID避免重复ID
        console.log('从删除的数组里取序号');
        indexId = state.delId[0];
        newIds = state.delId.filter((id) => id !== state.delId[0]);
      } else {
        //假如不存在那就是第一次新建只要设ID为数组的长度+1就行
        indexId = msgContents.length + 1;
        console.log('新增序号');
      }
      // console.log(params.list,'params.list')
      if (params.list.index && !params.list.indexId && newArr?.length > 0) {
        //index存在indexId不存在表示是插入
        console.log('按位置插入');
        newArr.forEach((item: any, index: number) => {
          if (item.indexId === params.list.index) {
            newArr.splice(index + 1, 0, { ...params.list, indexId });
          }
        });
      } else {
        //最后插入
        console.log('最后插入', params.list, indexId);
        newArr.push({ ...params.list, indexId });
      }
      return { ...state, msgContents: newArr, delId: newIds };
    case 'edit':
      console.log(params, 'params');
      newArr = [...msgContents];
      newArr.forEach((item: any, index: number) => {
        if (item.indexId === params.list.index) {
          newArr.splice(index, 1, { ...item, ...params.list });
        }
      });
      return { ...state, msgContents: newArr };
    case 'delList':
      let delId = [...state.delId, params.indexId]; //存放本次删除的ID以备新增时使用
      return {
        ...state,
        msgContents: msgContents.filter((item: any) => item.indexId !== params.indexId),
        delId,
      };
    case 'up':
      newArr = [...msgContents];
      msgContents.forEach((item: any, index: number) => {
        if (item.indexId === params.indexId) {
          newArr[index - 1] = item;
          newArr[index] = msgContents[index - 1];
        }
      });
      return { ...state, msgContents: newArr };
    case 'down':
      newArr = [...msgContents];
      msgContents.forEach((item: any, index: number) => {
        if (item.indexId === params.indexId) {
          newArr[index + 1] = item;
          newArr[index] = msgContents[index + 1];
        }
      });
      return { ...state, msgContents: newArr };
    case 'setTextKey':
      return { ...state, textKey: params.textKey };
    case 'setMenuKeys':
      return { ...state, menuKeys: params.menuKeys };
    case 'setTime':
      Object.keys(params).forEach((key) => {
        newState[key] = params[key];
      });
      return { ...newState };
    case 'setStrategyDesc':
      return { ...state, strategyDesc: params.strategyDesc };
    case 'setMsgStrategy':
      return { ...state, msgStrategy: params.msgStrategy };
    case 'setTextKeyStrategy':
      return { ...state, textKeyStrategy: params.textKeyStrategy };
    case 'setEventType':
      return { ...state, eventType: params.eventType };
    case 'setFansSelectValue':
      return { ...state, fansSelectValue: params.fansSelectValue };
    case 'setFansType':
      return { ...state, fansType: params.fansType };
    case 'initData':
      return { ...params.data.data };
    default:
      return state;
  }
}
const defultData = {
  msgContents: [],
  textKey: '',
  resDelayHours: 0,
  resDelayMinutes: 0, //分
  resDelaySecond: 0, //秒
  strategyDesc: '',
  msgStrategy: 0,
  textKeyStrategy: 0,
  eventType: 0,
  enabled: true,
  delId: [],
  fansType:1,
  fansSelectValue:{
    fansFilterOsType: [],//操作系统
    fansFilterMember: '',//是否是会员
    fansFilterSex: [],//粉丝性别
    fansFilterSubscribeTimeType: '',//关注时间
    fansFilterSubscribeTimeBegin: '',//关注起始时间
    fansFilterSubscribeTimeEnd: '',//关注截至时间
    fansFilterRechargeCountMin: '',//充值次数（最少）
    fansFilterRechargeCountMax: '',//充值次数（最多）
    fansFilterRechargeTimeMin: '',//上次充值时间（最少 n天内）
    fansFilterRechargeTimeMax: '',//上次充值时间（最大 n天内）
    fansFilterRechargeMin: '',//最低充值金额
    fansFilterRechargeMax: '',//最大充值金额
    fansFilterCoinCountMin: '',//最低书币余额
    fansFilterCoinCountMax: '',//最高书币余额
    fansFilterActiveTimeMin: '',//上次活跃距今时间（最低）
    fansFilterActiveTimeMax: '',//上次活跃距今时间（最高）
    rechargeType: '',//充值情况选项
    dayType: '',//天数选项
    countType: '',//书币选项
    timeType: ''//时间选项
}
};
export default function useInteract() {
  const [state, dispatch] = useReducer(reducer, defultData);
  const addMsg = useAjax((params: Params) => addMsgResStrategy(params), { msgNmae: '添加' });
  const editMsg = useAjax((params: Params) => editMsgResStrategy(params), { msgNmae: '编辑' });
  const editMsgIm = useAjax((params: Params) => editMsgResStrategyIm(params), { msgNmae: '保存' });
  const delMsg = useAjax((params: { strategyId: string }) => delMsgResStrategy(params), {
    msgNmae: '删除',
  });
  const getMsg = useAjax((params: { strategyId: string }) => getMsgResStrategy(params));
  const searchMsg = useAjax((params: { mpId: string; eventType?: number; strategyDesc?: string }) =>
    searchMsgResStrategy(params),
  );
  const searchImMsg = useAjax((params: { mpId: string; eventType?: number; textKey?: string }) =>
    searchImMsgResStrategy(params),
  );
  const searchDetail = useAjax((params: { strategyId: string }) => searchDetails(params));
  const getMenuList = useAjax((params: { mpId: string }) => getMpClickMenuList(params));
  const postReplyStrategyPreview = useAjax(
    (params: { fansIds?: string; mpIds: any[] }) => replyStrategyPreview(params),
    { msgNmae: '预览' },
  );
  const upLoad = useAjax((params: any) => importPushExcle(params), { msgNmae: '导入' });

  const setEnabled = useAjax(
    (params: { strategyId: number; enabled: boolean }) => editEnabled(params),
    { msgNmae: '设置' },
  );
  /** 初始化数据*/
  const initData = useCallback((data: any) => {
    console.log('initData====>')
    dispatch({ type: 'initData', params: { data } });
  }, []);
  /** 添加list*/
  const addList = useCallback((list: any) => {
    console.log('插入list', list);
    dispatch({ type: 'addList', params: { list } });
  }, []);
  const editList = useCallback((list: any) => {
    console.log(list);
    dispatch({ type: 'edit', params: { list } });
  }, []);
  /**删除list */
  const delList = useCallback((indexId: any) => {
    dispatch({ type: 'delList', params: { indexId } });
  }, []);
  /** 向上移动*/
  const up = useCallback((indexId: any) => {
    dispatch({ type: 'up', params: { indexId } });
  }, []);
  /** 向下移动*/
  const down = useCallback((indexId: any) => {
    dispatch({ type: 'down', params: { indexId } });
  }, []);
  /** 设置关键字*/
  const setTextKey = useCallback((textKey: string) => {
    dispatch({ type: 'setTextKey', params: { textKey } });
  }, []);
  /** 设置菜单点击*/
  const setMenuKeys = useCallback((menuKeys: string[]) => {
    dispatch({ type: 'setMenuKeys', params: { menuKeys } });
  }, []);
  /** 设置时间*/
  const setTime = useCallback((time: { [name: string]: any }) => {
    dispatch({ type: 'setTime', params: time });
  }, []);
  /** 设置策略描述*/
  const setStrategyDesc = useCallback((strategyDesc: string) => {
    dispatch({ type: 'setStrategyDesc', params: { strategyDesc } });
  }, []);
  /** 设置推送方式*/
  const setMsgStrategy = useCallback((msgStrategy: number) => {
    dispatch({ type: 'setMsgStrategy', params: { msgStrategy } });
  }, []);
  /** 设置半匹配 全匹配*/
  const setTextKeyStrategy = useCallback((textKeyStrategy: number) => {
    dispatch({ type: 'setTextKeyStrategy', params: { textKeyStrategy } });
  }, []);
  /** 设置触发条件*/
  const setEventType = useCallback((eventType: number) => {
    dispatch({ type: 'setEventType', params: { eventType } });
  }, []);
  const setDeflault = useCallback(() => {
    dispatch({ type: 'initData', params: { data: { data: { ...defultData } } } }); // id: state?.id
  }, [state]);
  const setFans = useCallback((fansSelectValue:any) => {
    console.log('setFans====>')
    dispatch({type:'setFansSelectValue',params:{fansSelectValue}})
  }, []);
  const setFansType = useCallback((fansType:any) => {
      console.log('fansType===>',fansType)
    dispatch({type:'setFansType',params:{fansType}})
  }, []);
//   console.log('useInteract=>sate.msgContents====>', state)
  return {
    state,
    addList,
    delList,
    editList,
    up,
    down,
    setTextKey,
    setMenuKeys,
    setTime,
    setStrategyDesc,
    setMsgStrategy,
    setTextKeyStrategy,
    setEventType,
    setFans,
    setFansType,
    addMsg,
    editMsg,
    delMsg,
    getMsg,
    searchMsg,
    searchImMsg,
    initData,
    setEnabled,
    editMsgIm,
    setDeflault,
    searchDetail,
    getMenuList,
    postReplyStrategyPreview,
    upLoad,
  };
}
