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.AppUserJobLevel;
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 com.xxfc.platform.vehicle.entity.BranchCompany;
import com.xxfc.platform.vehicle.feign.VehicleFeign;
import lombok.extern.slf4j.Slf4j;
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
@Slf4j
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;

    @Autowired
    private VehicleFeign vehicleFeign;

    @Autowired
    AppUserJobLevelBiz jobLevelBiz;


    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, "参数不能为空");
        }
        Integer companyId=appUserPositionTempDTO.getCompanyId();
        String companyName=appUserPositionTempDTO.getCompanyName();
       if (!(companyId!=null&&companyId>0&&StringUtils.isNotBlank(companyName)))
           return  ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, "分公司不存在");
        BranchCompany branchCompany=vehicleFeign.companyId(companyName);
        if (branchCompany==null){
            return  ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, "分公司不存在");
        }
        companyId=branchCompany.getId();
        companyName=branchCompany.getName();
        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);
        userPositionTemp.setCompanyId(companyId);
        userPositionTemp.setCompanyName(companyName);
        //编辑
        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.getCompanyId())) {
            criteria.andEqualTo("companyId", appUserPositionTempFindDTO.getCompanyId());
        }
        if(Objects.nonNull(appUserPositionTempFindDTO.getStatus())) {
            if (DataStatus.USERED.code == appUserPositionTempFindDTO.getStatus()) {
                criteria.andNotEqualTo("userId",0);
            }
            if (DataStatus.NO_USERED.code == appUserPositionTempFindDTO.getStatus()) {
                criteria.andEqualTo("userId",0);
            }
        }
        example.setOrderByClause("upd_time desc");
        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<Integer> jobIds = data.stream().map(AppUserPositionTemp::getJobId).collect(Collectors.toList());
        Map<Integer, AppUserJobLevel> jobMap = jobLevelBiz.findJobIdAndJobMapByIds(jobIds);
        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();
            String jobName = jobMap == null ? "" : jobMap.get(appUserPositionTemp.getJobId())==null?"":jobMap.get(appUserPositionTemp.getJobId()).getName();
            appUserPositionTempVo.setPositionName(postionName);
            appUserPositionTempVo.setJobName(jobName);
            appUserPositionTempVo.setStatus(appUserPositionTemp.getUserId() == null ? DataStatus.NO_USERED.code : appUserPositionTemp.getUserId()==0?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("身份为空");
                }
                if (StringUtils.isNotBlank(name)){
                    name.replaceAll(" ","");
                }
                Example example = new Example(AppUserPositionTemp.class);
                example.createCriteria().andEqualTo("phone", phone).andEqualTo("isDel", 0);
                List<AppUserPositionTemp> list = selectByExample(example);
                Integer id=0;
                Integer userId=0;
                if (list.size()>0){
                    AppUserPositionTemp appUserPositionTemp1= list.get(0);
                    id=appUserPositionTemp1.getId();
                    userId=appUserPositionTemp1.getUserId();
                }
                if (userId==null||userId==0){
                    //根据手机号查询userId
                    AppUserLogin userLogin = loginBiz.checkeUserLogin(phone);
                    if (Objects.nonNull(userLogin)) {
                        userId=userLogin.getId();
                    }
                }
                for (Map.Entry<Integer, String> integerStringEntry : entrySet) {
                    if (integerStringEntry.getValue().contains(postionName)) {
                        postionId = integerStringEntry.getKey();
                        break;
                    }
                }
                String companyName=data[3];
                Integer companyId=0;
                if (StringUtils.isNotBlank(companyName)){
                    BranchCompany branchCompany=vehicleFeign.companyId(companyName);
                    if (branchCompany!=null){
                        companyId=branchCompany.getId();
                        companyName=branchCompany.getName();
                    }else {
                        companyName=null;
                    }
                }
                String jobName=data[4];
                Integer jobId=2;
                if (StringUtils.isNotBlank(jobName)&&jobName.contains("销售")){
                    jobId=1;
                }
                appUserPositionTemp = new AppUserPositionTemp();
                appUserPositionTemp.setName(name);
                appUserPositionTemp.setPositionId(postionId);
                appUserPositionTemp.setPhone(phone);
                appUserPositionTemp.setCompanyId(companyId);
                appUserPositionTemp.setCompanyName(companyName);
                appUserPositionTemp.setJobId(jobId);
                if (userId!=null&&userId>0) {
                    //更新用户身份信息
                    detailBiz.updateUserPositionByUserId(userId, postionId);
                    appUserPositionTemp.setUserId(userId);
                }
                if (id!=null&&id>0){
                    appUserPositionTemp.setId(id);
                    updateSelectiveById(appUserPositionTemp);
                }else {
                    insertSelective(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();
    }


    public  void   setPostionIdByPhone(String phone){
        try {
            Example example = new Example(AppUserPositionTemp.class);
            example.createCriteria().andEqualTo("phone", phone).andEqualTo("isDel", 0);
            List<AppUserPositionTemp> list = selectByExample(example);
            if (CollectionUtils.isEmpty(list)){
                log.info("----用户无身份----phone==="+phone);
                return;
            }
            AppUserPositionTemp positionTemp=list.get(0);
            if (positionTemp.getUserId()>0){
                log.info("----用户已存在身份----phone==="+phone);
                return;
            }
            //根据手机号查询userId
            AppUserLogin userLogin = loginBiz.checkeUserLogin(phone);
            if (userLogin==null) {
                log.info("----用户不存在----phone==="+phone);
                return;
            }
            Integer userId=userLogin.getId();
            positionTemp.setUserId(userId);
            int num=updateSelectiveByIdRe(positionTemp);
            if (num>0){
                Integer postionId=positionTemp.getPositionId();
                log.info("----用户---postionId===="+postionId+"----phone==="+phone);
                detailBiz.updateUserPositionByUserId(userId, postionId);
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }
    }


}
