package com.ssm.manage.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.AESUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.core.utils.StoreParaUtils;
import com.ssm.manage.dao.SsmBaseStaffDao;
import com.ssm.manage.dao.SsmStoreConversionDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.query.StaffRequest;
import com.ssm.manage.query.StoreConversionQuery;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.response.StaffResponse;
import com.ssm.manage.response.UserResponse;
import com.ssm.manage.service.SsmBaseStaffService;
import com.ssm.manage.service.SsmBaseStoreService;
import com.ssm.manage.service.SsmStoreConversionService;
import com.ssm.manage.service.SsmStoreManagementService;
import com.ssm.manage.utils.Constant;
import com.ssm.util.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SsmStoreConversionServiceImpl extends BaseServiceImpl<StoreConversion> implements SsmStoreConversionService {


    private static String staffKey = "staffKey";
    private static  String key = "staffList";
    @Autowired
    private SsmStoreConversionDao dao;

    @Autowired
    private SsmBaseStaffDao ssmBaseStaffDao;
    @Autowired
    private RedisClient<List<BaseStaff>> redisClient1;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmBaseStaffService ssmBaseStaffService;

    @Autowired
    private RedisClient<StaffResponse> redisClient;

    @Override
    public SsmStoreConversionDao getDao() {
        return dao;
    }

    @Override
    public PageInfo<StoreConversionQuery> selectPage(StoreConversionQuery storeConversionQuery) {
        Example example = new Example(StoreConversion.class);
        Example.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(String.valueOf(storeConversionQuery.getStoreId())) && null != storeConversionQuery.getStoreId()) {
            criteria.andLike("storeId", "%" + storeConversionQuery.getStoreId() + "%");
        }
        if (StringUtils.isNotBlank(storeConversionQuery.getStoreNum()) && null != storeConversionQuery.getStoreNum()) {
            criteria.andLike("storeNum", "%" + storeConversionQuery.getStoreNum() + "%");
        }
        if (StringUtils.isNotBlank(storeConversionQuery.getStoreName()) && null != storeConversionQuery.getStoreName()) {
            criteria.andLike("storeName", "%" + storeConversionQuery.getStoreName() + "%");
        }
        if (StringUtils.isNotBlank(String.valueOf(storeConversionQuery.getStoresId())) && null != storeConversionQuery.getStoresId()) {
            criteria.andLike("storesId", "%" + storeConversionQuery.getStoresId() + "%");
        }
        if (StringUtils.isNotBlank(storeConversionQuery.getStoresNum()) && null != storeConversionQuery.getStoresNum()) {
            criteria.andLike("storesNum", "%" + storeConversionQuery.getStoresNum() + "%");
        }
        if (StringUtils.isNotBlank(storeConversionQuery.getStoresName()) && null != storeConversionQuery.getStoresName()) {
            criteria.andLike("storesName", "%" + storeConversionQuery.getStoresName() + "%");
        }
        if (StringUtils.isNotBlank(String.valueOf(storeConversionQuery.getStatu())) && null != storeConversionQuery.getStatu()) {
            criteria.andEqualTo("statu", "%" + storeConversionQuery.getStatu() + "%");
        }
        if (StringUtils.isNotBlank(String.valueOf(storeConversionQuery.getStaffId())) && null != storeConversionQuery.getStaffId()) {
            criteria.andLike("staffId", "%" + storeConversionQuery.getStaffId() + "%");
        }
        if (StringUtils.isNotBlank(storeConversionQuery.getStaffName()) && null != storeConversionQuery.getStaffName()) {
            criteria.andLike("staffName", "%" + storeConversionQuery.getStaffName() + "%");
        }
        if (StringUtils.isNotBlank(storeConversionQuery.getBrandNumber()) && null != storeConversionQuery.getBrandNumber()) {
            criteria.andLike("brandNumber", "%" + storeConversionQuery.getBrandNumber() + "%");
        }
        if (StringUtils.isNotBlank(storeConversionQuery.getStaffNum()) && null != storeConversionQuery.getStaffNum()) {
            criteria.andLike("staffNum", "%" + storeConversionQuery.getStaffNum() + "%");
        }

        storeConversionQuery.setSort("proposerDate");
        List<StoreConversion> list1 = selectByExample(example);
        PageHelper.startPage(storeConversionQuery.getPageNum(), storeConversionQuery.getPageSize(), storeConversionQuery.getOrderAndSort());
        List<StoreConversion> list = selectByExample(example);
        List<StoreConversionQuery> lists = new ArrayList<>();
        for (StoreConversion storeConversion : list) {
            StoreConversionQuery storeConversionQuery1 = new StoreConversionQuery();
            StaffRequest baseStaff = new StaffRequest();
            baseStaff.setId(storeConversion.getStaffId());
            BaseStaff baseStaff1 = ssmBaseStaffService.selectOne(baseStaff);
            if(baseStaff1!=null) {
                BeanUtils.copyProperties(baseStaff1, storeConversionQuery1);
                BeanUtils.copyProperties(storeConversion, storeConversionQuery1);
                storeConversionQuery1.setId(storeConversion.getId());
                lists.add(storeConversionQuery1);
            }
        }
        PageInfo<StoreConversionQuery> pageInfo = new PageInfo<>(lists);
        pageInfo.setTotal(list1.size());
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int add(List<StoreConversion> storeConversion, String phone, long storeId) {
        StaffResponse staffResponse = new StaffResponse();
        Set<String> keys = redisClient.keys(getStaffKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0) {
            String key = new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
        }
        int i = 0;
        for (StoreConversion conversion : storeConversion) {
            conversion.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            Date d = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateNowStr = sdf.format(d);
            String num = this.getNum(dateNowStr, storeId);
            conversion.setOrderCode(num);
            conversion.setProposerName(staffResponse.getStaffName());
            conversion.setProposerId(staffResponse.getId());
            conversion.setProposerDate(new Date());
            conversion.setStatu(0);
            int insert = dao.insert(conversion);
            i += insert;
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(StoreConversion storeConversion, String phone) {

        StaffResponse staffResponse = new StaffResponse();
        Set<String> keys = redisClient.keys(getStaffKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0) {
            String key = new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
        }
        storeConversion.setUpdateId(staffResponse.getId());
        storeConversion.setUpdateName(staffResponse.getStaffName());
        storeConversion.setUpdateDate(new Date());
        int i = dao.updateByPrimaryKey(storeConversion);
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateStatu(StoreConversionQuery storeConversion, String phone)throws SmsException {

        StaffResponse staffResponse = new StaffResponse();
        Set<String> keys = redisClient.keys(getStaffKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0) {
            String key = new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
        }

        Example example = new Example(StoreConversion.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", storeConversion.getIds());
        List<StoreConversion> list = dao.selectByExample(example);
        int i = 0;
        if (list.size() == 1) {
            StoreConversion conversion = list.get(0);
            conversion.setUpdateId(staffResponse.getId());
            conversion.setUpdateName(staffResponse.getStaffName());
            conversion.setUpdateDate(new Date());
            conversion.setBrandNumber(storeConversion.getBrandNumber());
            conversion.setStatu(storeConversion.getStatu());
            int update = dao.updateByPrimaryKey(conversion);
            if (update == 0) {
                throw new SmsException(ResponseCode.MSG,"审核失败");
            } else {
                if (storeConversion.getStatu() == 2) {

                    /*StaffRequest baseStaff = new StaffRequest();
                    baseStaff.setId(conversion.getStaffId());
                    BaseStaff baseStaff1 = ssmBaseStaffService.selectOne(baseStaff);*/
                    BaseStaff baseStaff1 = ssmBaseStaffService.selectByPrimaryKey(conversion.getStaffId());

                    //判断转进的门店，水牌号是否存在
                    StaffRequest staffRequest1 = new StaffRequest();
                    staffRequest1.setStoreId(conversion.getStoreId());
                    staffRequest1.setBrandNumber(storeConversion.getBrandNumber());
                    //转进门店的水牌信息
                    List<BaseStaff> baseStaffs = ssmBaseStaffDao.selectList(staffRequest1);
                    for (BaseStaff staff : baseStaffs) {
                        if (staff.getState() == 1 || staff.getState() == 2) {
                            throw new SmsException(ResponseCode.MSG,"水牌号存在，审核失败");
                        }
                    }
                    StaffRequest staffRequest = new StaffRequest();
                    staffRequest.setId(baseStaff1.getId());
                    staffRequest.setStoreId(conversion.getStoreId());
                    staffRequest.setStoreName(conversion.getStoreName());
                    staffRequest.setBrandNumber(storeConversion.getBrandNumber());
                    staffRequest.setStoreCodeBefore(conversion.getStoresId());
                    staffRequest.setStoreNameBefore(conversion.getStoresName());
                    int i1 = ssmBaseStaffService.updateStaffStore(staffRequest);
                    if (i1 == 0) {
                        throw new SmsException(ResponseCode.MSG,"审核失败");
                    }
                    i = i1;
                    if(i>0){
                        BaseStaff staff = new BaseStaff();
                        staff.setState(1);
                        staff.setStoreId(staffRequest.getStoreId());
                        if(null != staffRequest.getType()){
                            staff.setType(staffRequest.getType());
                        }
                        List<BaseStaff> list11 = ssmBaseStaffDao.select(staff);
//                        redisClient.delete(getKey(staffRequest.getStoreId(), key));
                        redisClient1.set(getKey(staffRequest.getStoreId(),key),list11,RedisClient.EXPIRE_TIME_ONE_DAY);
                    }
                }
            }
        }

        //int i =0;

        return i;
    }
    @Override
    public List<StoreConversionQuery> queryPage(StoreConversionQuery storeConversionQuery) {

        List<StoreConversion> storeConversions = dao.selectByIds(storeConversionQuery.getIds());
        List<StoreConversionQuery> lists = new ArrayList<>();
        for (StoreConversion storeConversion : storeConversions) {
            StoreConversionQuery conversionQuery = new StoreConversionQuery();
            BeanUtils.copyProperties(storeConversion, conversionQuery);
            lists.add(conversionQuery);
        }
        return lists;

        /*List<StoreConversion> conversionQueries = dao.selectByIds(storeConversionQuery.getIds());
        PageHelper.startPage(storeConversionQuery.getPageNum(),storeConversionQuery.getPageSize());
        List<StoreConversionQuery> lists = new ArrayList<>();
        for (StoreConversion storeConversion : conversionQueries) {
            StoreConversionQuery storeConversionQuery1 = new StoreConversionQuery();
            BeanUtils.copyProperties(storeConversion,storeConversionQuery1);
            lists.add(storeConversionQuery1);
        }
        PageInfo<StoreConversionQuery> pageInfo = new PageInfo<>(lists);
        return lists;*/
    }

    @Override
    public List<StoreConversionQuery> check(List<StoreConversion> queries) {


        /*for (StoreConversion conversion : queries) {
            int i = dao.updateByPrimaryKey(conversion);
            if (i < 0){
                throw new RuntimeException("检测失败");
            }
        }*/
        /*List<Long> ids = queries.stream().map(StoreConversion::getId).collect(Collectors.toList());
        List<StoreConversion> storeConversions = dao.selectByIds(ids);
        List<StoreConversionQuery> queryList = new ArrayList<>();*/
        List<StoreConversionQuery> queryList = new ArrayList<>();
        for (StoreConversion query : queries) {
            StoreConversion conversion = dao.selectByPrimaryKey(query.getId());
            StoreConversionQuery storeConversionQuery = new StoreConversionQuery();
            BeanUtils.copyProperties(conversion, storeConversionQuery);
            storeConversionQuery.setTag(0);
            StaffRequest staffRequest = new StaffRequest();
            String brandNumber = query.getBrandNumber();
            Long storeId = conversion.getStoreId();
            staffRequest.setStoreId(storeId);
            staffRequest.setBrandNumber(brandNumber);
            List<BaseStaff> baseStaffs = ssmBaseStaffDao.selectList(staffRequest);
            List<BaseStaff> collect = baseStaffs.stream().filter(s -> s.getState() == 1).collect(Collectors.toList());
            if (collect.size() > 0) {
                //有重复水牌号的
                storeConversionQuery.setTag(1);
            }
            //返回新输入的水牌号信息
            storeConversionQuery.setBrandNumber(brandNumber);
            queryList.add(storeConversionQuery);
        }
        return queryList;
    }

    @Override
    public List<StoreConversionQuery> update(List<StoreConversion> storeConversions, String phone) {

        //先检测水牌号是否有重复
        List<StoreConversionQuery> check = check(storeConversions);
        List<StoreConversionQuery> list = check.stream().filter(s -> s.getTag() == 1).collect(Collectors.toList());
        if (list.size() > 0) {
            return check;
        }

        StaffResponse staffResponse = new StaffResponse();
        Set<String> keys = redisClient.keys(getStaffKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0) {
            String key = new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
        }
        /*Example example = new Example(StoreConversion.class);
        Example.Criteria criteria = example.createCriteria();
        List<Long> ids = storeConversions.stream().map(StoreConversion::getId).collect(Collectors.toList());
        criteria.andIn("id",ids);
        List<StoreConversion> list = dao.selectByExample(example);*/

        for (StoreConversion conversion : storeConversions) {
            StoreConversion conversion1 = dao.selectByPrimaryKey(conversion.getId());
            conversion1.setUpdateId(staffResponse.getId());
            conversion1.setUpdateName(staffResponse.getStaffName());
            conversion1.setUpdateDate(new Date());
            conversion1.setBrandNumber(conversion.getBrandNumber());
            conversion1.setStatu(2);
            int update = dao.updateByPrimaryKey(conversion1);
            if (update == 0) {
                throw new RuntimeException("审核失败");
            } else {
                StaffRequest baseStaff = new StaffRequest();
                baseStaff.setId(conversion1.getStaffId());
                BaseStaff baseStaff1 = ssmBaseStaffService.selectOne(baseStaff);
                StaffRequest staffRequest = new StaffRequest();
                staffRequest.setId(baseStaff1.getId());
                staffRequest.setStoreId(conversion1.getStoreId());
                staffRequest.setStoreName(conversion1.getStoreName());
                staffRequest.setBrandNumber(conversion.getBrandNumber());
                staffRequest.setStoreCodeBefore(conversion1.getStoresId());
                staffRequest.setStoreNameBefore(conversion1.getStoresName());
                int i1 = ssmBaseStaffService.updateStaffStore(staffRequest);
                if (i1 == 0) {
                    throw new RuntimeException("审核失败");
                }
            }
        }
        return null;
    }


    public String getNum(String date, Long storeId) {
        Example example = new Example(StoreConversion.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLike("orderCode", "%" + date + "%");
        criteria.andEqualTo("storeId", storeId);
        List<StoreConversion> list = dao.selectByExample(example);
        String num = null;
        if (null != list) {
            if (list.size() > 0) {
                if (list.size() > 999) {
                    num = date + (list.size() + 1);
                } else if (list.size() > 99) {
                    num = date + "0" + (list.size() + 1);
                } else if (list.size() > 9) {
                    num = date + "00" + (list.size() + 1);
                } else {
                    num = date + "000" + (list.size() + 1);
                }
            } else {
                num = date + "0001";
            }
        } else {
            num = date + "0001";
        }
        return num.replace("-", "");
    }

    public String getStaffKey(String phone) {
        return staffKey + phone;
    }

    public String getKey(Long storeId, String key) {
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(storeId);
        key = baseStore.getStoreNum() + key;
        return key;
    }
}
