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

import com.github.wxiaoqi.security.admin.dto.AppUserPositionChangeRecordDTO;
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.apache.poi.ss.formula.functions.T;
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;

import static com.github.wxiaoqi.security.admin.biz.AppUserPositionChangeRecordBiz.*;


/**
 * 用户身份职位表
 *
 * @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;

    @Autowired
    AppUserPositionChangeRecordBiz appUserPositionChangeRecordBiz;

    public ObjectRestResponse add(AppUserPositionTempDTO appUserPositionTempDTO, Integer updUserId) {
        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());
        }
        //记录表插入
        appUserPositionChangeRecordBiz.addJoinJobRecord(appUserPositionTempDTO, updUserId);
        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 (Objects.nonNull(appUserPositionTempFindDTO.getPositionId())) {
            criteria.andEqualTo("positionId", appUserPositionTempFindDTO.getPositionId());
        }
        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.setIsQuit(appUserPositionTemp.getIsQuit());
            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);
        }
    }

    public AppUserPositionTemp getOne(Integer userId) {
        Example example = new Example(AppUserPositionTemp.class);
        example.createCriteria().andEqualTo("userId", userId).andEqualTo("isDel", 0);
        List<AppUserPositionTemp> list = selectByExample(example);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    /**
     *
     * @return
     */
    public ObjectRestResponse updateUserPositon(T obj) {
            Example example = new Example(AppUserPositionTemp.class);
            Integer userId = 888;
        example.createCriteria().andEqualTo("userId", userId);
        List<AppUserPositionTemp> list = selectByExample(example);
        System.out.println(list);
        mapper.deleteByExample(example);
        return ObjectRestResponse.succ("成功:" + list);
    }


    public List<Integer> getUserIdByParentCompany(List<Integer> parentCompanyId) {
        return mapper.getUserIdByParentCompany(parentCompanyId);
    }


    /**
     * 员工信息修改，插入变更记录表
     * zuoyh
     *
     * @param changeStatus
     * @param appUserPositionTempDTO
     * @return
     */
    public ObjectRestResponse addUserPositionChangeRecord(Integer changeStatus, AppUserPositionTempDTO appUserPositionTempDTO, Integer operatorId) {

        if (changeStatus == null) {
            return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, "操作类型参数不能为空");
        }
        if (appUserPositionTempDTO == null || StringUtils.isBlank(appUserPositionTempDTO.getPhone()) || StringUtils.isBlank(appUserPositionTempDTO.getName())
                || appUserPositionTempDTO.getPositionId() == null || appUserPositionTempDTO.getPositionId() == 0 || appUserPositionTempDTO.getCompanyId() == null) {
            return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, "参数不能为空");
        }
        AppUserPositionTemp userPositionTemp = new AppUserPositionTemp();
        Example example = new Example(AppUserPositionTemp.class);
        example.createCriteria().andEqualTo("id", appUserPositionTempDTO.getId());
        BeanUtils.copyProperties(appUserPositionTempDTO, userPositionTemp);
        AppUserPositionTemp oldData = selectById(appUserPositionTempDTO.getId());
        Long nowTime = System.currentTimeMillis();
        //2:人事变动(更换职位、身份)：需要删除记录后再新增一条记录
        //3：修改所属公司 直接修改即可
        //4：离职
        if (changeStatus.equals(POSITION_CHANGE) || changeStatus.equals(JOB_CHANGE)) {
            mapper.deleteByExample(example);
            userPositionTemp.setCrtTime(nowTime);
            userPositionTemp.setUpdTime(nowTime);
            insertSelective(userPositionTemp);
            //变更记录表插入
            appUserPositionChangeRecordBiz.addPositionChangeRecord(userPositionTemp, oldData, operatorId, appUserPositionTempDTO.getRelTime());
        } else if (changeStatus.equals(COMPANY_CHANGE)) {
            userPositionTemp.setUpdTime(nowTime);
            updateSelectiveById(userPositionTemp);
            //变更记录表插入
            appUserPositionChangeRecordBiz.addPositionChangeRecord(userPositionTemp, oldData, operatorId, appUserPositionTempDTO.getRelTime());
        } else {
            userPositionTemp.setUpdTime(nowTime);
            updateSelectiveById(userPositionTemp);
            appUserPositionChangeRecordBiz.addPositionChangeRecord(userPositionTemp, oldData, operatorId, appUserPositionTempDTO.getRelTime());
        }
        return ObjectRestResponse.succ();
    }

    /**
     * 员工复职
     */
    public ObjectRestResponse andAddUserPositionChangeRecord(AppUserPositionTempDTO appUserPositionTempDTO, Integer operatorId) {
        if (appUserPositionTempDTO == null || StringUtils.isBlank(appUserPositionTempDTO.getPhone())) {
            return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, "参数不能为空");
        }
        AppUserPositionTemp userPositionTemp = new AppUserPositionTemp();
        BeanUtils.copyProperties(appUserPositionTempDTO, userPositionTemp);
        updateSelectiveById(userPositionTemp);
        userPositionTemp.setUpdTime(System.currentTimeMillis());
        appUserPositionChangeRecordBiz.andAddJoinJobRecord(appUserPositionTempDTO, operatorId);
        return ObjectRestResponse.succ();
    }


    /**
     * 查询员工信息变更记录表
     */

    public List<AppUserPositionChangeRecordDTO> findPositionChangeRecord(AppUserPositionTemp userPositionTemp) {
        return appUserPositionChangeRecordBiz.findPositionChangeRecord(userPositionTemp);
    }

}
