package com.cftech.common.typeappform.service.impl;

import com.cftech.common.appitems.dao.AppitemsMapper;
import com.cftech.common.appitems.model.Appitems;
import com.cftech.common.grantitems.dao.GrantitemsMapper;
import com.cftech.common.grantitems.model.Grantitems;
import com.cftech.common.manager.model.ManagerDto;
import com.cftech.common.manager.service.ManagerService;
import com.cftech.common.promotionstock.dao.PromotionStockMapper;
import com.cftech.common.promotionstock.model.PromotionStock;
import com.cftech.common.send.util.CommonSendUtils;
import com.cftech.common.send.util.CommonWorkFlowConstants;
import com.cftech.common.typeappform.dao.TypeAppFormMapper;
import com.cftech.common.typeappform.model.TypeAppForm;
import com.cftech.common.typeappform.service.AppformGrantService;
import com.cftech.common.typeappform.service.TypeAppFormService;
import com.cftech.core.sql.Conds;
import com.cftech.core.util.MpTokenUtil;
import com.cftech.core.util.StringUtils;
import com.cftech.showroom.appform.util.DocToPdf;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.owasp.esapi.ESAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author lisw
 * @program schaeffler
 * @description 策略模式供应商发货业务实现
 * @createDate 2020-01-14 15:28:10
 **/
@Service("disGrantService")
public class DisAppformGrantServiceImpl implements AppformGrantService {



    @Autowired
    private AppitemsMapper appitemsMapper;

    @Autowired
    private GrantitemsMapper grantitemsMapper;

    @Autowired
    private TypeAppFormMapper typeAppFormMapper;

    @Autowired
    private MpTokenUtil mpTokenUtil;

    @Autowired
    private TypeAppFormService typeAppFormService;

    @Autowired
    private PromotionStockMapper promotionStockMapper;

    @Override
    public boolean updateGrantService(TypeAppForm typeAppForm,ThreadPoolTaskExecutor threadPoolTaskExecutor) {
        Conds formIdConds = new Conds();
        formIdConds.equal("ca.id", typeAppForm.getId());
        TypeAppForm typeAppFormTemp =typeAppFormService.fetchSearchByConds(formIdConds);
       // BigDecimal bigDecimalTotal = new BigDecimal("0");
        String items = ESAPI.encoder().decodeForHTML(typeAppFormTemp.getItems());
        JSONArray arrayItems = JSONArray.fromObject(items);
        JSONArray arrayTemp = new JSONArray();
        boolean isAllDelivery = false;
        switch (typeAppFormTemp.getGrantSource()){
            //仅供应商发货，则发送模版消息，并且发放状态更改为全部已发货
            case "0":
               isAllDelivery = true;
                break;
            case "1":
                break;
            //发货渠道为供应商+管理员
            case "2":
                //此前管理员已经发货，供应商发货后则为全部发货
                if("2".equals(typeAppFormTemp.getIssuingState())){
                    isAllDelivery = true;
                }else{
                    //设置管理员已发货
                    typeAppForm.setIssuingState("1");
                }
                break;
        }
        for(int i =0;i<arrayItems.size();i++){
            JSONObject itemObject = arrayItems.getJSONObject(i);
            Grantitems grantitems = new Grantitems();
            grantitems.setId(itemObject.getLong("grantId"));
            grantitems.setPrice(itemObject.getString("price"));
            grantitems.setAppitem(itemObject.getLong("id"));
            Integer disGrantCount = itemObject.getInt("disGrantCount");
            grantitems.setDisGrantCount(disGrantCount);
            Map<String, Object> params = new HashMap<>();
            Long appItemId = grantitems.getAppitem();
            params.put("id", appItemId);
            params.put("count",disGrantCount);
            params.put("operation", "-");
            int count = appitemsMapper.updateDisStock(params);
            if (count == 0){
                throw new RuntimeException("库存更新失败");
            }
            Appitems appitems = appitemsMapper.fetchById(appItemId);
            grantitems.setDisGrantTime(new Date());
            Integer disAfterStock = appitems.getDisStock();
            grantitems.setDisAfterStock(disAfterStock);
            if(isAllDelivery){
                grantitems.setDeliveryTime(new Date());
            }
            grantitemsMapper.update(grantitems);
            /**
             * 增加库存明细
             */
            PromotionStock promotionStock = new PromotionStock();
            promotionStock.setStatus(1);
            promotionStock.setChangeNum(0-grantitems.getDisGrantCount());
            promotionStock.setAfterChangeStock(disAfterStock);
            promotionStock.setType(CommonWorkFlowConstants.PROMOTION_STOCK_DIS_TYPE);
            promotionStock.setCreateBy(typeAppFormTemp.getCreateBy());
            promotionStock.setCreateTime(new Date());
            promotionStock.setItemId(appItemId);
            promotionStock.setFormId(typeAppForm.getId());
            promotionStockMapper.save(promotionStock);


            /**
             * 在管理员录入发货量时，这些金额都已确定，无需在进行重新赋值
             */
//            BigDecimal bigDecimalP = new BigDecimal(grantitems.getPrice());
//            BigDecimal bigDecimalN = new BigDecimal(grantitems.getDisGrantCount());
            //此商品发放金额
           // BigDecimal bigDecimalT = (bigDecimalP.multiply(bigDecimalN)).setScale(2, BigDecimal.ROUND_HALF_UP);
            //计算总发放金额
           // bigDecimalTotal = (bigDecimalTotal.add(bigDecimalT)).setScale(2, BigDecimal.ROUND_HALF_UP);
            //发放明细中，将某促销品的剩余库存固化进去
            itemObject.put("afterDisStock",appitems.getDisStock());
            arrayTemp.add(itemObject);
        }
        //实际发放总金额
        //typeAppForm.setDisTotalPrice(bigDecimalTotal.toString());
        String logisticsOrderInfo = StringUtils.isNotBlank(typeAppFormTemp.getLogisticsOrderInfo())?typeAppFormTemp.getLogisticsOrderInfo():" ";
        String disLogisticsOrderInfo =StringUtils.isNotBlank(typeAppForm.getDisLogisticsOrderInfo())?typeAppForm.getDisLogisticsOrderInfo():" ";
        String allLogisticsOrderInfo = logisticsOrderInfo+disLogisticsOrderInfo;
        String token = mpTokenUtil.getToken(typeAppFormTemp.getAccountsId());
        if (isAllDelivery){
           sendMessage(typeAppFormTemp,typeAppForm,allLogisticsOrderInfo,token);
        }

        //通知管理员
        CommonSendUtils.grantPromotionSendManager(getManagersOpenIds(typeAppFormTemp.getTypeform()),allLogisticsOrderInfo
                ,new Date(),token,typeAppFormTemp.getId(),typeAppFormTemp.getNumber()
        );
        typeAppForm.setItems(arrayTemp.toString());
        typeAppFormMapper.update(typeAppForm);
        return true;
    }
    public void sendMessage(TypeAppForm typeAppFormTemp,TypeAppForm typeAppForm,String allLogisticsOrderInfo,String token){
        //通知申请人
        CommonSendUtils.grantPromotionSendApply(typeAppFormTemp.getOpenid(),
                typeAppFormTemp.getId(),
                new Date(),
                typeAppFormTemp.getName(),
                allLogisticsOrderInfo,
                mpTokenUtil.getToken(typeAppFormTemp.getAccountsId()),
                typeAppForm.getNumber()

        );
        typeAppForm.setIssuingState("3");

    }

    @Autowired
    private ManagerService managerService;

    public List<String> getManagersOpenIds(Long typeform) {
        List<String> managerOpenIds = new ArrayList<>();
        List<ManagerDto> managerDtos = managerService.fetchOpenidNickName(typeform);
        if (managerDtos != null && managerDtos.size() > 0) {
            for (ManagerDto managerDto : managerDtos) {
                managerOpenIds.add(managerDto.getOpenid());
            }
        }
        return managerOpenIds;
    }
}
