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);

        Object personalData = fnaForm.getPersonalData();
        if (personalData != null) {
            fnaFormVO.setPersonalData(GSON.fromJson(personalData.toString(), PersonalData.class));
        }
        Object taxList = fnaForm.getTaxList();
        if (taxList != null) {
            fnaFormVO.setTaxList(GSON.fromJson(taxList.toString(), new TypeToken<List<TaxCountry>>() {
            }.getType()));
        }
        Object familyMembers = fnaForm.getFamilyMembers();
        if (familyMembers != null) {
            fnaFormVO.setFamilyMembers(GSON.fromJson(familyMembers.toString(), new TypeToken<List<FamilyMember>>() {
            }.getType()));
        }
        Object existingSecurityOwner = fnaForm.getExistingSecurityOwner();
        if (existingSecurityOwner != null) {
            fnaFormVO.setExistingSecurityOwner(GSON.fromJson(existingSecurityOwner.toString(), new TypeToken<List<ExistingSecurity>>() {
            }.getType()));
        }
        Object existingSecurityInsured = fnaForm.getExistingSecurityInsured();
        if (existingSecurityInsured != null) {
            fnaFormVO.setExistingSecurityInsured(GSON.fromJson(existingSecurityInsured.toString(), new TypeToken<List<ExistingSecurity>>() {
            }.getType()));
        }
        Object incomeExpense = fnaForm.getIncomeExpense();
        if (incomeExpense != null) {
            fnaFormVO.setIncomeExpense(GSON.fromJson(incomeExpense.toString(), IncomeExpense.class));
        }
        Object liquidAssets = fnaForm.getLiquidAssets();
        if (liquidAssets != null) {
            fnaFormVO.setLiquidAssets(GSON.fromJson(liquidAssets.toString(), LiquidAssets.class));
        }
        Object primaryResidence = fnaForm.getPrimaryResidence();
        if (primaryResidence != null) {
            fnaFormVO.setPrimaryResidence(GSON.fromJson(primaryResidence.toString(), new TypeToken<List<OwnerProperties>>() {
            }.getType()));
        }
        Object investment = fnaForm.getInvestment();
        if (investment != null) {
            fnaFormVO.setInvestment(GSON.fromJson(investment.toString(), new TypeToken<List<InvestmentProperties>>() {
            }.getType()));
        }
        Object monthlyIncome = fnaForm.getCompanyBusinessData();
        if (monthlyIncome != null) {
            fnaFormVO.setCompanyBusinessData(GSON.fromJson(monthlyIncome.toString(), CompanyBusinessData.class));
        }
        Object other = fnaForm.getOther();
        if (other != null) {
            fnaFormVO.setOther(GSON.fromJson(other.toString(), FnaFormOther.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.setPersonalData(GSON.toJson(fnaFormAddRequest.getPersonalData()));
        fnaForm.setTaxList(GSON.toJson(fnaFormAddRequest.getTaxList()));
        fnaForm.setFamilyMembers(GSON.toJson(fnaFormAddRequest.getFamilyMembers()));
        fnaForm.setExistingSecurityOwner(GSON.toJson(fnaFormAddRequest.getExistingSecurityOwner()));
        fnaForm.setExistingSecurityInsured(GSON.toJson(fnaFormAddRequest.getExistingSecurityInsured()));
        fnaForm.setIncomeExpense(GSON.toJson(fnaFormAddRequest.getIncomeExpense()));
        fnaForm.setLiquidAssets(GSON.toJson(fnaFormAddRequest.getLiquidAssets()));
        fnaForm.setPrimaryResidence(GSON.toJson(fnaFormAddRequest.getPrimaryResidence()));
        fnaForm.setInvestment(GSON.toJson(fnaFormAddRequest.getInvestment()));
        fnaForm.setCompanyBusinessData(GSON.toJson(fnaFormAddRequest.getCompanyBusinessData()));
        fnaForm.setOther(GSON.toJson(fnaFormAddRequest.getOther()));

        return fnaForm;
    }

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

        fnaForm.setPersonalData(GSON.toJson(fnaFormUpdateRequest.getPersonalData()));
        fnaForm.setTaxList(GSON.toJson(fnaFormUpdateRequest.getTaxList()));
        fnaForm.setFamilyMembers(GSON.toJson(fnaFormUpdateRequest.getFamilyMembers()));
        fnaForm.setExistingSecurityOwner(GSON.toJson(fnaFormUpdateRequest.getExistingSecurityOwner()));
        fnaForm.setExistingSecurityInsured(GSON.toJson(fnaFormUpdateRequest.getExistingSecurityInsured()));
        fnaForm.setIncomeExpense(GSON.toJson(fnaFormUpdateRequest.getIncomeExpense()));
        fnaForm.setLiquidAssets(GSON.toJson(fnaFormUpdateRequest.getLiquidAssets()));
        fnaForm.setPrimaryResidence(GSON.toJson(fnaFormUpdateRequest.getPrimaryResidence()));
        fnaForm.setInvestment(GSON.toJson(fnaFormUpdateRequest.getInvestment()));
        fnaForm.setCompanyBusinessData(GSON.toJson(fnaFormUpdateRequest.getCompanyBusinessData()));
        fnaForm.setOther(GSON.toJson(fnaFormUpdateRequest.getOther()));

        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);
    }

}
