package com.sifang.modules.platform.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.SourceConstants;
import com.sifang.modules.customer.dao.CustomerDao;
import com.sifang.modules.customer.dao.CustomerWarrantyDao;
import com.sifang.modules.customer.entity.Customer;
import com.sifang.modules.customer.entity.CustomerWarranty;
import com.sifang.modules.order.dao.CrmCustomerWarrantyCardDao;
import com.sifang.modules.order.dao.OrderDao;
import com.sifang.modules.order.entity.CrmCustomerWarrantyCard;
import com.sifang.modules.order.entity.CrmOrder;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.common.service.BaseService;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
public class WarrantyService extends BaseService {

  @Autowired
  private CrmCustomerWarrantyCardDao crmCustomerWarrantyCardDao;
   @Autowired
   private OrderDao orderDao;

    @Autowired
    private CustomerWarrantyDao warrantyDao;
    @Autowired
    private CustomerDao customerDao;


    public List<Record> getFeedBack(String orderId){
      String sql=" SELECT f.order_id,f.device_name,f.device_model,f.device_machine_code  FROM `crm_order_feedback` f WHERE f.order_id=? ";
      return Db.find(sql,orderId);
    }

    @Transactional(rollbackFor=Exception.class)
    public  Result saveWarranty(List<CrmCustomerWarrantyCard> list, String orderId, CustomerWarranty warranty){
        Result result=new Result();
        try{
            if(StringUtil.isNotEmpty(warranty.getCustomerId())){
                long count = getCusWarrantyCouont(warranty.getCustomerId());
                if(count>0){
                    logger.info("getCustomerId ： {} ,已添加过保修卡 ",warranty.getCustomerId() );
                    return Result.fail("202","已添加过保修卡");
                }
            }
            if(StringUtil.isNotEmpty(orderId)){
                CustomerWarranty warr= getByOrderId(orderId);
                if(warr != null){
                    logger.info("getorderId ： {} ,已添加过保修卡 ",orderId );
                    return Result.fail("202","已添加过保修卡");
                }
                CrmOrder order = orderDao.get(orderId);
                if(order!=null){
                    if(SourceConstants.ONE.equals(order.getWarrantyFlag())){   //已生成保修卡
                        result.setCode("500");
                        return result;
                    }
                    order.setLatestProcess("工单生成保修卡 ");
                    order.setLatestProcessTime(new Date());
                    order.setWarrantyFlag(SourceConstants.ONE);
                    orderDao.save(order);
                    //工单生成保修卡
                    if(StringUtil.isNotEmpty(order.getCustomerId())){
                        warranty.setCustomerId(order.getCustomerId());
                    }
                    warranty.setOrderId(orderId);
                    warranty.setApplianceBuyTime(order.getApplianceBuyTime());
                    warranty.setContactName(order.getCustomerName());
                    warranty.setCustomerAddress(order.getProvince()+order.getCity()+order.getArea()+order.getCustomerAddress());
                    warranty.setCustomerMobile(order.getCustomerMobile());
                    warranty.setCustomerName(order.getCustomerName());
                    warranty.setInvoice(order.getInvoice());
                    warranty.setPleaseReferMall(order.getPleaseReferMall());
                }
            }
            if(StringUtil.isNotEmpty(warranty.getCustomerId())){
                Customer customer = customerDao.get(warranty.getCustomerId());
                if(customer != null){
                    customer.setIsWarranty(SourceConstants.TWO);
                    customerDao.save(customer);
                }
            }

            warrantyDao.save(warranty);
            for(CrmCustomerWarrantyCard card:list){
                card.setWarrantyId(warranty.getId());
            }
            crmCustomerWarrantyCardDao.save(list);
            result.setCode("200");
        }catch (Exception e){
            e.printStackTrace();
            result.setCode("400");
        }
       return result;
    }

    public long getCusWarrantyCouont(String cusId){
        return Db.queryLong("SELECT COUNT(*) FROM crm_customer_warranty WHERE customer_id=?",cusId);
    }

    public CustomerWarranty getByOrderId(String orderId){
        return warrantyDao.getByOrderId(orderId);
    }

    public CustomerWarranty getByCustomerId(String customerId){
        return warrantyDao.getByCustomerId(customerId);
    }

    public List<Record> getByWarrantyId(String warrantyId){
        String sql=" SELECT * FROM `crm_customer_warranty_card` WHERE warranty_id=? ";
        return Db.find(sql,warrantyId);
    }


    //根据工单id获取保修卡中的信息
    public List<Record> getWarranty(String orderId){
        String sql=" SELECT * FROM `crm_customer_warranty_card` WHERE order_id=? ";
     return Db.find(sql,orderId);
    }
    /**
     * 删除新增电子保修卡  -- 只用于 手动添加
    */
    @Transactional(rollbackFor=Exception.class)
    public Result deleteWarrantyCard(String customerId){
        Customer customer = customerDao.get(customerId);
        customer.setIsWarranty(SourceConstants.ONE);
        customerDao.save(customer);

        CustomerWarranty warranty = warrantyDao.getByCustomerId(customerId);

        SQLQuery sqlQuery = warrantyDao.getSession().createSQLQuery("DELETE FROM crm_customer_warranty WHERE customer_id= :cuId ");
        sqlQuery.setParameter("cuId", customerId);
        sqlQuery.executeUpdate();

        SQLQuery sqlcard = warrantyDao.getSession().createSQLQuery("DELETE FROM crm_customer_warranty_card WHERE warranty_id= :waId ");
        sqlcard.setParameter("waId", warranty.getId());
        sqlcard.executeUpdate();

        return Result.ok();
    }


}
