package com.iamberry.wechat.service.warranty;

import com.iamberry.wechat.core.entity.admin.ShopSystemRule;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.product.ProductColor;
import com.iamberry.wechat.core.entity.warrantyCard.WarrantyCard;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.mq.EfastOrderService;
import com.iamberry.wechat.face.warranty.WarrantyService;
import com.iamberry.wechat.service.mapper.ProductInfoMapper;
import com.iamberry.wechat.service.mapper.WarrantyMapper;
import com.iamberry.wechat.service.member.dao.MemberDao;
import com.iamberry.wechat.tools.ResultInfo;
import net.sf.json.JSONArray;
import org.elasticsearch.common.inject.assistedinject.AssistedInject;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 质保卡servlet
 * Created by liuzhiwei on 2017/12/21.
 */
@Service
public class WarrantyServiceImpl implements WarrantyService {

    @Autowired
    private EfastOrderService efastOrderService;
    @Autowired
    private ProductInfoMapper productInfoMapper;
    @Autowired
    private SystemService systemService;
    @Autowired
    private WarrantyMapper warrantyMapper;
    @Autowired
    private MemberDao memberDao;
    @Override
    public boolean addWarrantyList(String txtOrderId, Member member, String cardWatero,
                                   String cardProvince, String cardCity, String cardDistrict) throws Exception {

        List<WarrantyCard> cardList = new ArrayList<WarrantyCard>();
        boolean flag = false;
        int sum = 0;
        //循环添加机器信息
        if (txtOrderId != null && !"".equals(txtOrderId)) {
            txtOrderId = txtOrderId.substring(0,txtOrderId.lastIndexOf(","));
            //获取交易号
            String[] orderIds = txtOrderId.split(":");
            for (int i = 0;i < orderIds.length;i++) {
                //获取百胜订单详情
                net.sf.json.JSONObject orderInfo = efastOrderService.getOrderFormEfast(orderIds[i]);
                if (orderInfo == null || !orderInfo.has("orders")) {
                    return flag;
                }
                //获取订单项集合
                JSONArray itemArray = orderInfo.getJSONArray("orders");
                if (itemArray == null || itemArray.size() == 0) {

                }
                for (int j = 0;j < itemArray.size();j++) {
                    ProductColor color = new ProductColor();
                    net.sf.json.JSONObject itemJson = itemArray.getJSONObject(j);
                    color.setColor69Code(itemJson.getString("goods_sn"));
                    //根据产品69码查询产品颜色信息
                    color = productInfoMapper.getProductColor(color);
                    if (color == null) {
                        continue;
                    }
                    //获取换新时间期限
                    ShopSystemRule endRule =  systemService.selectOneShopRuleById(242);
                    WarrantyCard card = new WarrantyCard();
                    card.setCardSalesTime(new Date(orderInfo.getLong("pay_time")*1000));
                    card.setProductChildType(color.getProductChildType());
                    card.setProductType(color.getColorProductType());
                    card.setCardEndTime(updateDate(card.getCardSalesTime(),endRule.getRuleNum().intValue()));
                    card.setCardCity(cardCity);
                    card.setCardDistrict(cardDistrict);
                    card.setCardProvince(cardProvince);
                    card.setCardWatero(Integer.parseInt(cardWatero));
                    card.setCardProductName(color.getColorProductName());
                    card.setCardTypeState(1);
                    card.setUserOpenId(member.getUserOpenid());
                    card.setCardCreateDate(new Date());

                    //查询该质保卡信息，如果存在，则不再添加
                    List<WarrantyCard> list = warrantyMapper.listWarrantyCard(card);
                    if (list != null || list.size() > 0) {
                        continue;
                    }

                    //生成编号
                    sum++;
                    String userid = member.getUserId().toString();
                    int len = 11;//条形码不加sum的定长
                    StringBuilder berQrcode = new StringBuilder(userid);
                    String dateTime = String.valueOf(new Date().getTime());
                    int dateTimeLen = len - userid.length();
                    dateTime = dateTime.substring(0,dateTimeLen);
                    berQrcode.append(dateTime);
                    card.setCardNo(berQrcode.toString() + sum);
                    cardList.add(card);
                }
            }
        }
        //修改用户信息
        int count = memberDao.updateMemberByUserId(member);
        //批量添加质保卡信息
        int num = 1;
        if (cardList != null && cardList.size() > 0) {
            num = warrantyMapper.addWarrantyCardList(cardList);
        }
        if (num > 0 && count > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 修改日期 增加月
     * @param date
     * @param month
     * @return
     * @throws Exception
     */
    public Date updateDate(Date date,int month) throws Exception {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, month);
        return calendar.getTime();
    }

    @Override
    public List<WarrantyCard> listWarrantyCard(WarrantyCard warrantyCard) {
        return warrantyMapper.listWarrantyCard(warrantyCard);
    }
}
