package com.wzj.soopin.member.controller;


import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzj.soopin.member.convert.MemberConvert;
import com.wzj.soopin.member.domain.bo.MemberBO;
import com.wzj.soopin.member.domain.po.Member;
import com.wzj.soopin.member.domain.vo.MemberDataStatisticsVO;
import com.wzj.soopin.member.domain.vo.MemberVO;
import com.wzj.soopin.member.service.IMemberService;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.dromara.common.core.domain.R;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;

/**
 * 会员信息Controller
 *
 * @author zcc
 * @date 2022-11-28
 */
@Tag(name = "会员信息接口列表")
@RequestMapping("/ums/member/")
@RestController
@Slf4j
public class MemberController extends BaseController {
    @Autowired
    private IMemberService service;
    @Autowired
    private MemberConvert convert;


    @Tag(name = "查询会员信息列表")
    @SaCheckPermission("ums:member:list")
    @PostMapping("list")
    public R<Page<MemberVO>> list(@RequestBody MemberBO bo,@RequestBody  Page<Member> page) {
        Page<Member> memberPage = service.page(page,bo.toWapper());
        TableDataInfo.build(memberPage);
        return R.ok(convert.toVO(memberPage));
    }

   @Tag(name ="导出会员信息列表")
    @Log(title = "会员信息", businessType = BusinessType.EXPORT)
    @PostMapping("export")
    public R<String> export(MemberBO query) {
        List<Member> list = service.list(query.toWapper());
        ExcelUtil<MemberVO> util = new ExcelUtil<>(MemberVO.class);
        return R.ok(util.writeExcel(convert.toVO(list), "会员信息数据"));
    }

   @Tag(name ="获取会员信息详细信息")
    @GetMapping(value = "{id}")
    public R<MemberVO> getInfo(@PathVariable("id") Long id) {
        return R.ok(service.getMemberInfo(id));
    }

   @Tag(name ="新增会员信息")
    @SaCheckPermission("'ums:member:add")
    @Log(title = "会员信息", businessType = BusinessType.INSERT)
    @PostMapping("add")
    public R add(@RequestBody MemberBO member) {
        return R.ok(service.save(convert.toPo(member)));
    }

   @Tag(name ="修改会员信息")
    @SaCheckPermission("ums:member:edit")
    @Log(title = "会员信息", businessType = BusinessType.UPDATE)
    @PostMapping("update")
    public Object edit(@RequestBody(required = false) Map<String, Object> callbackData,
                      @RequestParam(required = false) Long id,
                      @RequestParam(required = false) String nickname,
                      @RequestParam(required = false) Integer gender) {
        // 1. IM回调格式 - 用户资料更新回调
        if (callbackData != null && callbackData.containsKey("CallbackCommand")) {
            log.info("收到IM用户资料更新回调: {}", callbackData);
            String callbackCommand = (String) callbackData.get("CallbackCommand");
            if ("Profile.CallbackPortraitSet".equals(callbackCommand)) {
                String fromAccount = (String) callbackData.get("From_Account");
                List<Map<String, Object>> profileItems = (List<Map<String, Object>>) callbackData.get("ProfileItem");
                if (fromAccount != null && profileItems != null) {
                    Long userId = Long.valueOf(fromAccount.replace("UserID_", ""));
                    // 根据 ProfileItem 更新用户资料
                    Member memberToUpdate = service.getById(userId);
                    if (memberToUpdate != null) {
                        for (Map<String, Object> item : profileItems) {
                            String tag = (String) item.get("Tag");
                            Object value = item.get("Value");
                            updateMemberProfile(memberToUpdate, tag, value);
                        }
                        service.updateById(memberToUpdate);
                        log.info("IM用户资料更新回调处理成功: userId={}, profileItems={}", userId, profileItems);
                    } else {
                        log.warn("IM用户资料更新回调中用户不存在: userId={}", userId);
                    }
                } else {
                    log.warn("IM用户资料更新回调参数不完整: {}", callbackData);
                }
                // 返回IM平台要求的应答
                Map<String, Object> resp = new HashMap<>();
                resp.put("ActionStatus", "OK");
                resp.put("ErrorCode", 0);
                resp.put("ErrorInfo", "");
                return resp;
            }
        }
        // 2. 兼容JSON方式传递参数
        if (callbackData != null && callbackData.containsKey("id")) {
            log.info("收到JSON会员更新回调: {}", callbackData);
            Object idObj = callbackData.get("id");
            Object nicknameObj = callbackData.get("nickname");
            Object genderObj = callbackData.get("gender");
            if (idObj != null) {
                Long memberId = Long.valueOf(idObj.toString());
                Member memberToUpdate = service.getById(memberId);
                if (memberToUpdate != null) {
                    if (nicknameObj != null) {
                        memberToUpdate.setNickname(nicknameObj.toString());
                    }
                    if (genderObj != null) {
                        memberToUpdate.setGender(Integer.valueOf(genderObj.toString()));
                    }
                    service.updateById(memberToUpdate);
                    log.info("JSON会员更新回调处理成功: id={}, nickname={}, gender={}", memberId, nicknameObj, genderObj);
                    return R.ok("更新成功");
                } else {
                    log.warn("JSON会员更新回调中用户不存在: id={}", memberId);
                }
            }
        }
        // 3. 普通参数更新
        if (id != null) {
            log.info("收到参数会员更新回调: id={}, nickname={}, gender={}", id, nickname, gender);
            Member memberToUpdate = service.getById(id);
            if (memberToUpdate != null) {
                if (nickname != null) {
                    memberToUpdate.setNickname(nickname);
                }
                if (gender != null) {
                    memberToUpdate.setGender(gender);
                }
                service.updateById(memberToUpdate);
                log.info("参数会员更新回调处理成功: id={}, nickname={}, gender={}", id, nickname, gender);
                return R.ok("更新成功");
            } else {
                log.warn("参数会员更新回调中用户不存在: id={}", id);
            }
        }
        log.error("会员信息更新失败，参数为空: callbackData={}, id={}, nickname={}, gender={}", callbackData, id, nickname, gender);
        return R.fail("参数不能为空");
    }

    /**
     * 根据IM回调的ProfileItem更新用户资料
     */
    private void updateMemberProfile(Member member, String tag, Object value) {
        if (tag == null || value == null) {
            return;
        }
        switch (tag) {
            case "Tag_Profile_IM_Nick":
                member.setNickname(value.toString());
                break;
            case "Tag_Profile_IM_Gender":
                // 根据性别值设置性别字段
                if ("Gender_Type_Male".equals(value)) {
                    member.setGender(1); // 男
                } else if ("Gender_Type_Female".equals(value)) {
                    member.setGender(2); // 女
                } else {
                    member.setGender(0); // 未知
                }
                break;
            case "Tag_Profile_IM_AllowType":
                // 处理好友验证方式
                break;
            case "Tag_Profile_Custom_Data":
                // 处理自定义数据
                break;
            default:
                log.debug("未处理的用户资料字段: tag={}, value={}", tag, value);
                break;
        }
    }

   @Tag(name ="修改会员备注信息")
    @SaCheckPermission("ums:member:edit")
    @Log(title = "会员备注信息", businessType = BusinessType.UPDATE)
    @PostMapping("mark/update")
    public R<Integer> editMark(@RequestBody MemberBO member) {
        return R.ok(service.updateMark(member));
    }

   @Tag(name ="删除会员信息")
    @SaCheckPermission("ums:member:remove")
    @Log(title = "会员信息", businessType = BusinessType.DELETE)
	@DeleteMapping("{id}")
    public R  remove(@PathVariable Long id) {
        return R.ok(service.removeById(id));
    }

   @Tag(name =("修改会员账户状态"))
    @Log(title = "会员信息", businessType = BusinessType.UPDATE)
    @PostMapping("status/change")
    public R<Integer> changeStatus(@RequestBody MemberBO memberBO){
        return R.ok(service.changeStatus(memberBO));
    }

   @Tag(name ="会员手机号解密")
    @GetMapping("phone/decrypt/{phoneEncrypted}")
    public R<String> getPhoneDecrypted(@PathVariable String phoneEncrypted){
        return R.ok(service.getPhoneDecrypted(phoneEncrypted));
    }

   @Tag(name ="查看会员统计数据")
    @GetMapping("view/statistics/{memberId}")
    public R<MemberDataStatisticsVO> viewStatistics(@PathVariable Long memberId){
//        return ResponseEntity.ok(service.viewStatistics(memberId));
        return null;
    }


    @Tag(name ="获取登录会员的信息")
    @GetMapping(value = "/login/info")
    public R<MemberVO> getLoinInfo() {
        return R.ok(service.getLoginMemberInfo());
    }


    @Tag(name ="同步会员的信息")
    @GetMapping(value = "/sync")
    public R<MemberVO> syncInfo() {
        service.syncInfo();
        return R.ok();
    }

}
