package com.yd.csf.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yd.common.enums.ResultCode;
import com.yd.common.exception.BusinessException;
import com.yd.csf.service.dao.FnaFormMapper;
import com.yd.csf.service.dto.*;
import com.yd.csf.service.model.FnaForm;
import com.yd.csf.service.service.FnaFormService;
import com.yd.csf.service.utils.ValidateUtil;
import com.yd.csf.service.vo.FnaFormVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Fna表单服务实现
 *
 */
@Service
@Slf4j
public class FnaFormServiceImpl extends ServiceImpl<FnaFormMapper, FnaForm> implements FnaFormService {

//    @Resource
//    private UserService userService;

    private final static Gson GSON = new Gson();

    /**
     * 校验数据
     *
     * @param fnaForm
     * @param saveType 保存类型
     */
    @Override
    public void validFnaForm(FnaForm fnaForm, String saveType) {

    }

    /**
     * 获取查询条件
     *
     * @param fnaFormQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<FnaForm> getQueryWrapper(FnaFormQueryRequest fnaFormQueryRequest) {
        QueryWrapper<FnaForm> queryWrapper = new QueryWrapper<>();
        if (fnaFormQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Long id = fnaFormQueryRequest.getId();
        Long notId = fnaFormQueryRequest.getNotId();
        String title = fnaFormQueryRequest.getTitle();
        String content = fnaFormQueryRequest.getContent();
        String searchText = fnaFormQueryRequest.getSearchText();

        List<String> tagList = fnaFormQueryRequest.getTags();
        Long userId = fnaFormQueryRequest.getUserId();
        // todo 补充需要的查询条件
        // 从多字段中搜索
        if (StringUtils.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("title", searchText).or().like("content", searchText));
        }
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tagList)) {
            for (String tag : tagList) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(notId), "id", notId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        // 排序规则
//        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
//                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
//                sortField);
        return queryWrapper;
    }

    /**
     * 获取Fna表单封装
     *
     * @param fnaForm
     * @return
     */
    @Override
    public FnaFormVO getFnaFormVO(FnaForm fnaForm) {
        // 对象转封装类
        FnaFormVO fnaFormVO = FnaFormVO.objToVo(fnaForm);

        if (fnaForm.getBrokerList() != null) {
            fnaFormVO.setBrokerList(GSON.fromJson(fnaForm.getBrokerList().toString(), new TypeToken<List<BrokerData>>() {
            }.getType()));
        }
        if (fnaForm.getDependantList() != null) {
            fnaFormVO.setDependantList(GSON.fromJson(fnaForm.getDependantList().toString(), new TypeToken<List<DependantData>>() {
            }.getType()));
        }

        Object existingSecurityOwner = fnaForm.getExistingSecurityOwner();
        if (existingSecurityOwner != null) {
            fnaFormVO.setExistingSecurityOwner(GSON.fromJson(existingSecurityOwner.toString(), new TypeToken<List<ExistingSecurity>>() {
            }.getType()));
        }

        Object primaryResidence = fnaForm.getPrimaryResidence();
        if (primaryResidence != null) {
            fnaFormVO.setPrimaryResidence(GSON.fromJson(primaryResidence.toString(), new TypeToken<List<OwnerProperties>>() {
            }.getType()));
        }

        if (fnaForm.getPremiumAffordability() != null) {
            fnaFormVO.setPremiumAffordability(GSON.fromJson(fnaForm.getPremiumAffordability().toString(), PremiumAffordability.class));
        }

        if (fnaForm.getCompanyBusinessData() != null) {
            fnaFormVO.setCompanyBusinessData(GSON.fromJson(fnaForm.getCompanyBusinessData().toString(), CompanyBusinessData.class));
        }

        return fnaFormVO;
    }

    /**
     * 分页获取Fna表单封装
     *
     * @param fnaFormPage
     * @return
     */
    @Override
    public Page<FnaFormVO> getFnaFormVOPage(Page<FnaForm> fnaFormPage) {
        List<FnaForm> fnaFormList = fnaFormPage.getRecords();
        Page<FnaFormVO> fnaFormVOPage = new Page<>(fnaFormPage.getCurrent(), fnaFormPage.getSize(), fnaFormPage.getTotal());
        if (CollUtil.isEmpty(fnaFormList)) {
            return fnaFormVOPage;
        }
        // 对象列表 => 封装对象列表
        List<FnaFormVO> fnaFormVOList = fnaFormList.stream().map(fnaForm -> {
            return FnaFormVO.objToVo(fnaForm);
        }).collect(Collectors.toList());



        fnaFormVOPage.setRecords(fnaFormVOList);
        return fnaFormVOPage;
    }

    @Override
    public void validFnaFormAdd(PersonalData personalData, String saveType) {
        if (personalData == null || ValidateUtil.isAllFieldsNull(personalData)) {
            throw new BusinessException(ResultCode.PARAM_CHECK_ERROR.getCode(), "个人资料不能全不为空");
        }
        if ("save".equals(saveType)) {
//            if (StringUtils.isBlank(personalData.getAccountName())) {
//                throw new BusinessException(ResultCode.PARAM_CHECK_ERROR.getCode(), "陪同顾问姓名不能为空");
//            }
//            if (StringUtils.isBlank(personalData.getRegistrationNumber())) {
//                throw new BusinessException(ResultCode.PARAM_CHECK_ERROR.getCode(), "理财顾问注册编号不能为空");
//            }
            if (StringUtils.isBlank(personalData.getCustomerName())) {
                throw new BusinessException(ResultCode.PARAM_CHECK_ERROR.getCode(), "客户姓名不能为空");
            }
//            if (StringUtils.isBlank(personalData.getTaxCountry())) {
//                throw new BusinessException(ResultCode.PARAM_CHECK_ERROR.getCode(), "税务国家不能为空");
//            }
            if (StringUtils.isBlank(personalData.getEmployment())) {
                throw new BusinessException(ResultCode.PARAM_CHECK_ERROR.getCode(), "就业情况不能为空");
            }
        }
    }

    @Override
    public FnaForm getFnaForm(FnaFormAddRequest fnaFormAddRequest) {
        FnaForm fnaForm = new FnaForm();

        fnaForm.setCustomerBizId(fnaFormAddRequest.getCustomerBizId());
        fnaForm.setBrokerList(GSON.toJson(fnaFormAddRequest.getBrokerList()));
        fnaForm.setDependantList(GSON.toJson(fnaFormAddRequest.getDependantList()));
        fnaForm.setExistingSecurityOwner(GSON.toJson(fnaFormAddRequest.getExistingSecurityOwner()));
        fnaForm.setPrimaryResidence(GSON.toJson(fnaFormAddRequest.getPrimaryResidence()));
        fnaForm.setPremiumAffordability(GSON.toJson(fnaFormAddRequest.getPremiumAffordability()));
        fnaForm.setCompanyBusinessData(GSON.toJson(fnaFormAddRequest.getCompanyBusinessData()));

        return fnaForm;
    }

    @Override
    public FnaForm getFnaForm(FnaFormUpdateRequest fnaFormUpdateRequest) {
        FnaForm fnaForm = new FnaForm();
        BeanUtils.copyProperties(fnaFormUpdateRequest, fnaForm);

        fnaForm.setBrokerList(GSON.toJson(fnaFormUpdateRequest.getBrokerList()));
        fnaForm.setDependantList(GSON.toJson(fnaFormUpdateRequest.getDependantList()));
        fnaForm.setExistingSecurityOwner(GSON.toJson(fnaFormUpdateRequest.getExistingSecurityOwner()));
        fnaForm.setPrimaryResidence(GSON.toJson(fnaFormUpdateRequest.getPrimaryResidence()));
        fnaForm.setPremiumAffordability(GSON.toJson(fnaFormUpdateRequest.getPremiumAffordability()));
        fnaForm.setCompanyBusinessData(GSON.toJson(fnaFormUpdateRequest.getCompanyBusinessData()));

        return fnaForm;
    }

    @Override
    public FnaForm getByFnaFormBizId(String fnaFormBizId) {
        QueryWrapper<FnaForm> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fna_form_biz_id", fnaFormBizId);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public PersonalData getPersonalDataObj(Object personalData) {
        if (personalData == null) {
            return new PersonalData();
        }
        return GSON.fromJson(personalData.toString(), PersonalData.class);
    }

}
