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.common.typeform.model.Typeform;
import com.cftech.core.sql.Conds;
import com.cftech.core.util.MpTokenUtil;
import com.cftech.core.util.StringUtils;
import com.cftech.showroom.appform.dao.AppFormMapper;
import com.cftech.showroom.appform.util.DocToPdf;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.owasp.esapi.ESAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
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:26:53
 **/
@Service("managerGrantService")
public class ManagerAppformGrantServiceImpl 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 array = new JSONArray();
        //是否全部已经发货
        boolean isAllDelivery = false;
        switch (typeAppFormTemp.getGrantSource()){
            case "0":
                break;
            //仅管理员发货，则发送模版消息，并且发放状态更改为全部已发货
            case "1":
               isAllDelivery = true;
                break;
            //发货渠道为供应商+管理员
            case "2":
                //此前供应商已经发货，管理员发货后则为全部发货
                if("1".equals(typeAppFormTemp.getIssuingState())){
                   isAllDelivery = true;
                }else{
                    //设置管理员已发货
                    typeAppForm.setIssuingState("2");
                }
                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"));
            grantitems.setManagerGrantCount(itemObject.getInt("managerGrantCount"));
            Map<String, Object> params = new HashMap<>();
            Long appItemId = grantitems.getAppitem();
            params.put("id", appItemId);
            params.put("count",grantitems.getManagerGrantCount());
            params.put("operation", "-");
            int count = appitemsMapper.updateStock(params);
            if (count == 0) {
                throw new RuntimeException("库存更新失败");
            }
            Appitems appitems = appitemsMapper.fetchById(appItemId);
            Integer afterManagerStock = Integer.valueOf(appitems.getAuthenticStock());
            grantitems.setManagerAfterStock(afterManagerStock);
            grantitems.setManagerGrantTime(new Date());
            if(isAllDelivery){
                grantitems.setDeliveryTime(new Date());
            }
            grantitemsMapper.update(grantitems);
            /**
             * 增加库存明细
             */
            PromotionStock promotionStock = new PromotionStock();
            promotionStock.setStatus(1);
            promotionStock.setChangeNum(0-grantitems.getManagerGrantCount());
            promotionStock.setAfterChangeStock(afterManagerStock);
            promotionStock.setType(CommonWorkFlowConstants.PROMOTION_STOCK_MANAGER_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.getManagerGrantCount());
//            //此商品发放金额
//            BigDecimal bigDecimalT = (bigDecimalP.multiply(bigDecimalN)).setScale(2, BigDecimal.ROUND_HALF_UP);
//            //计算总发放金额
//            bigDecimalTotal = (bigDecimalTotal.add(bigDecimalT)).setScale(2, BigDecimal.ROUND_HALF_UP);

            //发放明细中，将某促销品的剩余库存固化进去
            itemObject.put("afterManagerStock",appitems.getAuthenticStock());
            array.add(itemObject);
        }
        //实际发放总金额
        //typeAppForm.setTotalPrice(bigDecimalTotal.toString());
        if (isAllDelivery){
            sendMessage(typeAppFormTemp,typeAppForm,threadPoolTaskExecutor);
        }
        typeAppForm.setItems(array.toString());
        typeAppFormMapper.update(typeAppForm);
        return true;
    }
    public void sendMessage(TypeAppForm typeAppFormTemp,TypeAppForm typeAppForm,ThreadPoolTaskExecutor threadPoolTaskExecutor){
        //CommonSendUtils.sendApplicationGrantTemplate(mpTokenUtil.getToken(typeAppFormTemp.getAccountsId()), typeAppFormTemp.getOpenid(), typeAppFormTemp.getId(), typeAppFormTemp.getName(), typeAppFormTemp.getCreateTime());
        typeAppForm.setIssuingState("3");
        //通知申请人
        String logisticsOrderInfo = StringUtils.isNotBlank(typeAppForm.getLogisticsOrderInfo())?typeAppForm.getLogisticsOrderInfo():" ";
        String disLogisticsOrderInfo =StringUtils.isNotBlank(typeAppFormTemp.getDisLogisticsOrderInfo())?typeAppFormTemp.getDisLogisticsOrderInfo():" ";
        String allLogisticsOrderInfo = logisticsOrderInfo+disLogisticsOrderInfo;
        String token = mpTokenUtil.getToken(typeAppFormTemp.getAccountsId());
        CommonSendUtils.grantPromotionSendApply(typeAppFormTemp.getOpenid(),
                typeAppFormTemp.getId(),
                new Date(),
                typeAppFormTemp.getName(),
                allLogisticsOrderInfo,
                token,typeAppFormTemp.getNumber()

        );
        //通知管理员
//        CommonSendUtils.grantPromotionSendManager(getManagersOpenIds(typeAppFormTemp.getTypeform()),allLogisticsOrderInfo
//                ,new Date(),token,typeAppFormTemp.getId(),typeAppFormTemp.getNumber()
//        );
        typeAppForm.setIssuingState("3");
//        threadPoolTaskExecutor.execute(new Runnable() {
//            @Override
//            public void run() {
//                /**
//                 * 发送附件给管理员
//                 */
//                Map<String, Object> params = CommonSendUtils.grantdata(typeAppFormTemp, typeAppFormTemp.getItems());
//                String pdfPath = null;
//                try {
//                    pdfPath = DocToPdf.DocToPdf(params, "cuxiaopingrantdocument.xml", "cuxiaopingrant.docx");
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                List<File> files = new ArrayList<File>();
//                File file = new File(pdfPath);
//                files.add(file);
//                String[] results = CommonSendUtils.sendManagerMailPdf(typeAppFormTemp.getNumber(),files);
//                if (results != null && "0".equals(results[0]) && file != null && file.exists()) {
//                    file.delete();
//                }
//            }
//        });
    }

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