package com.lightinit.hsdataportal.impl;

import com.lightinit.hsdataportal.common.OrderNumberUtils;
import com.lightinit.hsdataportal.dictionary.*;
import com.lightinit.hsdataportal.entity.*;
import com.lightinit.hsdataportal.mapper.*;
import com.lightinit.hsdataportal.model.*;
import com.lightinit.hsdataportal.service.IMicroappService;
import com.lightinit.hsdataportal.spring.DynamicDataContextHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class MicroappServiceImpl implements IMicroappService {
    @Autowired
    private ResourceMicroappMapper microappMapper;
    @Autowired
    private ResourceAuthMapper resourceAuthMapper;
    @Autowired
    private ResourceFollowMapper resourceFollowMapper;
    @Autowired
    private OfflineConferenceMapper offlineConferenceMapper;
    @Autowired
    private PublishSettingMapper publishSettingMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private ResourceViewTimesMapper resourceViewTimesMapper;
    /**
     * 开放列表
     * @param inputModel
     * @return
     */
    @Override
    public List<MicroappListModel> selectOpenList(MicroappSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return microappMapper.selectOpenList(inputModel);
    }

    @Override
    public long selectOpenCount(MicroappSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
            return microappMapper.selectOpenCount(inputModel);

    }
    /**
     * 共享列表
     * @param inputModel
     * @param 
     * @return
     */
    @Override
    public List<MicroappListModel> selectShareList(MicroappSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
            return microappMapper.selectShareList(inputModel);

    }

    @Override
    public long selectShareCount(MicroappSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
            return microappMapper.selectShareCount(inputModel);

    }



    public MicroappViewModel queryView(long id,String platformType) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        MicroappViewModel microappViewModel =microappMapper.queryView(id,platformType);
        ResourceViewTimes resourceViewTimes = new ResourceViewTimes() ;
        if (microappViewModel.getViewTimes()==null ){

            resourceViewTimes.setId(microappViewModel.getMicroappId());
            resourceViewTimes.setViewTimes(1);
            resourceViewTimesMapper.insertViews(resourceViewTimes.getId(),resourceViewTimes.getViewTimes());
        }else {
            resourceViewTimesMapper.updateViewTimes(microappViewModel.getMicroappId()) ;
        }
        return microappViewModel;
    }

    @Override
    public MicroappViewModel queryMicroapp(long id) {
        return null;
    }

    @Override
    @Transactional
    public ResultState doApply(MicroappApplyModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        ResourceAuth resourceAuth = new ResourceAuth();
        long sqlResult =0;long sqlResult1 =0;long sqlResult2 =0;
        Date date = new Date();
        inputModel.setCreatedAt(date);
        inputModel.setApplyTime(date);
        PublishSetting publishSetting = publishSettingMapper.selectByPrimaryKey(inputModel.getPublishSettingId());
        if(inputModel.getPlatformType().equals(DicPlatformType.OPEN)){//开放平台
            if(inputModel.getOpenType().equals(DicResourceOpenType.UNCONDITIONAL)) {//无条件开放
                inputModel.setAuditResult(DicResourceAuthAuditResult.AUTHORIZATION_SUCCESS);//授权成功
                BeanUtils.copyProperties(inputModel, resourceAuth);
                resourceAuth.setAuthState(DicResourceAuthAuditResult.AUTHORIZATION_SUCCESS);
                sqlResult = resourceAuthMapper.insert(resourceAuth);
                if(publishSetting.getChargeMethod().equals(DicPublishSettingChargeMethod.FREE)) {//免费
                    //插入order表
                    Order order = new Order() ;
                    order.setUserId(inputModel.getApplier());
                    order.setOrderTime(date) ;
                    order.setOrderNumber(OrderNumberUtils.generate());
                    order.setPlatformType(inputModel.getPlatformType()) ;
                    order.setOrderState(DicOrderState.PAY_SUCCESS);//已付款
                    order.setOrderAmount(publishSetting.getPackagePrice());
                    order.setRemark(publishSetting.getDescription());
                    order.setCreatedAt(date);
                    sqlResult1 = orderMapper.insert(order);
                    //插入order_goods表
                    OrderGoods orderGoods = new OrderGoods() ;
                    orderGoods.setResourceAuthId(resourceAuth.getId());
                    BeanUtils.copyProperties(publishSetting,orderGoods);
                    orderGoods.setOrderId(order.getId());
                    orderGoods.setResourceType(DicResourceType.MICROAPP) ;
                    orderGoods.setResourceName(inputModel.getResourceName());
                    orderGoods.setPublishSettingId(inputModel.getPublishSettingId());
                    orderGoods.setCreatedAt(date);
                    sqlResult2 = orderGoodsMapper.insert(orderGoods);
                }else {
                    //插入order表
                    Order order = new Order() ;
                    order.setUserId(inputModel.getApplier()) ;
                    order.setOrderTime(date) ;
                    order.setOrderNumber(OrderNumberUtils.generate());
                    order.setPlatformType(inputModel.getPlatformType()) ;
                    order.setOrderState(DicOrderState.PAY_WAIT);//待支付
                    order.setOrderAmount(publishSetting.getPackagePrice());
                    order.setRemark(publishSetting.getDescription());
                    order.setCreatedAt(date);
                    order.setPlatformType(inputModel.getOpenType());
                    resultState.setMsg(DicOrderState.PAY_WAIT);
                    resultState.setData(Long.parseLong(order.getOrderNumber()));
                    sqlResult1 = orderMapper.insert(order);
                    //插入order_goods表
                    OrderGoods orderGoods = new OrderGoods() ;
                    BeanUtils.copyProperties(publishSetting,orderGoods);
                    orderGoods.setOrderId(order.getId());
                    orderGoods.setResourceType(DicResourceType.MICROAPP) ;
                    orderGoods.setResourceName(inputModel.getResourceName());
                    orderGoods.setPublishSettingId(inputModel.getPublishSettingId());
                    orderGoods.setCreatedAt(date);
                    sqlResult2 = orderGoodsMapper.insert(orderGoods);
                }
            }
            if(inputModel.getOpenType().equals(DicResourceOpenType.NEED_TO_APPLY)) {//依申请开放

                if(resourceAuth.getAuditResult() !=null && resourceAuth.getAuditResult().equals(DicResourceAuthAuditResult.AUTHORIZATION_SUCCESS)) {
                    Order order = new Order() ;
                    order.setUserId(inputModel.getApplier()) ;
                    order.setOrderTime(date) ;
                    order.setOrderNumber(OrderNumberUtils.generate());
                    order.setPlatformType(inputModel.getPlatformType()) ;
                    order.setOrderState(DicOrderState.PAY_SUCCESS);//已付款
                    order.setOrderAmount(publishSetting.getPackagePrice());
                    order.setRemark(publishSetting.getDescription());
                    order.setCreatedAt(date);
                    order.setPlatformType(inputModel.getOpenType());
                    sqlResult1 = orderMapper.insert(order);
                    //插入order_goods表
                    OrderGoods orderGoods = new OrderGoods() ;
                    orderGoods.setResourceAuthId(resourceAuth.getId());
                    BeanUtils.copyProperties(publishSetting,orderGoods);
                    orderGoods.setOrderId(order.getId());
                    orderGoods.setResourceType(DicResourceType.MICROAPP) ;
                    orderGoods.setResourceName(inputModel.getResourceName());
                    orderGoods.setPublishSettingId(inputModel.getPublishSettingId());
                    orderGoods.setCreatedAt(date);
                    sqlResult2 = orderGoodsMapper.insert(orderGoods);

                }else if(resourceAuth.getAuditResult()==null){

                    BeanUtils.copyProperties(inputModel, resourceAuth);
                    resourceAuth.setAuthState(DicResourceAuthAuditResult.WAIT_AUTHORIZATION);
                    sqlResult = resourceAuthMapper.insert(resourceAuth);
                }
            }
        }
 else{
            if(inputModel.getShareType().equals(DicResourceShareType.UNCONDITIONAL)) {//无条件共享

                BeanUtils.copyProperties(inputModel, resourceAuth);
                resourceAuth.setAuthState(DicResourceAuthAuditResult.AUTHORIZATION_SUCCESS);
                sqlResult = resourceAuthMapper.insert(resourceAuth);

                Order order = new Order() ;
                order.setUserId(inputModel.getApplier()) ;
                order.setOrderTime(date) ;
                order.setOrderNumber(OrderNumberUtils.generate());
                order.setPlatformType(inputModel.getPlatformType()) ;
                //order.setOrderState(DicOrderState.PAY_SUCCESS);//已付款
                order.setOrderAmount(publishSetting.getPackagePrice());
                order.setRemark(publishSetting.getDescription());
                order.setCreatedAt(date);
                order.setPlatformType(inputModel.getShareType());
                sqlResult1 = orderMapper.insert(order);
                //插入order_goods表
                OrderGoods orderGoods = new OrderGoods() ;
                orderGoods.setResourceAuthId(resourceAuth.getId());
                BeanUtils.copyProperties(publishSetting,orderGoods);
                orderGoods.setOrderId(order.getId());
                orderGoods.setResourceType(DicResourceType.MICROAPP) ;
                orderGoods.setResourceName(inputModel.getResourceName());
                orderGoods.setPublishSettingId(inputModel.getPublishSettingId());
                orderGoods.setCreatedAt(date);
                sqlResult2 = orderGoodsMapper.insert(orderGoods);
            }else if(inputModel.getShareType().equals(DicResourceShareType.CONDITIONAL)){//有条件共享
                    BeanUtils.copyProperties(inputModel, resourceAuth);
                    resourceAuth.setAuthState(DicResourceAuthAuditResult.WAIT_AUTHORIZATION);//待授权
                    sqlResult = resourceAuthMapper.insert(resourceAuth);
            }
        }

        if(!(sqlResult>0||(sqlResult1>0&&sqlResult2>0))){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据插入失败");
        }
//        resultState.setData(inputModel.getId());
        return resultState;
    }

    @Override
    public ResourceMicroappWithBLOBs demo(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return microappMapper.demo(id);
    }

    @Override
    public ResultState follow(ResourceFollow model) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        long sqlResult =resourceFollowMapper.insert(model);
        if(!(sqlResult>0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("关注失败");
        }
        resultState.setData(model.getId());
        return resultState;
    }

    @Override
    public ResultState delfollow(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
      long  sqlResult = resourceFollowMapper.deleteByPrimaryKey(id);
        if(!(sqlResult>0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("取消关注失败");
        }
        resultState.setData(id);
        return resultState;
    }

    @Override
    public ResultState<Long> offlineConference(MicroappOfflineConferenceModel inputModel, Long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>() ;

        OfflineConferenceWithBLOBs offlineConferenceWithBLOBs = new OfflineConferenceWithBLOBs() ;
        BeanUtils.copyProperties(inputModel,offlineConferenceWithBLOBs);
        offlineConferenceWithBLOBs.setUserId(id) ;
        offlineConferenceWithBLOBs.setOrderNumber(OrderNumberUtils.generate());
        offlineConferenceWithBLOBs.setSubmitTime(new Date());
        int result = offlineConferenceMapper.insert(offlineConferenceWithBLOBs) ;
        if (!(result>0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("点击洽谈失败");
        }
        return resultState;
    }

    @Override
    public List<ResourceAuth> isAPPly(Long id, Long publishSettingId) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResourceAuth  resourceAuth = new ResourceAuth();
        resourceAuth.setApplier(id);
        resourceAuth.setPublishSettingId(publishSettingId);
        List<ResourceAuth> list = resourceAuthMapper.selectResourceAuth(resourceAuth);
        return list;
    }



//    @Override
//    public PublishSetting selectSettingById(Long publishSettingId) {
//        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
//        return publishSettingMapper.selectByPrimaryKey(publishSettingId);
//    }

//    @Override
//    public ResultState add(Order order) {
//        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
//        ResultState<Long> resultState = new ResultState<Long>() ;
//        int  result = orderMapper.insert(order);
//        if (!(result>0)){
//            resultState.setStateCode(ResultStateCode.INVALID_DATA);
//            resultState.setMsg("数据插入失败");
//        }
//        return resultState;
//    }
//
//    @Override
//    public ResultState add(OrderGoods orderGoods) {
//        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
//        ResultState<Long> resultState = new ResultState<Long>() ;
//        int  result = orderGoodsMapper.insert(orderGoods);
//        if (!(result>0)){
//            resultState.setStateCode(ResultStateCode.INVALID_DATA);
//            resultState.setMsg("数据插入失败");
//        }
//        return resultState;
//    }





}
