package com.github.wxiaoqi.security.admin.biz;

import com.github.wxiaoqi.security.admin.dto.AppUserPositionTempDTO;
import com.github.wxiaoqi.security.admin.dto.AppUserPositionTempFindDTO;
import com.github.wxiaoqi.security.admin.entity.AppUserLogin;
import com.github.wxiaoqi.security.admin.entity.AppUserPosition;
import com.github.wxiaoqi.security.admin.entity.AppUserPositionTemp;
import com.github.wxiaoqi.security.admin.mapper.AppUserPositionTempMapper;
import com.github.wxiaoqi.security.admin.vo.AppUserPositionTempVo;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 用户身份职位表
 *
 * @author libin
 * @email 18178966185@163.com
 * @date 2019-07-09 10:00:42
 */
@Transactional
@DependsOn("appUserPositionBiz")
@Service
public class AppUserPositionTempBiz extends BaseBiz<AppUserPositionTempMapper, AppUserPositionTemp> implements InitializingBean {

    @Autowired
    private AppUserDetailBiz detailBiz;

    @Autowired
    private AppUserLoginBiz loginBiz;

    @Autowired
    private AppUserPositionBiz appUserPositionBiz;

    private Map<Integer, String> postionIdAndNameMap;


    public ObjectRestResponse add(AppUserPositionTempDTO appUserPositionTempDTO) {
        if (appUserPositionTempDTO == null || StringUtils.isBlank(appUserPositionTempDTO.getPhone()) || StringUtils.isBlank(appUserPositionTempDTO.getName())
                || appUserPositionTempDTO.getPositionId() == null || appUserPositionTempDTO.getPositionId() == 0) {
            return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, "参数不能为空");
        }
        String phone = appUserPositionTempDTO.getPhone();
        Integer id = appUserPositionTempDTO.getId() == null ? 0 : appUserPositionTempDTO.getId();
        Example example = new Example(AppUserPositionTemp.class);
        example.createCriteria().andEqualTo("phone", phone).andNotEqualTo("id", id).andEqualTo("isDel", 0);
        List<AppUserPositionTemp> list = selectByExample(example);
        if (list.size() > 0) {
            return ObjectRestResponse.createFailedResult(ResultCode.EXIST_CODE, "手机号码已存在");
        }
        Integer userId = 0;
        AppUserLogin userLogin = loginBiz.checkeUserLogin(phone);
        if (userLogin != null) {
            userId = userLogin.getId();
        }
        AppUserPositionTemp userPositionTemp = new AppUserPositionTemp();
        BeanUtils.copyProperties(appUserPositionTempDTO, userPositionTemp);
        userPositionTemp.setUserId(userId);
        //编辑
        if (id == null || id == 0) {
            insertSelective(userPositionTemp);
        } else {
            updateSelectiveById(userPositionTemp);
        }
        if (userId!=0){
            detailBiz.updateUserPositionByUserId(userId,appUserPositionTempDTO.getPositionId());
        }
        return ObjectRestResponse.succ();
    }

    public void updateAppuserPostionStatusById(Integer id, int status) {
        AppUserPositionTemp appUserPositionTemp = new AppUserPositionTemp();
        appUserPositionTemp.setId(id);
        appUserPositionTemp.setIsDel(status);
        mapper.updateByPrimaryKeySelective(appUserPositionTemp);
    }

    public PageDataVO<AppUserPositionTempVo> findWithPage(AppUserPositionTempFindDTO appUserPositionTempFindDTO) {
        PageDataVO<AppUserPositionTempVo> dataVO = new PageDataVO<>();
        Example example = new Example(AppUserPositionTemp.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDel", 0);
        if (StringUtils.isNotEmpty(appUserPositionTempFindDTO.getName())) {
            criteria.andLike("name", String.format("%%%s%%", appUserPositionTempFindDTO.getName().trim()));
        }
        if (StringUtils.isNotEmpty(appUserPositionTempFindDTO.getPhone())) {
            criteria.andEqualTo("phone", appUserPositionTempFindDTO.getPhone());
        }
        if(Objects.nonNull(appUserPositionTempFindDTO.getStatus())) {
            if (DataStatus.USERED.code == appUserPositionTempFindDTO.getStatus()) {
                criteria.andIsNotNull("userId");
            }
            if (DataStatus.NO_USERED.code == appUserPositionTempFindDTO.getStatus()) {
                criteria.andIsNull("userId");
            }
        }
        PageDataVO<AppUserPositionTemp> pageDataVO = PageDataVO.pageInfo(appUserPositionTempFindDTO.getPage(), appUserPositionTempFindDTO.getLimit(), () -> mapper.selectByExample(example));
        List<AppUserPositionTemp> data = pageDataVO.getData();
        if (CollectionUtils.isEmpty(data)) {
            dataVO.setData(Collections.EMPTY_LIST);
            dataVO.setPageNum(appUserPositionTempFindDTO.getPage());
            dataVO.setPageSize(appUserPositionTempFindDTO.getLimit());
            return dataVO;
        }

        List<Integer> postionIds = data.stream().map(AppUserPositionTemp::getPositionId).collect(Collectors.toList());
        Map<Integer, AppUserPosition> postionMap = appUserPositionBiz.findPostionIdAndPostionMapByIds(postionIds);

        List<AppUserPositionTempVo> appUserPositionTempVos = new ArrayList<>();
        AppUserPositionTempVo appUserPositionTempVo;
        for (AppUserPositionTemp appUserPositionTemp : data) {
            appUserPositionTempVo = new AppUserPositionTempVo();
            BeanUtils.copyProperties(appUserPositionTemp, appUserPositionTempVo);
            String postionName = postionMap == null ? "" : postionMap.get(appUserPositionTemp.getPositionId())==null?"":postionMap.get(appUserPositionTemp.getPositionId()).getName();
            appUserPositionTempVo.setPositionName(postionName);
            appUserPositionTempVo.setStatus(appUserPositionTemp.getUserId() == null ? DataStatus.NO_USERED.code : DataStatus.USERED.code);
            appUserPositionTempVos.add(appUserPositionTempVo);
        }

        dataVO.setData(appUserPositionTempVos);
        dataVO.setPageSize(pageDataVO.getPageSize());
        dataVO.setPageNum(pageDataVO.getPageNum());
        dataVO.setTotalCount(pageDataVO.getTotalCount());
        dataVO.setTotalPage(pageDataVO.getTotalPage());
        return dataVO;
    }

    public Map<String,Object> importUserPostion(List<String[]> userPostionData) {
        Map<String,Object> result = new HashMap<>(2);
        List<Map<String, Object>> errorResult = Lists.newArrayList();
        Map<String, Object> errorResultMap;

        Set<Map.Entry<Integer, String>> entrySet = postionIdAndNameMap.entrySet();
        AppUserPositionTemp appUserPositionTemp;
        for (int i = 0; i < userPostionData.size(); i++) {
            String[] data = userPostionData.get(i);
            Integer postionId = null;
            String name="";
            String phone="";
            String postionName="";
            try {
                 name = data[0];
                 phone = data[1];
                if (StringUtils.isEmpty(phone)){
                    throw new BaseException("手机号为空");
                }
                 postionName = data[2];
                if (StringUtils.isEmpty(postionName)){
                    throw new BaseException("身份为空");
                }
                //根据手机号查询userId
                AppUserLogin userLogin = loginBiz.checkeUserLogin(phone);
                for (Map.Entry<Integer, String> integerStringEntry : entrySet) {
                    if (integerStringEntry.getValue().contains(postionName)) {
                        postionId = integerStringEntry.getKey();
                        break;
                    }
                }
                appUserPositionTemp = new AppUserPositionTemp();
                appUserPositionTemp.setCrtTime(Instant.now().toEpochMilli());
                appUserPositionTemp.setName(name);
                appUserPositionTemp.setPositionId(postionId);
                appUserPositionTemp.setPhone(phone);
                appUserPositionTemp.setUserId(0);
                if (Objects.nonNull(userLogin)) {
                    //更新用户身份信息
                    detailBiz.updateUserPositionByUserId(userLogin.getId(), postionId);
                    appUserPositionTemp.setUserId(userLogin.getId());
                }
                mapper.insertWithIgnoreRepeat(appUserPositionTemp);
            } catch (BaseException ex) {
                errorResultMap = new HashMap<>(1);
                errorResultMap.put("num", i);
                errorResultMap.put("msg",ex.getMessage());
                errorResult.add(errorResultMap);
            }catch (ArrayIndexOutOfBoundsException ex){
                errorResultMap = new HashMap<>(1);
                errorResultMap.put("num", i);
                String msg= "";
                if(StringUtils.isEmpty(phone)){
                    msg+="手机号码缺失";
                }
                if (StringUtils.isEmpty(postionName)){
                    msg+=",身份信息缺失";
                }
                errorResultMap.put("msg",msg);
                errorResult.add(errorResultMap);
            } catch (Exception ex){
                errorResultMap = new HashMap<>(1);
                errorResultMap.put("num", i);
                errorResultMap.put("msg","数据"+Arrays.toString(data)+"保存失败");
                errorResult.add(errorResultMap);
            }
        }
         result.put("success",userPostionData.size()-errorResult.size());
         result.put("error",errorResult.size());
         result.put("data",errorResult);
        return result;
    }

    private enum DataStatus {
        USERED(1), NO_USERED(0);
        private int code;

        DataStatus(int code) {
            this.code = code;
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        postionIdAndNameMap = appUserPositionBiz.findPostionIdAndNameMap() == null ? Collections.EMPTY_MAP : appUserPositionBiz.findPostionIdAndNameMap();
    }

}
