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.SupplySupplierApply;
import com.sifang.modules.kingdee.service.SupplierService;
import com.sifang.modules.kingdee.vo.KingDeeResponseVo;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sunshine.SystemSetting.dao.SiteInformationDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
import com.sifang.modules.sunshine.SystemSetting.form.AddTrader;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.RandomUtil;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.setting.dao.CrmSupplySupplierDao;
import com.sifang.modules.supply.setting.entity.CrmSupplySupplier;
import com.sifang.modules.supply.setting.form.AddSupplierVo;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.dao.UserDao;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class CrmSupplySupplierService extends BaseService {

    @Autowired
    CrmSupplySupplierDao supplySupplierDao;

    @Autowired
    private SiteInformationDao siteInformationDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private SupplierService supplierService;

    public void supplierList(LayuiPage<Record> page, Map<String, String> map){
        List<Record> recordList = supplySupplierDao.getList(page, map);
        Long count = supplySupplierDao.listCount(map);
        page.setData(recordList);
        page.setCount(count);
    }

    @Transactional(rollbackFor = Exception.class)
    public void addEditSupplier(AddSupplierVo supplierVo) {
        if (StringUtil.isBlank(supplierVo.getId())){
            addSupplier(supplierVo);
        } else {
            editSupplier(supplierVo);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void addSupplier(AddSupplierVo supplierVo) {
        if (siteInformationDao.getExistsLoginName(supplierVo.getLoginName())) {
            throw new BusinessException("登录账号已存在！");
        }

        if (checkSupplierName(supplierVo.getName(), "")) {
            throw new BusinessException("供应商名称已存在！");
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public String addSupplierByApply(SupplySupplierApply apply) throws Exception {
        CrmSupplySupplier supplySupplier;
        if(StringUtil.isNotBlank(apply.getSupplierId())){
            supplySupplier = supplySupplierDao.get(apply.getSupplierId());
        }else{
            if (siteInformationDao.getExistsLoginName(apply.getLoginName())) {
                throw new BusinessException("登录账号已存在！");
            }
            supplySupplier = new CrmSupplySupplier();
            User user = createNewUser(apply);
            userDao.save(user);
            supplySupplier.setUserId(user.getId());
            supplySupplier.setStatus(UserConstants.USER_STATUS_NORMAL);
            supplySupplier.setCreateBy(apply.getCreator());
            supplySupplier.setCreator(apply.getCreator());
            supplySupplier.setCreateTime(new Date());
            supplySupplier.setDepartmentId(apply.getDepartmentId());
            supplySupplier.setDepartmentName(apply.getDepartmentName());
        }
        setCommonField(apply, supplySupplier);
           if(StringUtil.isNotBlank(apply.getSupplierId()) && StringUtil.isNotBlank(supplySupplier.getKingDeeId())){   //修改
             //  supplierService.updateSupplierToKingDee(supplySupplier);
           }else{    //新增

          //  KingDeeResponseVo responseVo= supplierService.saveSupplierToKingDee(supplySupplier);
          //  String kingDeeId=responseVo.getId();
          //  String number=responseVo.getNumber();
         //   supplySupplier.setKingDeeId(kingDeeId);
          //  supplySupplier.setKingDeeNumber(number);
           }

        supplySupplierDao.save(supplySupplier);
        return supplySupplier.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    public void editSupplier(AddSupplierVo supplierVo) {
        CrmSupplySupplier supplySupplier = supplySupplierDao.get(supplierVo.getId());
        if(supplySupplier==null){
            throw new BusinessException("供应商不存在！");
        }
        User user = userDao.get(supplySupplier.getUserId());
        if(user==null){
            throw new BusinessException("内部错误，用户不存在！");
        }
        if (siteInformationDao.getExistsLoginNameNew(user.getId(), supplierVo.getLoginName())) {
            throw new BusinessException("登录账号已存在！");
        }
        if (checkSupplierName(supplierVo.getName(), supplierVo.getId())) {
            throw new BusinessException("供应商名称已存在！");
        }
        user.setMobile(supplierVo.getMobile());
        user.setLoginName(supplierVo.getLoginName());
        if (!supplierVo.getPassword().equals("default") && !user.getPassword().equals(supplierVo.getPassword())) {
            user.setPassword(RandomUtil.entryptPassword(supplierVo.getPassword()));
        }
      //  userDao.save(user);
       // setCommonField(supplierVo,supplySupplier);

       // supplySupplierDao.save(supplySupplier);
    }

    private User createNewUser(SupplySupplierApply req) {
        User user = new User();
        user.setCreateBy(req.getCreateBy());
        user.setStatus("0");
        user.setUserType("8");
        user.setCreateType(1);
        user.setMobile(req.getMobile());
        user.setCreateDate(new Date());
        user.setLoginName(req.getLoginName());
        user.setPassword(RandomUtil.entryptPassword(req.getPassword()));
        return user;
    }

    public void setCommonField(SupplySupplierApply req, CrmSupplySupplier supplySupplier) {
        supplySupplier.setName(req.getName());
        supplySupplier.setMobile(req.getMobile());

        supplySupplier.setProvince(req.getProvince());
        supplySupplier.setCity(req.getCity());
        supplySupplier.setArea(req.getArea());
        supplySupplier.setAddress(req.getAddress());
        supplySupplier.setContacts(req.getContacts());
        supplySupplier.setActualContacts(req.getActualContacts());
        supplySupplier.setTelephone(req.getTelephone());
        supplySupplier.setActualIdCode(req.getActualIdCode());
        supplySupplier.setBankName(req.getBankName());
        supplySupplier.setBankCode(req.getBankCode());
        supplySupplier.setTaxNumber(req.getTaxNumber());
        supplySupplier.setCertificationImg(req.getCertificationImg());
        supplySupplier.setLicenseImg(req.getLicenseImg());
        supplySupplier.setIdFrontImg(req.getIdFrontImg());
        supplySupplier.setIdOppositeImg(req.getIdOppositeImg());
        supplySupplier.setRemarks(req.getRemarks());
        supplySupplier.setMaterialTypeId(req.getMaterialTypeId());
        supplySupplier.setMaterialBrandId(req.getMaterialBrandId());

    }

    public Boolean checkSupplierNumber(String number, String id) {
        StringBuffer sb = new StringBuffer();
        sb.append(" SELECT COUNT(s.id) FROM `crm_supply_supplier` s WHERE s.status='0' AND s.number=? ");
        if (StringUtil.isNotBlank(id)) {
            sb.append(" AND s.id<>'" + id + "'");
        }
        long count = Db.queryLong(sb.toString(), number);
        return count > 0 ? true : false;
    }

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

    public CrmSupplySupplier getById(String id){
        return supplySupplierDao.get(id);
    }

    public List<Record> supervisionList(String id){
        String roleId=Db.queryStr(" SELECT id FROM `crm_platform_employee_role` WHERE TYPE='4' AND STATUS='0' ");
        StringBuffer sb=new StringBuffer();
        sb.append(" SELECT  e.id,e.name FROM `crm_platform_employee` e WHERE e.status='0' and  e.id IN(SELECT employee_id FROM `crm_platform_employee_role_rel` r WHERE INSTR(r.role_ids,?))  ");
       // sb.append(" AND e.id NOT IN( SELECT supervision_id FROM `crm_supply_supplier` s  WHERE s.status='1' AND s.binding_flag='1' ");
      /*  if(StringUtil.isNotBlank(id)){
            sb.append("  AND s.id<>'"+ id +"' ");
        }*/
       // sb.append("  ) ");
        return Db.find(sb.toString(),roleId);
    }

    public void bindSupervision(String id,String supervision,String supervisionId){
      /*  String sql=" SELECT COUNT(s.id) FROM `crm_supply_supplier` s WHERE s.status='1' AND s.supervision_id=? AND s.id<>? ";
        long count=Db.queryLong(sql,supervisionId,id);
        if(count>0){
           throw new BusinessException("该监管人员已绑定供应商！");
        }*/
        CrmSupplySupplier supplySupplier=supplySupplierDao.get(id);
   /*     supplySupplier.setSupervision(supervision);
        supplySupplier.setBindingFlag("1");
        supplySupplier.setSupervisionId(supervisionId);*/

        supplySupplierDao.save(supplySupplier);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteSupplier(String ids){
        for (String id : ids.split(",")) {
            CrmSupplySupplier supplySupplier = getById(id);
            supplySupplier.setStatus("2");

            supplySupplierDao.save(supplySupplier);
            if (supplySupplier.getUserId() != null) {
                User user = userDao.getById(supplySupplier.getUserId());
                user.setStatus("1");
                user.setUpdateTime(new Date());
                userDao.save(user);
            }
        }
    }

    public void unBindSupervision(String id){
        CrmSupplySupplier supplySupplier=supplySupplierDao.get(id);
 /*       supplySupplier.setSupervisionId("");
        supplySupplier.setSupervision("");
        supplySupplier.setBindingFlag("0");*/

        supplySupplierDao.save(supplySupplier);
    }
}
