package com.tofly.feesapi.wxgl.wechatofficalacctmgt.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.tofly.feesapi.bjgl.entity.YhCbkxx;
import com.tofly.feesapi.bjgl.service.YhCbkxxService;
import com.tofly.feesapi.common.enums.WxEnum;
import com.tofly.feesapi.common.exception.FeesErrorCode;
import com.tofly.feesapi.common.exception.FeesException;
import com.tofly.feesapi.wxgl.wechatofficalacctmgt.entity.WxDbsq;
import com.tofly.feesapi.wxgl.wechatofficalacctmgt.entity.dto.WxCommonDto;
import com.tofly.feesapi.wxgl.wechatofficalacctmgt.entity.vo.WxDbsqVo;
import com.tofly.feesapi.wxgl.wechatofficalacctmgt.service.WxDbsqService;
import com.tofly.feesapi.yhgl.entity.YhKhjbxx;
import com.tofly.feesapi.yhgl.mapper.YhKhjbxxMapper;
import com.tofly.feesapi.yhgl.service.YhKhjbxxService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tofly.feesapi.wxgl.wechatofficalacctmgt.mapper.WxDbsqMapper;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class WxDbsqServiceImpl extends ServiceImpl<WxDbsqMapper, WxDbsq> implements WxDbsqService {

    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private YhKhjbxxService yhKhjbxxService;
    @Autowired
    private YhCbkxxService yhCbkxxService;
    @Autowired
    private YhKhjbxxMapper yhKhjbxxMapper;

    @Override
    public Page<WxDbsqVo> getWxDbsqPage(Page page, WxCommonDto dto) {
        WxDbsq wxDbsq = JSONObject.parseObject(JSON.toJSONString(dto), WxDbsq.class);
        QueryWrapper<WxDbsq> queryWrapper = new QueryWrapper<>();
        Date starttime = dto.getStarttime();
        Date endtime = dto.getEndtime();

        String searchText = dto.getSearchText();

        //关键字查询
        if (null != searchText) {
            queryWrapper.or().like("register_yhbh", searchText);
            queryWrapper.or().like("register_name", searchText);
            queryWrapper.or().like("register_address", searchText);
            queryWrapper.or().like("register_phone", searchText);
            dto.setSearchText(null);
        }
        //添加时间条件
        if (null != starttime && null != endtime) {
            queryWrapper.ge("register_date", starttime).lt("register_date", endtime);
            dto.setStarttime(null);
            dto.setEndtime(null);
        } else if (null != starttime) {
            queryWrapper.ge("register_date", starttime);
            dto.setStarttime(null);
        } else if (null != endtime) {
            queryWrapper.le("register_date", endtime);
            dto.setEndtime(null);
        }

        queryWrapper.setEntity(wxDbsq);
        queryWrapper.orderByDesc("register_date");

        Page infoPageList = this.page(page, queryWrapper);
        infoPageList.setRecords(this.viewConversion(infoPageList.getRecords()));
        return infoPageList;
    }

    /**
     * 更新微信低保申请（审核通过更新用户类别）
     */
    @Override
    public boolean updateWxDbsq(WxDbsq update) {
        String id = update.getId();
        if (StringUtils.isEmpty(id)) throw new FeesException("id不能为空", FeesErrorCode.BUSINESS_ERROR);
        WxDbsq wxDbsq = this.getById(id);
        if (wxDbsq == null)
            throw new FeesException(String.format("id(%s)不存在", id), FeesErrorCode.BUSINESS_ERROR);
        BeanUtils.copyProperties(update, wxDbsq);

        transactionTemplate.execute((status) -> {
            try {
                this.updateById(wxDbsq);
                if(wxDbsq.getState().equals("2")){
                    //更新用户档案信息
                    yhKhjbxxService.lambdaUpdate().set(YhKhjbxx::getKhlb,"2")//1正常 2低保
                            .eq(YhKhjbxx::getYhbh,wxDbsq.getRegisterYhbh())
                            .update();
                    //更新抄表卡信息
                    yhCbkxxService.lambdaUpdate()
                            .set(YhCbkxx::getLjfbz,"0")
                            .eq(YhCbkxx::getYhbh,wxDbsq.getRegisterYhbh())
                            .update();
                }
            } catch (Exception e) {
                status.setRollbackOnly();
                throw e;
            }
            return 1;
        });
        return true;
    }

    /**
     * 转换视图
     */
    public List<WxDbsqVo> viewConversion(List<WxDbsq> infoList) {
        if (CollectionUtils.isEmpty(infoList)) {
            return Collections.emptyList();
        }

        List<WxDbsqVo> infoVoList = new ArrayList<>();
        infoList.forEach(info -> {
            WxDbsqVo baseInfo = JSONObject.parseObject(JSON.toJSONString(info), WxDbsqVo.class);

            if (null != info.getState()) {
                baseInfo.setStateName(WxEnum.getCodeForValue(info.getState()));
            }
            infoVoList.add(baseInfo);
        });
        return infoVoList;
    }
}
