package com.sifang.modules.supply.setting.service;


import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.UserConstants;
import com.sifang.modules.flowpath.entity.SupplyWarehouseApply;
import com.sifang.modules.flowpath.entity.TraderApply;
import com.sifang.modules.kingdee.service.WarehouseService;
import com.sifang.modules.kingdee.vo.KingDeeResponseVo;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.setting.constant.WarehouseConstants;
import com.sifang.modules.supply.setting.dao.CrmSupplyWarehouseDao;
import com.sifang.modules.supply.setting.entity.CrmSupplyWarehouse;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.entity.Ascription;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import com.sifang.modules.sys.web.BaseExceptionController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
import java.util.Map;
import java.util.Objects;

@Service
public class CrmSupplyWarehouseSettingService extends BaseExceptionController {

    Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    private CrmSupplyWarehouseDao crmSupplyWarehouseDao;

    @Autowired
    private WarehouseService jDWarehouseService;

    public LayuiPage getWarehousePage(LayuiPage page,Map<String, String> map){
        User user = UserUtils.getUser();
        String userType = CrmUtils.getCurrentUserType(user);
        if(!UserConstants.TYPE_ADMIN.equals(userType)){
            Ascription ascription=CrmUtils.getAscription();
            map.put("ascriptionId",ascription.getAscriptionId());
        }
        List<Record> list = crmSupplyWarehouseDao.getList(page, map);
        for (Record record : list) {
            String province = record.getStr("province");
            String city = record.getStr("city");
            String area = record.getStr("area");
            String address = record.getStr("address");
            address = province + "" +city+""+ area + "" + address;
            // 将拼接后的 address 值重新放回 Record 对象
            record.set("address", address);
        }
        page.setData(list);
        page.setCount(crmSupplyWarehouseDao.countList(map));
        return page;
    }

    public List<Record> getSupplyList(){
        return Db.find(" SELECT  s.id,s.name FROM `crm_supply_supplier` s WHERE s.status='0' ORDER BY s.create_time DESC  ");
    }

    public List<Record> getSupplyListByBrand(String brand){
        return Db.find(" SELECT  s.id,s.name FROM `crm_supply_supplier` s LEFT JOIN `crm_supply_material_brand` b ON b.id=s.material_brand_id WHERE s.status='0' AND b.name=?  ORDER BY s.create_time DESC  ",brand.trim());
    }


    @Transactional(rollbackFor = Exception.class)
    public void addWarehouse(CrmSupplyWarehouse req){
        CrmSupplyWarehouse warehouse;
        Date date=new Date();
        User user=UserUtils.getUser();
        Boolean fg=false;
        if(StringUtil.isBlank(req.getId())){
            if (crmSupplyWarehouseDao.checkQqCode(req.getQqCode(),null)){
                throw new BusinessException("外部编码已存在,请确认后重新输入！");
            }
            Ascription ascription=CrmUtils.getAscription();
            //判断是否有在使用的仓库
            warehouse=new CrmSupplyWarehouse();
            if(User.USER_TYPE_KJ.equals(user.getUserType())||User.USER_TYPE_ADVISOR.equals(user.getUserType())){

            }else{

                warehouse.setCreateTime(date);
                warehouse.setCreator(user.getId());
                if (User.USER_TYPE_YYS.equals(user.getUserType()) || User.USER_TYPE_PTYG.equals(user.getUserType())){
                    warehouse.setType("1");

                }else  if (User.USER_TYPE_GYS.equals(user.getUserType())){
                    warehouse.setType("3");
                    warehouse.setNumber(CrmUtils.no());
                }
                warehouse.setAscriptionName(ascription.getAscriptionName());
                warehouse.setAscriptionId(ascription.getAscriptionId());
            }

        }else{
            warehouse=crmSupplyWarehouseDao.get(req.getId());
            if(warehouse==null){
                throw new BusinessException("该仓库不存在！");
            }

            if (crmSupplyWarehouseDao.checkQqCode(req.getQqCode(),req.getId())){
                throw new BusinessException("外部编码已存在,请确认后重新输入！");
            }

            warehouse.setUpdateTime(date);
            warehouse.setModifier(user.getId());
            //判断是否有修改
            if(!Objects.equals(req.getName(), warehouse.getName())){
                fg=true;
            }else if(!Objects.equals(req.getProvince()+req.getCity()+req.getArea()+req.getAddress(), warehouse.getProvince()+warehouse.getCity()+warehouse.getArea()+warehouse.getAddress())){
                fg=true;
            }else if(Objects.equals(req.getMobile(), warehouse.getMobile())){
                fg=true;
            }
        }

        commonField(req,warehouse);
        String kingDeeId="";
        //推入金蝶系统
    /*    try{
            if(StringUtil.isBlank(warehouse.getId()) && "1".equals(warehouse.getType())){
                KingDeeResponseVo responseVo=jDWarehouseService.saveWarehouse(warehouse);
                kingDeeId=responseVo.getId();
                warehouse.setKingDeeId(kingDeeId);
                String number=responseVo.getNumber();
                warehouse.setNumber(number);
            }else if(StringUtil.isNotBlank(warehouse.getKingDeeId())){
                if(fg){  //只有改了部分字段  才会推送
                    jDWarehouseService.editWarehouse(warehouse);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(">>>>>>>>>>>>>>>>>>>addWarehouse e:{}",e);
            throw new BusinessException("导入金蝶系统错误,"+e.getMessage()+"!");
        }*/

        warehouse.setQqCode(req.getQqCode());
        crmSupplyWarehouseDao.save(warehouse);
    }


    @Transactional(rollbackFor = Exception.class)
    public String addTraderWarehouse(SupplyWarehouseApply req){
        CrmSupplyWarehouse warehouse;
        Date date=new Date();
        User user=UserUtils.getUser();

        if(StringUtil.isBlank(req.getWarehouseId())){
            //判断是否有在使用的仓库
            warehouse=new CrmSupplyWarehouse();
            warehouse.setType("2");
            warehouse.setNumber(CrmUtils.no());
            warehouse.setCreateTime(date);
            warehouse.setCreator(user.getId());
            warehouse.setAscriptionId(req.getAscriptionId());
            warehouse.setAscriptionName(req.getAscriptionName());
        }else{
            warehouse=crmSupplyWarehouseDao.get(req.getWarehouseId());
            if(warehouse==null){
                throw new BusinessException("该仓库不存在！");
            }
            warehouse.setUpdateTime(date);
            warehouse.setModifier(user.getId());

        }
        warehouse.setName(req.getName());
        warehouse.setPersonInCharge(req.getPersonInCharge());
        warehouse.setMobile(req.getMobile());
        warehouse.setProvince(req.getProvince());
        warehouse.setCity(req.getCity());
        warehouse.setArea(req.getArea());
        warehouse.setAddress(req.getAddress());
        warehouse.setImgs(req.getImgs());
        warehouse.setQualificationsImgs(req.getQualificationsImgs());
        warehouse.setEvidence(req.getEvidence());
        warehouse.setAttribute(req.getAttribute());
        warehouse.setRemarks(req.getRemarks());

        crmSupplyWarehouseDao.save(warehouse);
        return warehouse.getId();
    }


    public void commonField(CrmSupplyWarehouse req,CrmSupplyWarehouse warehouse){
      if(checkName(req.getName(),req.getId(),warehouse.getAscriptionId())){
          throw new BusinessException("该仓库已存在，请勿重复添加！");
      }
      warehouse.setName(req.getName());
      warehouse.setPersonInCharge(req.getPersonInCharge());
      warehouse.setMobile(req.getMobile());
      warehouse.setProvince(req.getProvince());
      warehouse.setCity(req.getCity());
      warehouse.setArea(req.getArea());
      warehouse.setAddress(req.getAddress());
      warehouse.setImgs(req.getImgs());
      warehouse.setQualificationsImgs(req.getQualificationsImgs());
      warehouse.setRemarks(req.getRemarks());
    }

    public Boolean checkName(String name,String id,String ascriptionId){
       StringBuffer sb=new StringBuffer();
       sb.append(" SELECT COUNT(w.id) FROM `crm_supply_warehouse` w WHERE w.status<>'2' AND w.name=? and w.ascription_id=? ");
       if(StringUtil.isNotBlank(id)){
           sb.append(" AND w.id<>'"+ id +"' ");
       }
       long count=Db.queryLong(sb.toString(),name,ascriptionId);
       return count>0?true:false;
    }

    public CrmSupplyWarehouse getWarehouseDetail(String id){
        return crmSupplyWarehouseDao.get(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public void disabledWarehouse(String id){
        CrmSupplyWarehouse warehouse=crmSupplyWarehouseDao.get(id);
        if(warehouse==null){
            throw new BusinessException("该仓库不存在！");
        }
        warehouse.setUpdateTime(new Date());
        warehouse.setModifier(UserUtils.getUser().getId());
        warehouse.setStatus(WarehouseConstants.DISABLED);
     /*   try {
            logger.info(">>>>>>>>>>>>disabledWarehouse  id:{}",id);
            if(StringUtil.isNotBlank(warehouse.getKingDeeId())){
                jDWarehouseService.hiddenWarehouse(warehouse.getKingDeeId());
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(">>>>>>>>>>>>>>>>>>>disabledWarehouse e:{}",e);
            throw new BusinessException("禁用失败,导入金蝶系统错误,请联系管理员！");
        }*/
        crmSupplyWarehouseDao.save(warehouse);
    }

    @Transactional(rollbackFor = Exception.class)
    public void canUsedWarehouse(String id){
        CrmSupplyWarehouse warehouse=crmSupplyWarehouseDao.get(id);
        if(warehouse==null){
            throw new BusinessException("该仓库不存在！");
        }
        /*if("1".equals(warehouse.getType())){
            List<Record> list =  crmSupplyWarehouseDao.findByTypeAndAscriptionId("1",warehouse.getAscriptionId());
            if(list.size()>0){
                throw new BusinessException("已存在正使用的仓库，不可启用！");
            }
        }*/
        warehouse.setUpdateTime(new Date());
        warehouse.setModifier(UserUtils.getUser().getId());
        warehouse.setStatus(WarehouseConstants.NORMAL);
       /* try {
            logger.info(">>>>>>>>>>>>canUsedWarehouse  id:{}",id);
            if(StringUtil.isNotBlank(warehouse.getKingDeeId())){
                jDWarehouseService.useWarehouse(warehouse.getKingDeeId());
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(">>>>>>>>>>>>>>>>>>>canUsedWarehouse e:{}",e);
            throw new BusinessException("启用失败,导入金蝶系统错误,请联系管理员！");
        }*/
        crmSupplyWarehouseDao.save(warehouse);
    }

    public List<Record> findByType(String type) {
        return crmSupplyWarehouseDao.findByType(type);
    }

    public List<Record> supplyChainWarehouses(){
        return Db.find("select * from crm_supply_warehouse where type='1' and status='0' order by create_time desc");
    }

    public List<Record> supplyChainWarehouses2(String province, String city){
        SqlBuilder builder = new SqlBuilder();
        builder.line("select * from crm_supply_warehouse where type='1' and status=?","0");
        if (StringUtil.isNotBlank(province)) {
            builder.line(" and province=?",province);
        }
        if (StringUtil.isNotBlank(city)) {
            builder.line(" and city=?",city);
        }
        builder.line("order by create_time desc");
        return Db.find(builder.build(),builder.params());
    }

    public List<Record> findWarehouseByAscriptionId(String ascriptionId){
        return Db.find("select *,CONCAT(`province`,`city`,`area`,`address`) AS warehouseAddress  from crm_supply_warehouse where status='0' and ascription_id=? order by create_time desc", ascriptionId);
    }

    //创建代理商时--直接创建一个代理商
    @Transactional(rollbackFor = Exception.class)
    public void addTraderWarehouseMr(TraderApply trader){
        CrmSupplyWarehouse warehouse;
        Date date=new Date();

        //判断是否有在使用的仓库
        warehouse=new CrmSupplyWarehouse();
        warehouse.setType("2");
        warehouse.setNumber(CrmUtils.no());
        warehouse.setCreateTime(date);
        warehouse.setCreator("默认");
        warehouse.setAscriptionId(trader.getTraderId());
        warehouse.setAscriptionName(trader.getName());

        warehouse.setName(trader.getName()+"仓库");
        warehouse.setPersonInCharge(trader.getWarehouseTake());
        warehouse.setMobile(trader.getWarehouseTakeMobile());
        warehouse.setProvince(trader.getTakeDeliveryProvince());
        warehouse.setCity(trader.getTakeDeliveryCity());
        warehouse.setArea(trader.getTakeDeliveryArea());
        warehouse.setAddress(trader.getTakeDeliveryAddress());
        warehouse.setImgs("");
        warehouse.setQualificationsImgs("");
        warehouse.setEvidence("");
        warehouse.setAttribute("1");
        warehouse.setRemarks("代理商新建时创建的仓库");

        crmSupplyWarehouseDao.save(warehouse);

    }
}
