package com.fs.app.controller;

import com.fs.app.annotation.Login;
import com.fs.common.BeanCopyUtils;
import com.fs.common.annotation.Log;
import com.fs.common.config.LoginContextManager;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.doctor.domain.Doctor;
import com.fs.doctor.domain.DoctorCompanyUser;
import com.fs.doctor.domain.DoctorLevel;
import com.fs.doctor.domain.DoctorLevelApply;
import com.fs.doctor.mapper.DoctorCompanyUserMapper;
import com.fs.doctor.mapper.DoctorLevelApplyMapper;
import com.fs.doctor.service.IDoctorLevelApplyService;
import com.fs.doctor.service.IDoctorLevelService;
import com.fs.doctor.service.IDoctorService;
import com.fs.doctor.vo.*;
import com.fs.wx.ma.service.WxMaQrcodeServiceImpl;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 讲者Controller
 *
 * @author fs
 * @date 2025-12-30
 */
@RestController
@RequestMapping("/doctor/doctor")
public class DoctorController extends BaseController
{
    @Autowired
    private IDoctorService doctorService;

    @Autowired
    private DoctorCompanyUserMapper doctorCompanyUserMapper;

    @Autowired
    private WxMaQrcodeServiceImpl wxMaQrcodeService;

    @Value("${fs.miniapp.page:pages/auth/login}")
    private String miniappPage;

    @Value("${wx.miniapp.configs[0].appid:}")
    private String miniappAppid;

    @Autowired
    private IDoctorLevelService doctorLevelService;

    @Autowired
    private DoctorLevelApplyMapper doctorLevelApplyMapper;

    /**
     * 查询讲者列表
     */
    @Login
    @GetMapping("/list")
    public TableDataInfo list(Doctor doctor)
    {
        logger.info("查询讲者列表 参数列表: {}",doctor);
        // 获取当前登录的业务员ID
        Long currentCompanyUserId = LoginContextManager.getCurrentCompanyUserId();

        logger.info("获取当前登录的业务员ID: {}",currentCompanyUserId);
        // 设置业务员ID，用于过滤只显示与该业务员关联的医生
        doctor.setCompanyUserId(currentCompanyUserId);

        startPage();
        List<Doctor> list = doctorService.selectDoctorList(doctor);

        List<DoctorVO> doctorVOS = BeanCopyUtils.copyList(list, DoctorVO.class);
        for (DoctorVO doctorVO : doctorVOS) {
            List<DoctorCompanyUser> doctorCompanyUsers = doctorCompanyUserMapper.queryProductGroup(doctorVO.getCompanyId(), doctorVO.getDoctorId());
            Map<String,DoctorProductVO> doctorProductMap = new HashMap<>();

            for (DoctorCompanyUser dc : doctorCompanyUsers) {
                String companyUserName = String.format("%s_%s", dc.getCompanyUserId(), dc.getCompanyUserName());
                DoctorProductVO doctorProductVO = doctorProductMap.get(companyUserName);
                if(doctorProductVO == null) {
                    doctorProductVO = new DoctorProductVO();
                    doctorProductVO.setCompanyUserName(companyUserName);
                    doctorProductMap.put(companyUserName, doctorProductVO);
                }
//                if(StringUtils.isEmpty(doctorProductVO.getProductCode())){
//                    doctorProductVO.setProductCode(String.join("、",dc.getProduct().split(",")));
//                } else {
//                    doctorProductVO.setProductCode(doctorProductVO.getProductCode()+"、"+dc.getProduct());
//                }
            }

//            doctorVO.setDoctorProducts(new ArrayList<>(doctorProductMap.values()));

            // 医生级别
            DoctorLevel doctorLevel = doctorLevelService.selectDoctorLevelByDoctorId(doctorVO.getDoctorId());
            if(doctorLevel != null) {
                doctorVO.setDoctorLevel(doctorLevel.getLevel());
            }

            List<DoctorLevelApply> doctorLevelApply = doctorLevelApplyMapper.selectByDoctorId(doctorVO.getDoctorId());
            if (doctorLevelApply == null || doctorLevelApply.isEmpty()
                    || doctorLevelApply.stream().allMatch(apply -> ObjectUtils.equals(apply.getStatus(), 2L))) {
                doctorVO.setIsApply(0);
            } else {
                doctorVO.setIsApply(1);
            }

        }

        return getDataTable(doctorVOS);
    }






    /**
     * 查询已经定级申请的讲者列表
     */
    @Login
    @GetMapping("/appliedList")
    public TableDataInfo appliedList(Doctor doctor)
    {
        // 获取当前登录的业务员ID
        Long currentCompanyUserId = LoginContextManager.getCurrentCompanyUserId();

        // 设置业务员ID，用于过滤只显示与该业务员关联的医生
        doctor.setCompanyUserId(currentCompanyUserId);

        startPage();
        List<Doctor> list = doctorService.selectDoctorList(doctor);
        List<DoctorVO> doctorVOS = BeanCopyUtils.copyList(list, DoctorVO.class);
        List<DoctorVO> filteredList = new ArrayList<>();

        for (DoctorVO doctorVO : doctorVOS) {
            // 处理产品组信息
            List<DoctorCompanyUser> doctorCompanyUsers = doctorCompanyUserMapper.queryProductGroup(doctorVO.getCompanyId(), doctorVO.getDoctorId());
            Map<String, DoctorProductVO> doctorProductMap = new HashMap<>();

            for (DoctorCompanyUser dc : doctorCompanyUsers) {
                String companyUserName = String.format("%s_%s", dc.getCompanyUserId(), dc.getCompanyUserName());
                DoctorProductVO doctorProductVO = doctorProductMap.get(companyUserName);
                if (doctorProductVO == null) {
                    doctorProductVO = new DoctorProductVO();
                    doctorProductVO.setCompanyUserName(companyUserName);
                    doctorProductMap.put(companyUserName, doctorProductVO);
                }
//                if (StringUtils.isEmpty(doctorProductVO.getProductCode())) {
//                        doctorProductVO.setProductCode(String.join("、", dc.getProduct().split(",")));
//                } else {
//                    doctorProductVO.setProductCode(doctorProductVO.getProductCode() + "、" + dc.getProduct());
//                }
            }
            doctorVO.setDoctorProducts(new ArrayList<>(doctorProductMap.values()));

            // 医生级别
            DoctorLevel doctorLevel = doctorLevelService.selectDoctorLevelByDoctorId(doctorVO.getDoctorId());
            if (doctorLevel != null) {
                doctorVO.setDoctorLevel(doctorLevel.getLevel());
                filteredList.add(doctorVO);
            }


        }

        return getDataTable(filteredList);
    }


    /**
     * 导出讲者列表
     */
    @GetMapping("/export")
    public AjaxResult export(Doctor doctor)
    {
        doctor.setCompanyId(LoginContextManager.getCurrentCompanyUserId());

        List<Doctor> list = doctorService.selectDoctorList(doctor);
        ExcelUtil<Doctor> util = new ExcelUtil<Doctor>(Doctor.class);
        return util.exportExcel(list, "讲者数据");
    }

    /**
     * 获取讲者详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        Doctor doctor = doctorService.selectDoctorById(id);
        List<DoctorLevelApply> doctorLevelApply = doctorLevelApplyMapper.selectByDoctorId(doctor.getDoctorId());
        if (doctorLevelApply == null || doctorLevelApply.isEmpty()
                || doctorLevelApply.stream().allMatch(apply -> ObjectUtils.equals(apply.getStatus(), 2L))) {
            doctor.setIsApply(0);
        } else {
            doctor.setIsApply(1);
        }

        return AjaxResult.success(doctor);
    }

    /**
     * 新增讲者
     */
    @PostMapping
    public AjaxResult add(@RequestBody DoctorVO doctorVO)
    {
       return toAjax( doctorService.add(doctorVO));
    }

    /**
     * 修改讲者
     */
    @PutMapping
    public AjaxResult edit(@RequestBody Doctor doctor)
    {
        return toAjax(doctorService.updateDoctor(doctor));
    }

    /**
     * 删除讲者
     */
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(doctorService.deleteDoctorByIds(ids));
    }


    @PreAuthorize("@ss.hasPermi('doctor:doctor:list')")
    @GetMapping("/getDoctorOptionVOList")
    public AjaxResult getDoctorOptionVOList(DoctorOptionReqVO doctorOptionReqVO)
    {
        List<DoctorOptionRespVO> list = doctorService.getDoctorOptionVOList(doctorOptionReqVO);
        return AjaxResult.success(list);
    }


    /**
     * 查询讲者审核页面信息
     */
    @GetMapping("/audit/{id}")
    public AjaxResult getAuditInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(doctorService.selectDoctorAuditInfo(id));
    }


    @PostMapping("doAudit")
    public void doAudit(@RequestBody DoctorDoAuditReqVO doctorDoAuditReqVO){
        doctorService.doAudit(doctorDoAuditReqVO);
    }



    /**
     * 修改讲者密码
     */
    @PostMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody DoctorResetPwdReqVO req) {
        return toAjax(doctorService.resetPwd(req));
    }

    /**
     * 邀请讲者 - 生成小程序二维码
     *
     * @param companyUserId 销售ID
     * @param companyId 公司ID
     * @return 小程序码图片
     */
    /**
     * 邀请讲者 - 生成小程序二维码（返回Base64图片数据，前端直接用于img.src）
     */
    @GetMapping("/invite_doctor")
    public ResponseEntity<String> inviteDoctor(
            @RequestParam("companyUserId") Long companyUserId,
            @RequestParam(value = "companyId", required = false) Long companyId) {
        try {
            // 构建 scene 参数（注意长度不超过32字符）
            String scene = "cuid=" + companyUserId;
            if (companyId != null) {
                scene += ",cid=" + companyId;
            }

            // 调用微信API生成小程序码（无限制）
            byte[] qrcodeImage = wxMaQrcodeService.createWxaCodeUnlimit(scene, miniappPage, 430, miniappAppid);

            // 转换为 Base64 并构建 data URL
            String base64 = Base64.getEncoder().encodeToString(qrcodeImage);
            String dataUrl = "data:image/png;base64," + base64;

            // 设置响应头（纯文本）
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.TEXT_PLAIN);
            headers.setContentLength(dataUrl.getBytes(StandardCharsets.UTF_8).length);
            headers.set("Content-Disposition", "inline; filename=invite_miniapp_qrcode.txt");
            headers.setCacheControl("no-cache");

            return new ResponseEntity<>(dataUrl, headers, HttpStatus.OK);
        } catch (WxErrorException e) {
            logger.error("生成小程序码失败: errCode={}, errMsg={}", e.getError().getErrorCode(), e.getError().getErrorMsg(), e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            logger.error("生成小程序码失败", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


}
