package com.fs.company.controller.qw;

import com.alibaba.fastjson.JSON;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanyUserRoleMapper;
import com.fs.company.service.ICompanyUserService;
import com.fs.framework.security.LoginUser;
import com.fs.framework.security.SecurityUtils;
import com.fs.his.domain.FsDoctorPatient;
import com.fs.his.domain.FsPrescribe;
import com.fs.his.dto.AddressInfoDTO;
import com.fs.his.param.CollectionPhoneParam;
import com.fs.his.param.PrescribePhoneParam;
import com.fs.his.service.IFsDoctorPatientService;
import com.fs.his.service.IFsPrescribeService;
import com.fs.hisStore.param.FsCompanyCustomerOrderParam;
import com.fs.hisStore.service.IFsUserInformationCollectionService;
import com.fs.hisStore.vo.FsStoreOrderVO;
import com.fs.hisStore.vo.FsUserInformationCollectionOverviewVo;
import com.fs.qw.domain.FsCompanyCustomer;
import com.fs.qw.service.IFsCompanyCustomerService;
import com.fs.qw.vo.CompanyUserAndDoctorVO;
import com.fs.qw.vo.FsDoctorMemberSalesVO;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;

/**
 * 客户基础信息Controller
 *
 * @author cgp
 * @date 2026-04-30
 */
@Slf4j
@RestController
@RequestMapping("/qw/companyCustomer")
public class FsCompanyCustomerController extends BaseController {

    @Autowired
    private IFsCompanyCustomerService fsCompanyCustomerService;

    @Autowired
    private ICompanyUserService companyUserService;

    @Autowired
    private CompanyUserRoleMapper roleMapper;

    @Autowired
    private IFsPrescribeService fsPrescribeService;

    @Autowired
    private IFsUserInformationCollectionService fsUserInformationCollectionService;

    @Autowired
    private IFsDoctorPatientService fsDoctorPatientService;

    @Autowired
    private IFsUserInformationCollectionService informationCollectionService;

    /**
     * 查询客户列表
     */
    @GetMapping("/list")
    public TableDataInfo list(FsCompanyCustomer fsCompanyCustomer) {
        // 防止 SQL 注入：只允许指定的排序字段和方向
        String sortField = fsCompanyCustomer.getSortField();
        if (sortField != null) {
            if (!"create_time".equals(sortField) && !"filing_time".equals(sortField)) {
                fsCompanyCustomer.setSortField(null);
                fsCompanyCustomer.setSortOrder(null);
            }
        }
        String sortOrder = fsCompanyCustomer.getSortOrder();
        if (sortOrder != null) {
            if (!"asc".equals(sortOrder) && !"desc".equals(sortOrder)) {
                fsCompanyCustomer.setSortOrder(null);
            }
        }
        // 获取当前登录用户id
        Long currentUserId = SecurityUtils.getLoginUser().getUser().getUserId();
        //管理员
        Long isAdmin = roleMapper.companyUserIsAdmin(fsCompanyCustomer.getCompanyUserId());
        PageHelper.startPage(fsCompanyCustomer.getPageNum(), fsCompanyCustomer.getPageSize());
        List<FsCompanyCustomer> list = fsCompanyCustomerService.selectFsCompanyCustomerList(fsCompanyCustomer);
        // 遍历集合，对每个对象的 phone 属性进行脱敏赋值
        list.forEach(customer -> {
            // 如果销售 ID 等于当前用户 ID，就是自己的客户
            customer.setMyCustomerFlag(
                    customer.getCompanyUserId() != null && customer.getCompanyUserId().equals(currentUserId)
            );
            customer.setPhone(maskPhoneMiddleFive(customer.getPhone()));
            if (isAdmin != null) {
            customer.setMyCustomerFlag(true);  // 如果是管理员全部为自己的客户
            }
        });
        return getDataTable(list);
    }

    /**
     * 手机号中间5位脱敏处理 (例如: 13812345678 -> 138******678)
     * @param phone 原始手机号
     * @return 脱敏后的手机号
     */
    public static String maskPhoneMiddleFive(String phone) {
        // 判断是否为空，不为空才进行替换处理
        if (phone == null || phone.isEmpty()) {
            return phone;
        }
        // 使用正则表达式将中间5位数字替换为 *****
        // (\\d{3}) 匹配前3位并作为分组1，\\d{5} 匹配中间5位，(\\d{3}) 匹配后3位并作为分组2
        return phone.replaceAll("(\\d{3})\\d{5}(\\d{3})", "$1*****$2");
    }

    /**
     * 导出客户信息
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, FsCompanyCustomer fsCompanyCustomer) {
        List<FsCompanyCustomer> list = fsCompanyCustomerService.selectFsCompanyCustomerList(fsCompanyCustomer);
        list.forEach(customer -> {
            customer.setPhone(maskPhoneMiddleFive(customer.getPhone()));
        });
        ExcelUtil<FsCompanyCustomer> util = new ExcelUtil<>(FsCompanyCustomer.class);
        try {
            util.exportExcel(response, list, "客户信息数据");
        }catch (Exception e){
            log.error("导出客户信息数据异常",e);
            throw new CustomException("客户信息数据异常");
        }

    }

    /**
     * 获取客户详情
     */
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        FsCompanyCustomer fsCompanyCustomer = fsCompanyCustomerService.selectFsCompanyCustomerById(id);
//        if (fsCompanyCustomer!=null){
//            fsCompanyCustomer.setNoEncryptPhone(fsCompanyCustomer.getPhone());
//            fsCompanyCustomer.setPhone(maskPhoneMiddleFive(fsCompanyCustomer.getPhone()));
//        }
        fsCompanyCustomer.setPhone(maskPhoneMiddleFive(fsCompanyCustomer.getPhone()));
        return AjaxResult.success(fsCompanyCustomer);
    }

    /**
     * 新增客户
     */
    @PostMapping
    public AjaxResult add(@RequestBody FsCompanyCustomer fsCompanyCustomer) {
        // 获取当前登录销售
        CompanyUser companyUser = SecurityUtils.getLoginUser().getUser();
        return AjaxResult.success(fsCompanyCustomerService.insertFsCompanyCustomer(fsCompanyCustomer,companyUser));
    }

    /**
     * 修改客户
     */
    @PutMapping
    public AjaxResult edit(@RequestBody FsCompanyCustomer fsCompanyCustomer) {
        // 获取当前登录用户id
        Long currentUserId = SecurityUtils.getLoginUser().getUser().getUserId();
        fsCompanyCustomer.setCompanyUserId(currentUserId);
        try {
            return toAjax(fsCompanyCustomerService.updateFsCompanyCustomer(fsCompanyCustomer));
        } catch (DuplicateKeyException e) {
            if (e.getMessage().contains("uk_phone")) {
                return AjaxResult.error("电话号码已存在，请更换后再试");
            }
            return AjaxResult.error("数据冲突，请稍后重试");
        }
    }

    /**
     * 认领客户
     */
    @PutMapping("/claimCustomer")
    public AjaxResult claimCustomer(@RequestBody FsCompanyCustomer fsCompanyCustomer) {
        // 获取当前登录销售
        CompanyUser companyUser = SecurityUtils.getLoginUser().getUser();
        try {
            return toAjax(fsCompanyCustomerService.claimCustomer(fsCompanyCustomer,companyUser));
        }catch (CustomException e){
            log.error("认领客户异常: {}", e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 删除客户
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return AjaxResult.success(fsCompanyCustomerService.deleteFsCompanyCustomerByIds(ids));
    }

    /**
     * 获取当前登录销售id信息以及绑定的医生信息
     * */
    @GetMapping("/getCompanyUserAndDoctor")
    public AjaxResult getSaleAndDoctor(){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long companyUserId = loginUser.getUser().getUserId();
        CompanyUserAndDoctorVO companyUserAndDoctorVO = companyUserService.getCompanyUserAndDoctor(companyUserId);
        return AjaxResult.success(companyUserAndDoctorVO);
    }

    /**
     * 根据传入手机号获取处方列表信息
     * */
    @PostMapping("/getPrescribeListByPhone")
    public TableDataInfo getPrescribeListByPhone(@RequestBody PrescribePhoneParam param){
        PageHelper.startPage(param.getPageNum(),param.getPageSize());
        List<FsPrescribe> list = fsPrescribeService.selectPrescribeListByEncryptPhone(param.getPhone());
        return getDataTable(list);
    }

    /**
     * 根据传入客户信息id查询手机号然后获取处方列表信息
     * */
    @PostMapping("/getPrescribeListByIdAndPhone")
    public TableDataInfo getPrescribeListByIdAndPhone(@RequestBody PrescribePhoneParam param){
        FsCompanyCustomer companyCustomer = fsCompanyCustomerService.selectFsCompanyCustomerById(param.getId());
        if (companyCustomer == null){
            return getDataTable(Collections.emptyList());
        }
        PageHelper.startPage(param.getPageNum(),param.getPageSize());
        List<FsPrescribe> list = fsPrescribeService.selectPrescribeListByEncryptPhone(companyCustomer.getPhone());
        return getDataTable(list);
    }

    /**
     * 根据传入手机号获取信息采集列表数据
     * */
    @PostMapping("/getCollectionInfoListByPhone")
    public TableDataInfo getCollectionInfoListByPhone(@RequestBody CollectionPhoneParam param){
        PageHelper.startPage(param.getPageNum(),param.getPageSize());
        List<FsUserInformationCollectionOverviewVo> list = fsUserInformationCollectionService.selectUserInformationCollectionByPhone(param.getPhone());
        return getDataTable(list);
    }

    /**
     * 根据传入手机号获取信息采集列表数据
     * */
    @PostMapping("/getCollectionInfoListByIdAndPhone")
    public TableDataInfo getCollectionInfoListByIdAndPhone(@RequestBody CollectionPhoneParam param){
        FsCompanyCustomer companyCustomer = fsCompanyCustomerService.selectFsCompanyCustomerById(param.getId());
        if (companyCustomer == null){
            return getDataTable(Collections.emptyList());
        }
        PageHelper.startPage(param.getPageNum(),param.getPageSize());
        List<FsUserInformationCollectionOverviewVo> list = fsUserInformationCollectionService.selectUserInformationCollectionByPhone(companyCustomer.getPhone());
        return getDataTable(list);
    }
    /**
     * 销售端-查询医生设置指定可见的患者信息列表
     */
    @ApiOperation("查询医生设置指定可见的患者信息列表")
    @GetMapping("/doctorPatientList")
    public TableDataInfo doctorPatientList(FsDoctorPatient fsDoctorPatient) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long companyUserId = loginUser.getUser().getUserId();
        if (companyUserId == null){
            throw new CustomException("销售登录信息获取异常");
        }
        fsDoctorPatient.setCompanyUserId(companyUserId);
        PageHelper.startPage(fsDoctorPatient.getPageNum(), fsDoctorPatient.getPageSize());
        List<FsDoctorPatient> list = fsDoctorPatientService.selectFsDoctorPatientList(fsDoctorPatient);
        //电话号码脱敏
        for (FsDoctorPatient item : list) {
            if (item.getPhone() != null) {
                item.setPhone(item.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
            }
        }
        return getDataTable(list);
    }

    /**
     * 销售端-查询绑定医生的患者详细信息
     */
    @ApiOperation("查询绑定医生的患者详细信息")
    @GetMapping(value = "/getDoctorPatientInfo/{id}")
    public AjaxResult getDoctorPatientInfo(@PathVariable("id") Long id) {
        FsDoctorPatient fsDoctorPatient = fsDoctorPatientService.selectFsDoctorPatientById(id);
        if (fsDoctorPatient.getPhone() != null) {
            fsDoctorPatient.setPhone(fsDoctorPatient.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
        }
        return AjaxResult.success(fsDoctorPatient);
    }

    /**
     * 查询客户信息表订单列表信息
     * */
    @ApiOperation("查询客户订单列表信息")
    @GetMapping("/getOrderList")
    public TableDataInfo getOrderList(FsCompanyCustomerOrderParam customerOrderParam) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long companyUserId = loginUser.getUser().getUserId();
        if (companyUserId == null){
            throw new CustomException("销售登录信息获取异常");
        }
        PageHelper.startPage(customerOrderParam.getPageNum(), customerOrderParam.getPageSize());
        List<FsStoreOrderVO> list = fsCompanyCustomerService.selectStoreOrderScrmByCompanyCustomerParam(customerOrderParam);
        return getDataTable(list);
    }

    /**
     * 增加客户购买次数
     * */
    @PostMapping("/addBuyTimes")
    public AjaxResult addBuyTimes(@RequestBody FsCompanyCustomer fsCompanyCustomer){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long companyUserId = loginUser.getUser().getUserId();
        if (companyUserId == null){
            throw new CustomException("登录信息已过期，请重新登录");
        }
        int result=fsCompanyCustomerService.addBuyTimes(fsCompanyCustomer.getId());
        return toAjax( result);
    }

    /**
     * 生成客户信息表制单二维码
     * */
    @GetMapping("/getQRCode/{orderId}")
    public R getQRCode(@PathVariable("orderId") Long orderId){
        //TODO appId后续从配置获取
        String appId="wx50bcb040b4963a7e";
        return informationCollectionService.getCustomerGenerateQRCode(orderId,appId);
    }

    @GetMapping(value = "/getAddress")
    public AjaxResult getAddress(@RequestParam("address") String address)
    {
        String kdnAddress = fsCompanyCustomerService.getKdnAddress(address);

        AddressInfoDTO addressInfoDTO = JSON.parseObject(kdnAddress, AddressInfoDTO.class);
        if (!addressInfoDTO.isSuccess()) {
            return AjaxResult.error(addressInfoDTO.getReason());
        }
        AddressInfoDTO.AddressData data = addressInfoDTO.getData();
        logger.info("快递鸟返回{}：",kdnAddress);
        if (data==null){
            return AjaxResult.error("解析地址失败请输入正确地址");
        }
        String provinceName = data.getProvinceName();
        if (!provinceName.contains("省") && !provinceName.contains("区")){
            data.setProvinceName(data.getProvinceName()+"市");
            if (data.getExpAreaName().contains("县")){
                data.setCityName("县");
            }else {
                data.setCityName("市辖区");
            }
        }
        return AjaxResult.success(addressInfoDTO);
    }
}