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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cftech.cms.SendEmail.EmailSendMessageUtil;
import com.cftech.common.appitems.dao.AppitemsMapper;
import com.cftech.common.appitems.model.Appitems;
import com.cftech.common.cancelitems.dao.CancelitemsMapper;
import com.cftech.common.cancelitems.model.Cancelitems;
import com.cftech.common.grantitems.dao.GrantitemsMapper;
import com.cftech.common.grantitems.model.Grantitems;
import com.cftech.common.manager.dao.ManagerMapper;
import com.cftech.common.manager.model.ManagerDto;
import com.cftech.common.marketing.model.Marketing;
import com.cftech.common.marketing.service.MarketingService;
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.supplier.dao.SupplierMapper;
import com.cftech.common.supplier.model.SupplierDto;
import com.cftech.common.typeappform.model.AppitemsGrantReport;
import com.cftech.common.typeappform.model.TypeAppForm;
import com.cftech.common.typeappform.dao.TypeAppFormMapper;
import com.cftech.common.typeappform.service.TypeAppFormService;
import com.cftech.common.typeform.dao.TypeformMapper;
import com.cftech.common.typeform.model.Typeform;
import com.cftech.core.generic.GenericDao;
import com.cftech.core.generic.GenericServiceImpl;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.DateUtils;
import com.cftech.core.util.MpTokenUtil;
import com.cftech.core.util.StringUtils;
import com.cftech.core.util.SystemConfig;
import com.cftech.showroom.appform.util.DocToPdf;
import org.mp.api.wxsendmsg.JwSendMessageAPI;
import org.mp.api.wxsendmsg.JwTemplateMessageAPI;
import org.owasp.esapi.ESAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

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

/**
 * 类型申请单ServiceImpl
 *
 * @author faye
 * @date: 2019-08-14 16:52
 */
@Service("typeAppFormService")
public class TypeAppFormServiceImpl extends GenericServiceImpl<TypeAppForm> implements TypeAppFormService {

    @Autowired
    @Qualifier("typeAppFormMapper")
    private TypeAppFormMapper typeAppFormMapper;

    @Autowired
    private GrantitemsMapper grantitemsMapper;


    @Autowired
    private AppitemsMapper appitemsMapper;

    @Autowired
    private CancelitemsMapper cancelitemsMapper;

    @Autowired
    private PromotionStockMapper promotionStockMapper;

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private MpTokenUtil mpTokenUtil;

    @Override
    public GenericDao<TypeAppForm> getGenericMapper() {
        return typeAppFormMapper;
    }

    @Override
    public boolean save(TypeAppForm typeAppForm, String items) {
        typeAppFormMapper.save(typeAppForm);
        String item = typeAppForm.getItems();
        item = ESAPI.encoder().decodeForHTML(item);
        JSONArray array = JSON.parseArray(item);
        List<Grantitems> grantitemsList = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            JSONObject obj = array.getJSONObject(i);
            Grantitems grantitems = new Grantitems();
            grantitems.setAccountsId(typeAppForm.getAccountsId());
            grantitems.setAppform(typeAppForm.getId());
            grantitems.setDelFlag(false);
            grantitems.setItemname(obj.getString("name"));
            grantitems.setAppitem(obj.getLong("id"));
            grantitems.setSpecifications(obj.getString("specifications"));
            grantitems.setCover(obj.getString("cover"));
            String price = obj.getString("price");
            grantitems.setPrice(price);
            Integer num = obj.getInteger("num");
            grantitems.setAppCount(num);
            grantitems.setStatus("0");
            grantitemsList.add(grantitems);
        }
        Map<String, Object> params = new HashMap<>();
        params.put("items", grantitemsList);
        grantitemsMapper.saveBatchGrantitems(params);
        typeAppFormMapper.update(typeAppForm);
        return true;
    }


    @Override
    public boolean updatecancelSubmit(TypeAppForm typeAppForm, List<Cancelitems> cancelitemsList) {
        TypeAppForm typeAppFormTemp = typeAppFormMapper.fetchById(typeAppForm.getId());
        BigDecimal bigDecimalTotal = new BigDecimal("0");
        String cItems = typeAppFormTemp.getCItems();
        JSONArray cItmeArray = new JSONArray();
        if (StringUtils.isNotBlank(cItems)) {
            cItmeArray = JSON.parseArray(ESAPI.encoder().decodeForHTML(cItems));
        }
        JSONArray datas = new JSONArray();
        JSONObject objc = new JSONObject();
        for (Cancelitems cancelitems : cancelitemsList) {
            if(cancelitems.getAppitem() == null){
                continue;
            }
            /**
             * 将退库明细，固话至单据中，用于导出
             */
            objc.put("desc",cancelitems.getDescription());
            JSONObject objItems = new JSONObject();
            Long appItemId = cancelitems.getAppitem();
            String price = cancelitems.getPrice();
            Integer cancelCount = cancelitems.getCancelCount();
            objItems.put("name", cancelitems.getItemname());
            objItems.put("id", appItemId);
            objItems.put("price", price);
            objItems.put("count",cancelCount);
            datas.add(objItems);
            objc.put("datas",datas);
            cancelitems.setAppform(typeAppFormTemp.getId());
            cancelitems.setAccountsId(typeAppFormTemp.getAccountsId());
            cancelitems.setDelFlag(false);
            cancelitems.setCancelTime(new Date());
            Map<String, Object> params = new HashMap<>();
            params.put("id", cancelitems.getAppitem());
            params.put("count", cancelitems.getCancelCount());
            params.put("operation", "+");
            int count = appitemsMapper.updateStock(params);
            if (count == 0) {
                throw new RuntimeException("库存更新失败");
            }
            Appitems appitems = appitemsMapper.fetchById(cancelitems.getAppitem());
            /**
             * 增加库存明细
             */
            PromotionStock promotionStock = new PromotionStock();
            promotionStock.setStatus(1);
            promotionStock.setChangeNum(cancelCount);
            promotionStock.setAfterChangeStock(Integer.valueOf(appitems.getAuthenticStock()));
            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(cancelitems.getPrice());
            BigDecimal bigDecimalN = new BigDecimal(cancelitems.getCancelCount());
            //此商品退库金额
            BigDecimal bigDecimalT = (bigDecimalP.multiply(bigDecimalN)).setScale(2, BigDecimal.ROUND_HALF_UP);
            //计算本次所有商品总退库金额
            bigDecimalTotal = (bigDecimalTotal.add(bigDecimalT)).setScale(2, BigDecimal.ROUND_HALF_UP);
            cancelitemsMapper.save(cancelitems);

            //更新发放单的实际发放数量
            Grantitems grantitems = new Grantitems();
            grantitems.setId(cancelitems.getGrantId());
            grantitems.setRealityGrantCount(cancelitems.getRealityGrantCount());
            grantitems.setManagerGrantCount(cancelitems.getManagerGrantCount());
            grantitemsMapper.update(grantitems);
        }
        cItmeArray.add(objc);
        if(cItmeArray!=null && cItmeArray.size()>0){
            typeAppForm.setcItems(cItmeArray.toJSONString());
        }
        BigDecimal totalPrice = new BigDecimal(typeAppFormTemp.getTotalPrice());

        //原有发放总金额-本次退库总金额 实际发放总金额
        typeAppForm.setTotalPrice(totalPrice.subtract(bigDecimalTotal).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        typeAppForm.setIsCancel("1");//退库
        typeAppFormMapper.update(typeAppForm);
        return true;
    }

    @Override
    public boolean updateSubmitGrantCount(TypeAppForm typeAppForm, List<Grantitems> grantitemsList) {
        BigDecimal bigDecimalTotal = null;
        BigDecimal supplierBigDecimalTotal = null;
        for (Grantitems grantitems : grantitemsList) {
            grantitems.setGrantTime(new Date());
            if(grantitems.getManagerGrantCount()!=null){
                if(bigDecimalTotal==null){
                    bigDecimalTotal= new BigDecimal("0");
                }
                //计算管理员发放金额
                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);
            }
            //计算供应商发放金额
            if(grantitems.getDisGrantCount()!=null){
                if(supplierBigDecimalTotal==null){
                    supplierBigDecimalTotal = new BigDecimal("0");
                }
                //计算管理员发放金额
                BigDecimal bigDecimalP = new BigDecimal(grantitems.getPrice());
                BigDecimal bigDecimalN = new BigDecimal(grantitems.getDisGrantCount());
                //此商品发放金额
                BigDecimal bigDecimalT = (bigDecimalP.multiply(bigDecimalN)).setScale(2, BigDecimal.ROUND_HALF_UP);
                //计算总发放金额
                supplierBigDecimalTotal = (supplierBigDecimalTotal.add(bigDecimalT)).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            grantitemsMapper.update(grantitems);
        }
        typeAppForm.setTotalPrice(bigDecimalTotal!=null?bigDecimalTotal.toString():null);
        typeAppForm.setDisTotalPrice(supplierBigDecimalTotal!=null?supplierBigDecimalTotal.toString():null);
        typeAppForm.setIssuingState("0");
        typeAppFormMapper.update(typeAppForm);
        /**
         * 通知供应商进行发货
         */
        //发货方式为仅供应商或者供应商+管理员时则进行推送
        if(StringUtils.equals(typeAppForm.getGrantSource(),"0") || StringUtils.equals("2",typeAppForm.getGrantSource())) {
            TypeAppForm typeAppFormTemp = typeAppFormMapper.fetchById(typeAppForm.getId());
            List<SupplierDto> supplierDtos = supplierMapper.fetchOpenidNickName(typeAppFormTemp.getTypeform());
            if (!supplierDtos.isEmpty()) {
                List<String> openIds = new ArrayList<>();
                for (SupplierDto supplierDto : supplierDtos) {
                    openIds.add(supplierDto.getOpenid());
                }

                CommonSendUtils.managerGrantSubmitSendSupplier(openIds, typeAppFormTemp.getId(),
                        typeAppFormTemp.getCreateTime(),
                        typeAppFormTemp.getNumber(),
                        mpTokenUtil.getToken(typeAppFormTemp.getAccountsId())
                );
            }
        }
        return true;
    }

    @Override
    public boolean updateMarketRefuse(TypeAppForm typeAppForm) {
        typeAppForm.setStatus("5");
        typeAppFormMapper.update(typeAppForm);
        return false;
    }

    @Override
    public List<AppitemsGrantReport> getAppitemsGrantReport(String typeform) {
        Map<String,Object> params = new HashMap<>();
        params.put("typeform",typeform);
        return typeAppFormMapper.getAppitemsGrantReport(params);
    }

    @Override
    public String getSumGrantPrice(Conds conds, String type) {
        Map<String, Object> params = new HashMap<>();

        params.put("conds", conds);
        params.put("type", type);
        params.put("costCenters",SystemConfig.p.getProperty("STATISTICSCOSTCENTERS").split(","));
        return typeAppFormMapper.getSumGrantPrice(params);
    }

    @Override
    public List<TypeAppForm> fetchSearchByPage(Conds conds, Sort sort, int page, int pageSize, String isDisRole) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("conds", conds);
        params.put("offset", page > 0 ? page : 0);
        params.put("limit", pageSize > 0 ? pageSize : 0);
        params.put("sort", sort);
        params.put("isDisRole",isDisRole);
        return typeAppFormMapper.fetchSearchByPageServer(params);
    }

    @Override
    public int countServer(Conds conds,String isDisRole) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("conds", conds);
        params.put("isDisRole",isDisRole);
        return typeAppFormMapper.countServer(params);
    }
}
