package com.heyu.api.controller.vv;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.heyu.api.alibaba.request.mm.order.resp.PropertyNameValue;
import com.heyu.api.alibaba.request.vv.*;
import com.heyu.api.common.annotation.AppRealyLogin;
import com.heyu.api.common.annotation.Describe;
import com.heyu.api.data.dao.vv.*;
import com.heyu.api.data.dto.vv.VvCommentDTO;
import com.heyu.api.data.entity.vv.*;
import com.heyu.api.data.enums.CommentLevelEnums;
import com.heyu.api.data.enums.CommentStatusEnums;
import com.heyu.api.data.utils.R;
import com.heyu.api.utils.ISelect;
import com.heyu.api.utils.PPageUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/app/comment")
public class AppCommentController {

    @Autowired
    private VvCommentDao vvCommentDao;


    @Autowired
    private VvCommentDetailDao vvCommentDetailDao;

    @Autowired
    private VvSkuDao vvSkuDao;

    @Autowired
    private VvProductDao vvProductDao;

    @Autowired
    private VvSkuPropertyValueDao vvSkuPropertyValueDao;

    @Autowired
    private VvBuyerDao vvBuyerDao;


    @Autowired
    private VvTradeOrderLineDao vvTradeOrderLineDao;

    @Autowired
    private VvCommentUserfulDao vvCommentUserfulDao;


    /***
     * 列表
     *  http://localhost:8888/app/comment/list
     */
    @RequestMapping("/list")
    @Describe("评论列表")
    public R list(@RequestBody AppCommentRequest appCommentRequest) {
        PPageUtils pageUtils = null;
        //     /***
        //     * 状态 待审批 wait_approval 待审批, approval_pass，审批通过 , approval_not_pass 审批未通过，如果审批未通过，即自己可见，但别人不可见
        //     */
        //    private String status;
        if (appCommentRequest.getBuyerId() != null) {
            pageUtils = PPageUtils.startPage(appCommentRequest.getPageNum(), appCommentRequest.getPageSize())
                    .doSelect(new ISelect() {
                        @Override
                        public List doSelect(IPage page) {
                            return vvCommentDao.selectLogin(page,
                                    appCommentRequest.getLevel(),
                                    appCommentRequest.getProductId(),
                                    appCommentRequest.getBuyerId(),
                                    CommentStatusEnums.approval_pass.getStatus(),
                                    appCommentRequest.getCreateTimestampSort()
                            );
                        }
                    });
        } else {
            pageUtils = PPageUtils.startPage(appCommentRequest.getPageNum(), appCommentRequest.getPageSize())
                    .doSelect(new ISelect() {
                        @Override
                        public List doSelect(IPage page) {
                            return vvCommentDao.selectNotLogin(page,
                                    appCommentRequest.getProductId(),
                                    CommentStatusEnums.approval_pass.getStatus(),
                                    appCommentRequest.getLevel(),
                                    appCommentRequest.getCreateTimestampSort()
                            );
                        }
                    });
        }
        List<VvCommentEntity> vvCommentEntities = pageUtils.getRows();
        List<VvCommentDTO> vvCommentDTOS = new ArrayList<>();

        List<VvCommentDetailEntity> vvCommentDetailEntities = vvCommentDetailDao.selectVvCommentDetailByProductId(appCommentRequest.getProductId());
        Map<Long, List<VvCommentDetailEntity>> vvDetailMap = new HashMap<>();
        for (VvCommentDetailEntity vvCommentDetailEntity : vvCommentDetailEntities) {

            List<VvCommentDetailEntity> commentDetailEntities = vvDetailMap.get(vvCommentDetailEntity.getCommentId());
            if (commentDetailEntities == null) {
                commentDetailEntities = new ArrayList<>();
            }
            commentDetailEntities.add(vvCommentDetailEntity);
            vvDetailMap.put(vvCommentDetailEntity.getCommentId(), commentDetailEntities);

        }
        List<Long> commentIds = new ArrayList<>();
        for (VvCommentEntity vvCommentEntity : vvCommentEntities) {

            VvCommentDTO vvCommentDTO = new VvCommentDTO();
            BeanUtils.copyProperties(vvCommentEntity, vvCommentDTO);

            commentIds.add(vvCommentDTO.getId());

            List<VvCommentDetailEntity> list = vvDetailMap.get(vvCommentEntity.getId());
            vvCommentDTO.setVvCommentDetailEntities(list);
            vvCommentDTOS.add(vvCommentDTO);
        }

        if (appCommentRequest.getBuyerId() != null && CollectionUtils.isNotEmpty(commentIds)) {
            List<VvCommentUserfulEntity> commentUserfulEntities = vvCommentUserfulDao.selectVvCommentUserfulByCommentId(commentIds, appCommentRequest.getBuyerId());
            for (VvCommentDTO vvCommentDTO : vvCommentDTOS) {
                for (VvCommentUserfulEntity commentUserfulEntity : commentUserfulEntities) {
                    if (vvCommentDTO.getId().equals(commentUserfulEntity.getCommentId())) {
                        vvCommentDTO.setUserful(1);
                    }
                }
            }
        }
        return R.ok().setData(vvCommentDTOS);
    }

    /***
     * /app/comment/add
     */
    @Describe("添加评论")
    @RequestMapping("/add")
    @AppRealyLogin
    public R add(@RequestBody AppCommentAdd appCommentRequest) {
        List<VvTradeOrderLineEntity> vvTradeOrderLineEntityList = vvTradeOrderLineDao.selectVvTradeOrderLineByTrackNumberGroupBySkuId(appCommentRequest.getTrackNumber());
        for (VvTradeOrderLineEntity vvTradeOrderLineEntity : vvTradeOrderLineEntityList) {
            doAddComment(appCommentRequest, vvTradeOrderLineEntity);
            vvTradeOrderLineEntity.setCommentStatus(1);
            vvTradeOrderLineDao.updateVvTradeOrderLineById(vvTradeOrderLineEntity);
        }
        return R.ok();
    }


    public void doAddComment(AppCommentAdd appCommentRequest , VvTradeOrderLineEntity  vvTradeOrderLineEntity) {
        VvCommentEntity vvCommentEntity = new VvCommentEntity();
        vvCommentEntity.setTradeOrderId(vvTradeOrderLineEntity.getTradeOrderId());
        vvCommentEntity.setProductComment(appCommentRequest.getProductComment());


        vvCommentEntity.setSkuId(vvTradeOrderLineEntity.getSkuId());

        VvSkuEntity vvSkuEntity = vvSkuDao.selectVvSkuById(vvTradeOrderLineEntity.getSkuId());
        if(vvSkuEntity == null){
            return ;
        }

        VvProductEntity vvProduct = vvProductDao.selectVvProductById(vvSkuEntity.getProductId());
        if(vvProduct ==null){
            return ;
        }

        vvCommentEntity.setProductId(vvSkuEntity.getProductId());
        vvCommentEntity.setProductTitle(vvProduct.getTitle());

        List<VvSkuPropertyValueEntity> vvSkuPropertyValueEntities = vvSkuPropertyValueDao.selectVvSkuPropertyValueBySkuId(vvSkuEntity.getId());


        //描述相符  1 ~ 5
        Integer descMatch =appCommentRequest.getDescMatch()  !=null    ?appCommentRequest.getDescMatch()   :0  ;
        //卖家服务 1 ~ 5
        Integer sellerService = appCommentRequest.getSellerService()   !=null ? appCommentRequest.getSellerService() : 0 ;
        //物流服务 1 ~ 5
        Integer logisticsService =  appCommentRequest.getLogisticsService()   !=null ?  appCommentRequest.getLogisticsService() : 0 ;

        int levelCount = descMatch + sellerService  + logisticsService;

        String level =  CommentLevelEnums.good.getLevel();

        if(levelCount > 0 && levelCount <= 5 ){
            level = CommentLevelEnums.notgood.getLevel();
        } else if (levelCount > 5 && levelCount <= 10){
            level = CommentLevelEnums.common.getLevel();
        }else {
            level = CommentLevelEnums.good.getLevel();
        }

        List<PropertyNameValue> propertyNameValues = new ArrayList<>();
        for (VvSkuPropertyValueEntity vvSkuPropertyValueEntity : vvSkuPropertyValueEntities) {
            PropertyNameValue propertyNameValue = new PropertyNameValue();
            propertyNameValue.setPropertyName(vvSkuPropertyValueEntity.getProductPropertyName());
            propertyNameValue.setPropertyValue(vvSkuPropertyValueEntity.getProductPropertyValue());
            propertyNameValues.add(propertyNameValue);
        }

        vvCommentEntity.setSkuInfo(JSON.toJSONString(propertyNameValues));
        vvCommentEntity.setStatus(CommentStatusEnums.wait_approval.getStatus());
        vvCommentEntity.setLevel(level);
        vvCommentEntity.setCreateTimestamp(System.currentTimeMillis());
        vvCommentEntity.setServiceComment(appCommentRequest.getServiceComment());
        vvCommentEntity.setDescMatch(appCommentRequest.getDescMatch());
        vvCommentEntity.setSellerService(appCommentRequest.getSellerService());
        vvCommentEntity.setLogisticsService(appCommentRequest.getLogisticsService());
        vvCommentEntity.setUsefulCount(0);

        VvBuyerEntity vvBuyerEntity = vvBuyerDao.selectVvBuyerById(appCommentRequest.getBuyerId());

        vvCommentEntity.setBuyerId(vvBuyerEntity.getId());
        vvCommentEntity.setBuyerName(vvBuyerEntity.getBuyerName());
        vvCommentEntity.setBuyerPhone(vvBuyerEntity.getBuyerPhone());
        vvCommentEntity.setAvatar(vvBuyerEntity.getAvatar());

        vvCommentDao.insert(vvCommentEntity);

        if (CollectionUtils.isNotEmpty(appCommentRequest.getCommentDetailList())) {
            for (AppCommentDetail appCommentDetail : appCommentRequest.getCommentDetailList()) {
                VvCommentDetailEntity vvCommentDetailEntity = new VvCommentDetailEntity();
                vvCommentDetailEntity.setCommentId(vvCommentEntity.getId());
                vvCommentDetailEntity.setCommentUrl(appCommentDetail.getCommentUrl());
                vvCommentDetailEntity.setType(appCommentDetail.getType());
                vvCommentDetailEntity.setProductId(vvCommentEntity.getProductId());
                vvCommentDetailDao.insertOrUpdateVvCommentDetail(vvCommentDetailEntity);
            }
        }

        vvTradeOrderLineDao.updateVvTradeOrderLineCommentIdById(vvCommentEntity.getId(),vvTradeOrderLineEntity.getId());
    }


    /***
     *
     */
    @Describe("评论是否有用")
    @RequestMapping("/useful")
    @AppRealyLogin
    public R useful(@RequestBody AppCommentUseful appCommentRequest) {
        VvCommentUserfulEntity vvCommentUserful = vvCommentUserfulDao.selectVvCommentUserfulByCommentIdBuyerId(appCommentRequest.getCommentId(), appCommentRequest.getBuyerId());
        if (appCommentRequest.getUseful() == 1) {
            if(vvCommentUserful !=null){
                return R.error("已经点过了");
            }
        } else if (appCommentRequest.getUseful() == -1) {
            if (vvCommentUserful == null) {
                return R.error("之前没有点过有用");
            }
            vvCommentUserfulDao.deleteVvCommentUserfulById(vvCommentUserful.getId());

        } else {
            return R.ok();
        }
        VvCommentEntity vvCommentEntity = vvCommentDao.selectVvCommentById(appCommentRequest.getCommentId());
        vvCommentDao.updateVvCommentUserfulByCommidId(appCommentRequest.getUseful(), appCommentRequest.getCommentId());

        if (appCommentRequest.getUseful() == 1) {
            VvCommentUserfulEntity vvCommentUserfulEntity = new VvCommentUserfulEntity();
            vvCommentUserfulEntity.setBuyerId(appCommentRequest.getBuyerId());
            vvCommentUserfulEntity.setCommentId(appCommentRequest.getCommentId());
            vvCommentUserfulEntity.setProductId(vvCommentEntity.getProductId());
            vvCommentUserfulEntity.setSkuId(vvCommentEntity.getSkuId());
            vvCommentUserfulDao.insertOrUpdateVvCommentUserful(vvCommentUserfulEntity);
        }
        return R.ok();
    }


    /***
     * 删除
     */
    @Describe("删除评论")
    @RequestMapping("/delete")
    @AppRealyLogin
    public R list(@RequestBody AppCommentDelete appCommentRequest) {
        VvCommentEntity vvCommentEntity = vvCommentDao.selectVvCommentById(appCommentRequest.getCommentId());

        if (!vvCommentEntity.getBuyerId().equals(appCommentRequest.getBuyerId())) {

            return R.error("评论不是你的，不能删除");
        }

        vvCommentDao.deleteVvCommentById(appCommentRequest.getCommentId());
        return R.ok("删除评论成功");
    }
}
