package com.hfkj.service.impl;

import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.channel.weixin.utils.MD5Util;
import com.hfkj.common.utils.IDGenerator;
import com.hfkj.dao.BsStoreMapper;
import com.hfkj.entity.*;
import com.hfkj.model.MerBasisModel;
import com.hfkj.model.OpenStoreModel;
import com.hfkj.model.StoreModel;
import com.hfkj.service.*;
import com.hfkj.sysenum.SecUserRoleIdEnum;
import com.hfkj.sysenum.SecUserTypeEnum;
import com.hfkj.sysenum.StoreCreateTypeEnum;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service("storeService")
public class BsStoreServiceImpl implements BsStoreService {

    @Resource
    private BsStoreMapper storeMapper;

    @Resource
    private BsMerContractService merContractService;

    @Resource
    private BsStoreIndustryService storeIndustryService;

    @Resource
    private BsStoreSettleAcctService storeSettleAcctService;

    @Resource
    private BsStoreRegionService storeRegionService;

    @Resource
    private SecUserService userService;

    @Override
    @Transactional(propagation= Propagation.REQUIRED,rollbackFor= {RuntimeException.class})
    public void configStore(StoreModel store) throws Exception {
        editStore(store);

        SecUser secUser = userService.findByLoginName(String.valueOf(store.getStoreNo()));
        if (secUser != null && !secUser.getObjectId().equals(store.getId())) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "账户已存在，请更换");
        }

        // 查询门店主账号
        SecUser user = userService.getMainAccount(SecUserTypeEnum.type5.getNumber(), store.getId());
        if (user == null) {
            user = new SecUser();
            user.setUserName(store.getName());
            user.setTelephone(store.getTelephone());
            user.setLoginName(store.getStoreNo().toString());
            user.setPassword(MD5Util.MD5Encode("123456", "utf-8").toUpperCase());
            user.setAdminFlag(1);
            user.setRoleId(SecUserRoleIdEnum.roleId6.getRoleId());
            user.setObjectType(SecUserTypeEnum.type5.getNumber());
            user.setObjectId(store.getId());
            user.setStatus(1);
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            userService.addUser(user);
        } else {
            user.setUserName(store.getName());
            user.setTelephone(store.getTelephone());
            user.setUpdateTime(new Date());
            userService.updateUser(user);
        }

        // 行业
        BsStoreIndustry industry = storeIndustryService.getIndustryByStoreId(store.getId());
        if (industry != null) {
            store.getStoreIndustry().setId(industry.getId());
            store.getStoreIndustry().setStatus(industry.getStatus());
            store.getStoreIndustry().setCreateTime(industry.getCreateTime());
        }
        store.getStoreIndustry().setStoreId(store.getId());
        storeIndustryService.editStoreIndustry(store.getStoreIndustry());

        // 门店
        BsStoreRegion region = storeRegionService.getRegionByStoreId(store.getId());
        if (region != null) {
            store.getStoreRegion().setId(region.getId());
            store.getStoreRegion().setStatus(region.getStatus());
            store.getStoreRegion().setCreateTime(region.getCreateTime());
        }
        store.getStoreRegion().setStoreId(store.getId());
        storeRegionService.editStoreRegion(store.getStoreRegion());

        if (store.getStoreSettleAcct() != null) {
            // 门店结算
            BsStoreSettleAcct storeSettleAcct = storeSettleAcctService.getDetailByStore(store.getId());
            if (storeSettleAcct != null) {
                store.getStoreSettleAcct().setId(store.getId());
            }
            storeSettleAcctService.editStoreSettle(store.getStoreSettleAcct());
        }

        if (store.getAloneSettle().equals(true)) {
            merContractService.addStoreContract(store.getId());
        }
    }

    @Override
    public void editStore(BsStore store) {
        if (store.getId() == null) {
            store.setCreateTime(new Date());
            store.setUpdateTime(new Date());
            storeMapper.insert(store);

            // 门店号总长度
            Integer storeNoTotalNum = 8;

            // 门店号 101开头 + id
            String storeNo = "101" + store.getId();
            int storeNoNum = storeNo.length();
            store.setStoreNo(Long.parseLong(storeNo + IDGenerator.nextId(storeNoTotalNum - storeNoNum)));
            storeMapper.updateByPrimaryKey(store);
        } else {
            store.setUpdateTime(new Date());
            storeMapper.updateByPrimaryKey(store);
        }
    }

    @Override
    public BsStore getStoreById(Long storeId) {
        return storeMapper.selectByPrimaryKey(storeId);
    }

    @Override
    public BsStore getStoreByStoreNo(Long storeNo) {
        BsStoreExample example = new BsStoreExample();
        example.createCriteria().andStoreNoEqualTo(storeNo);
        List<BsStore> list = storeMapper.selectByExample(example);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public StoreModel getStoreDetail(Long storeId) {
        // 查询门店
        BsStore store = getStoreById(storeId);
        if (store == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到门店");
        }

        StoreModel storeModel = new StoreModel();
        BeanUtils.copyProperties(store, storeModel);

        // 门店账户
        SecUser account = userService.getMainAccount(SecUserTypeEnum.type5.getNumber(), storeId);
        if (account != null) {
            account.setPassword(null);
        }
        storeModel.setAccount(account);
        storeModel.setStoreIndustry(storeIndustryService.getIndustryByStoreId(storeId));
        storeModel.setStoreRegion(storeRegionService.getRegionByStoreId(storeId));
        if (store.getAloneSettle() != null && store.getAloneSettle().equals(true)) {
            storeModel.setStoreSettleAcct(storeSettleAcctService.getDetailByStore(storeId));
        }
        return storeModel;
    }

    @Override
    public List<BsStore> getStoreByMerId(Long merId, StoreCreateTypeEnum typeEnum) {
        BsStoreExample example = new BsStoreExample();
        BsStoreExample.Criteria criteria = example.createCriteria().andStatusNotEqualTo(0).andMerIdEqualTo(merId);

        if (typeEnum != null) {
            criteria.andCreateTypeEqualTo(typeEnum.getNumber());
        }

        return storeMapper.selectByExample(example);
    }

    @Override
    public List<StoreModel> getStoreList(Map<String, Object> param) {
        BsStoreExample example = new BsStoreExample();
        BsStoreExample.Criteria criteria = example.createCriteria().andStatusNotEqualTo(0);

        if (MapUtils.getLong(param, "companyId") != null) {
            criteria.andCompanyIdEqualTo(MapUtils.getLong(param, "companyId"));
        }

        if (MapUtils.getLong(param, "agentId") != null) {
            criteria.andAgentIdEqualTo(MapUtils.getLong(param, "agentId"));
        }

        if (MapUtils.getLong(param, "merId") != null) {
            criteria.andMerIdEqualTo(MapUtils.getLong(param, "merId"));
        }

        if (StringUtils.isNotBlank(MapUtils.getString(param, "name"))) {
            criteria.andNameLike("%" +MapUtils.getString(param, "name")+ "%");
        }

        if (MapUtils.getInteger(param, "status") != null) {
            criteria.andStatusEqualTo(MapUtils.getInteger(param, "status"));
        }

        example.setOrderByClause("create_time desc");
        List<BsStore> bsStoreList = storeMapper.selectByExample(example);

        StoreModel storeModel;
        List<StoreModel> storeModels = new ArrayList<>();
        for (BsStore store : bsStoreList) {
            storeModel = new StoreModel();
            BeanUtils.copyProperties(store, storeModel);
            storeModels.add(storeModel);
        }
        return storeModels;
    }

    @Override
    public List<OpenStoreModel> getStoreList(String name , Long childId) {

        Map<String  , Object> map = new HashMap<>();
        if (name != null) {
            map.put("name" , name);
        }
        if (childId != null) {
            map.put("childId" , childId);
        }

        return storeMapper.getStoreList(map);
    }

    @Override
    public Map<String, Object> countStoreTrade(Map<String, Object> param) {
        return storeMapper.countStoreTrade(param);
    }
}
