package com.repair.controller;

import com.alibaba.fastjson.JSON;
import com.repair.annotation.PassToken;
import com.repair.api.RepairUserControllerAPI;
import com.repair.common.utils.paramUtils;
import com.repair.model.enumModel.eUserZZ;
import com.repair.model.pojo.*;
import com.repair.model.request.ArticleBuildRequest;
import com.repair.model.request.insertRepairUserRequest;
import com.repair.model.request.updateAddressBookRequest;
import com.repair.model.request.updateUserDataRequest;
import com.repair.model.result.CommonResult;
import com.repair.model.result.PageUtils;
import com.repair.model.vo.*;
import com.repair.services.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ceshi
 * @since 2023-07-11
 */
@RestController
public class RepairUserController implements RepairUserControllerAPI {

    @Autowired
    private RepairUserService repairUserService;
    @Autowired
    private RepairRecordService repairRecordService;
    @Autowired
    private RepairArticleBuildService repairArticleBuildService;
    @Autowired
    private RepairDispatchRecordService repairDispatchRecordService;
    @Autowired
    private RepairCollaborateRecordService repairCollaborateRecordService;

    /**
     * 添加员工数据接口
     *
     * @param irur 员工数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public CommonResult InsertRepairUser(insertRepairUserRequest irur) throws Exception {
        System.out.println("添加员工接口参数：" + JSON.toJSON(irur));

        if (irur == null) {
            return CommonResult.fail("参数不能为空！");
        }

        if (irur.getUserZzid() == null) {
            return CommonResult.fail("身份不能为空！");
        }

        //无法添加用户
        if (irur.getUserZzid().intValue() == eUserZZ.User.getValue()){
            return CommonResult.fail("无法添加用户身份！");
        }

        if (irur.getUserName() == null) {
            return CommonResult.fail("姓名不能为空！");
        }
        if (irur.getTeamId() == null) {
            return CommonResult.fail("维修班不能为空！");
        }
        if (irur.getSchoolId() == null) {
            return CommonResult.fail("校区不能为空！");
        }

        //参数判断
        if (irur.getUserZzid().intValue() != eUserZZ.Offline.getValue()) {
            if (irur.getCardNumber() == null) {
                return CommonResult.fail("微校卡号不能为空！");
            }
            if (irur.getUserPhone() == null) {
                return CommonResult.fail("手机号码不能为空！");
            }
            if (irur.getArticleBuilds() == null || irur.getArticleBuilds().size() <= 0) {
                return CommonResult.fail("报修关联楼栋不能为空！");
            }
        }

        RepairUser data = repairUserService.getRepairByCardNumber(irur.getCardNumber());
        RepairUser ru = new RepairUser();
        if (data != null && !data.getUserZzid().equals(eUserZZ.User.getValue())) {
            return CommonResult.fail("该卡号已存在！");
        } else if (data != null) {
            ru.setId(data.getId());
        }

        try {
            //报修类型关联楼栋新增 修改 删除
            List<RepairArticleBuild> ArticleBuilds = new ArrayList<>();//传进来的报修楼栋
            if (irur.getUserZzid().intValue() != eUserZZ.Offline.getValue() && data != null) {
                List<RepairArticleBuild> oldArticleBuilds = repairArticleBuildService.getRepairArticleBuilds(data.getId());
                for (ArticleBuildRequest articleBuild : irur.getArticleBuilds()) {
                    if (articleBuild.getArticleId() == null) {
                        return CommonResult.fail("报修物品ID不能为空");
                    }
                    if (articleBuild.getBuildIds() == null || articleBuild.getBuildIds().size() <= 0) {
                        return CommonResult.fail("关联楼栋不能为空");
                    }

                    RepairArticleBuild articleData = new RepairArticleBuild();
                    articleData.setUserId(data.getId());
                    articleData.setArticleId(articleBuild.getArticleId());
                    articleData.setBuildId(StringUtils.join(articleBuild.getBuildIds(), ','));
                    if (articleBuild.getId() != null && articleBuild.getId() > 0) {
                        articleData.setId(articleBuild.getId());
                    }
                    ArticleBuilds.add(articleData);
                }

                if (ArticleBuilds.size() > 0) {
                    boolean result = repairArticleBuildService.saveorUpdateArticleBuildBatch(ArticleBuilds);

                    if (!result) {
                        throw new Exception("添加失败！");
                    }
                }

                List<Integer> newDatas = ArticleBuilds.stream().map(RepairArticleBuild::getId).collect(Collectors.toList());
                List<Integer> oldDatas = oldArticleBuilds.stream().map(RepairArticleBuild::getId).collect(Collectors.toList());
                //oldData集合不在newDatas集合中的内容
                List<Integer> ids = oldDatas.stream().filter(item -> !newDatas.contains(item)).collect(Collectors.toList());//需要删除的id

                if (ids.size() > 0) {
                    int deleted = repairArticleBuildService.deletedArticleBuildByIds(ids);
                    if (deleted <= 0) {
                        throw new Exception("添加失败！");
                    }
                }
            }

            ru.setUserName(irur.getUserName());
            ru.setUserZzid(irur.getUserZzid());
            ru.setTeamId(irur.getTeamId());
            ru.setSchoolId(irur.getSchoolId());
            ru.setWorkType(irur.getWorkType());
            ru.setState(1);//设置正常接单

            if (irur.getUserZzid().intValue() != eUserZZ.Offline.getValue()) {
                ru.setCardNumber(irur.getCardNumber());
                ru.setUserPhone(irur.getUserPhone());
                ru.setAcceptanceAssessTime(irur.getAcceptanceAssessTime());
                ru.setMaintenanceAssessTime(irur.getMaintenanceAssessTime());
            }

            int result = 0;
            if (data != null) {
                result = repairUserService.updateRepairUser(ru);
            } else {
                result = repairUserService.insertRepairUser(ru);

                if (result > 0 && irur.getUserZzid().intValue() != eUserZZ.Offline.getValue()) {
                    for (ArticleBuildRequest articleBuild : irur.getArticleBuilds()) {
                        RepairArticleBuild articleData = new RepairArticleBuild();
                        articleData.setUserId(result);
                        articleData.setArticleId(articleBuild.getArticleId());
                        articleData.setBuildId(StringUtils.join(articleBuild.getBuildIds(), ','));
                        ArticleBuilds.add(articleData);
                    }
                    if (ArticleBuilds.size() > 0) {
                        boolean insertBatch = repairArticleBuildService.saveArticleBuildBatch(ArticleBuilds);
                        if (!insertBatch) {
                            throw new Exception("添加失败！");
                        }
                    }
                }
            }

            if (result <= 0) {
                throw new Exception("添加失败！");
            }

        } catch (Exception e) {
            throw new Exception("添加失败！");
        }

        return CommonResult.ok("添加成功");
    }

    /**
     * 根据ID编辑用户数据的名称、手机号、身份、工种、维修班、楼栋关联ID、是否能转换、接单考核时间、维修考核时间
     *
     * @param ra            员工数据
     * @param bindingResult 是否为空判断
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public CommonResult updateRepairUserById(updateUserDataRequest ra, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }
        RepairUser data = new RepairUser();
        data.setId(ra.getId());
        data.setSchoolId(ra.getSchoolId());
        data.setUserName(ra.getUserName());
        data.setUserPhone(ra.getUserPhone());
        data.setUserZzid(ra.getUserZzid());
        data.setWorkType(ra.getWorkType());
        data.setTeamId(ra.getTeamId());
        data.setIsChange(ra.getIsChange());
        data.setAcceptanceAssessTime(ra.getAcceptanceAssessTime());
        data.setMaintenanceAssessTime(ra.getMaintenanceAssessTime());

        try {
            if (ra.getArticleBuilds() != null && ra.getArticleBuilds().size() > 0) {
                //报修类型关联楼栋新增 修改 删除
                List<RepairArticleBuild> ArticleBuilds = new ArrayList<>();//传进来的报修楼栋
                List<RepairArticleBuild> oldArticleBuilds = repairArticleBuildService.getRepairArticleBuilds(data.getId());
                for (ArticleBuildRequest articleBuild : ra.getArticleBuilds()) {
                    if (articleBuild.getArticleId() == null) {
                        return CommonResult.fail("报修物品ID不能为空");
                    }
                    if (articleBuild.getBuildIds() == null || articleBuild.getBuildIds().size() <= 0) {
                        return CommonResult.fail("关联楼栋不能为空");
                    }
                    RepairArticleBuild articleData = new RepairArticleBuild();
                    articleData.setUserId(ra.getId());
                    articleData.setArticleId(articleBuild.getArticleId());
                    articleData.setBuildId(StringUtils.join(articleBuild.getBuildIds(), ','));
                    if (articleBuild.getId() != null && articleBuild.getId() > 0) {
                        articleData.setId(articleBuild.getId());
                    }
                    ArticleBuilds.add(articleData);
                }

                if(ArticleBuilds.size() > 0){
                    boolean result = repairArticleBuildService.saveorUpdateArticleBuildBatch(ArticleBuilds);

                    if (!result) {
                        throw new Exception("添加失败！");
                    }
                }

                List<Integer> newDatas = ArticleBuilds.stream().map(RepairArticleBuild::getId).collect(Collectors.toList());
                List<Integer> oldDatas = oldArticleBuilds.stream().map(RepairArticleBuild::getId).collect(Collectors.toList());
                //oldData集合不在newDatas集合中的内容
                List<Integer> ids = oldDatas.stream().filter(item -> !newDatas.contains(item)).collect(Collectors.toList());//需要删除的id

                if (ids.size() > 0) {
                    int deleted = repairArticleBuildService.deletedArticleBuildByIds(ids);
                    if (deleted <= 0) {
                        throw new Exception("修改失败！");
                    }
                }
            }

            int result = repairUserService.updateRepairUser(data);
            if (result <= 0) {
                throw new Exception("修改失败！");
            }
        } catch (Exception e) {
            throw new Exception("修改失败！");
        }

        return CommonResult.ok("修改成功");
    }

    /**
     * 用户分页数据查询
     *
     * @param currentPage 当前页
     * @param pageCount   一页数据条数
     * @param keyWord     关键字
     * @param teamId      维修班
     *                    校方人员：0
     *                    第三方人员：1
     * @param schoolId    校区ID
     *                    黄家湖校区：1
     *                    墨轩湖校区：2
     * @return
     */
    @Override
    public CommonResult queryPageRepairUser(int currentPage, int pageCount, String keyWord, Integer teamId, Integer schoolId) {
        PageUtils<RepairUserVo> result = repairUserService.queryPageRepairUser(currentPage, pageCount, keyWord, teamId, schoolId);

        List<ArticleBuildVo> articleBuilds = new ArrayList<>();
        if (result.getList() != null && result.getList().size() > 0) {
            List<Integer> userIds = result.getList().stream().map(RepairUserVo::getId).collect(Collectors.toList());
            articleBuilds = repairUserService.queryArticleBuilds(userIds);
        }

        for (RepairUserVo r : result.getList()) {
            r.setArticleNames(r.getArticleNames() == null ? new ArrayList() : r.getArticleNames());
            r.setBuildNames(r.getBuildNames() == null ? new ArrayList() : r.getBuildNames());
            r.setArticleBuilds(r.getArticleBuilds() == null ? new ArrayList<>() : r.getArticleBuilds());

            r.setUserZzname(eUserZZ.stringOf(r.getUserZzid()));

            if (articleBuilds.size() > 0) {
                List<ArticleBuildVo> ownerArticleBuild = articleBuilds.stream().filter(e -> e.getUserId().intValue() == r.getId()).collect(Collectors.toList());
                for (ArticleBuildVo owner : ownerArticleBuild) {
                    r.getArticleNames().add(owner.getArticleName());
                    r.getBuildNames().add(owner.getArticleName() + "：" + owner.getBuildName());
                    ArticleBuildRequest data = new ArticleBuildRequest();
                    data.setId(owner.getId());
                    data.setArticleId(owner.getArticleId());
                    List<String> builds = Arrays.asList(owner.getBuildId().split(","));
                    data.setBuildIds(builds);
                    r.getArticleBuilds().add(data);
                }
            }
        }

        return CommonResult.ok(result);
    }

    /**
     * 将原有用户表中的报修关联楼栋弄进去
     */
    @Override
    @PassToken
    public CommonResult insertArticleBuild() {
        List<RepairArticleBuild> result = repairArticleBuildService.queryRepairArticleBuilds();
        List<RepairUser> users = repairUserService.queryRepairUserByArticle();

        List<RepairArticleBuild> insertData = new ArrayList<>();
        for (RepairUser user : users) {
            List<String> articleIds = Arrays.asList(user.getArticleId().split(","));
            for (String articleId : articleIds) {
                if (result != null) {
                    long count = result.stream().filter(e -> e.getArticleId().toString().equals(articleId) && e.getUserId().equals(user.getId())).count();
                    if (count <= 0) {
                        RepairArticleBuild insertD = new RepairArticleBuild();
                        insertD.setArticleId(Integer.valueOf(articleId));
                        insertD.setBuildId(user.getBuildId());
                        insertD.setUserId(user.getId());
                        insertData.add(insertD);
                    }
                }
            }
        }

        boolean insertResult = repairArticleBuildService.saveArticleBuildBatch(insertData);

        return insertResult ? CommonResult.ok("操作成功") : CommonResult.fail("操作失败");
    }


    /**
     * 根据ID删除用户数据
     *
     * @param id 数据ID
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public CommonResult deleteRepairUserById(int id) throws Exception {

        RepairUser data = repairUserService.getRepairById(id);
        if (data == null) {
            return CommonResult.fail("当前数据不存在，删除失败！");
        }

        //判断是否存在待接单或维修中数据:
        //接单表中是否存在当前用户ID的数据条数
        //维修表中是否存在当前用户ID的数据条数
        DisReceCountVo disCount = repairDispatchRecordService.queryDisReceCount(Integer.valueOf(id));
        if (disCount != null) {
            if (disCount.getDisCount() > 0 || disCount.getRecCount() > 0) {
                return CommonResult.fail("存在待处理工单，无法删除");
            }
        }

        try {
            //删除维修关联楼栋数据
            if(data.getUserZzid().intValue() != eUserZZ.Offline.getValue()){
                int deleteData = repairArticleBuildService.deleteRepairArticleBuildByWrapper(id);
                if(deleteData <= 0){
                    throw new Exception("删除失败！");
                }
            }

            int result = repairUserService.deleteRepairUserById(id);
            if(result <= 0){
                throw new Exception("删除失败！");
            }

        } catch (Exception e) {
            throw new Exception("删除失败！");
        }
        return CommonResult.ok("删除成功");
    }

    /**
     * 根据卡号查找用户信息
     *
     * @param cardNumber 卡号
     * @return
     */
    @Override
    public CommonResult queryRepairUserByCardNumber(String cardNumber) {
        RepairUser result = repairUserService.getRepairByCardNumber(cardNumber);
        return result == null ? CommonResult.fail("数据不存在") : CommonResult.ok(result);
    }

    /**
     * 员工分页数据查询
     *
     * @param currentPage 当前页数
     * @param pageCount   一页数据条数
     * @param recordId    报修记录ID
     * @param keyWord     关键字
     * @return
     */
    @Override
    public CommonResult queryPageRepairUsers(int currentPage, int pageCount, Integer recordId, String keyWord) {

        RepairRecord rr = repairRecordService.getRepairById(recordId);

        if (rr == null) {
            return CommonResult.fail("维修单无效，获取维修师傅数据失败");
        }

        String dateNow = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        PageUtils<AutoDispatchUserVo> users = repairUserService.autoDispatchUser(currentPage, pageCount, rr.getSchoolId(), dateNow, rr.getArticleId(), rr.getBuildId(), keyWord);

        return CommonResult.ok(users);
    }

    /**
     * 转线下的员工列表分页数据查询
     *
     * @param currentPage 当前页数
     * @param pageCount   一页数据条数
     * @param recordId    报修记录ID
     * @param keyWord     关键字
     * @return
     */
    @Override
    public CommonResult queryPageOfflineUsers(Integer currentPage, Integer pageCount, Integer recordId, String keyWord) {

        currentPage = currentPage == null || currentPage <= 0 ? 1 : currentPage;
        pageCount = pageCount == null || pageCount <= 0 ? 100 : pageCount;

        RepairRecord rr = repairRecordService.getRepairById(recordId);

        if (rr == null) {
            return CommonResult.fail("维修单无效，获取维修师傅数据失败");
        }

        PageUtils<AutoOfflineUserVo> users = repairUserService.autoOfflineRepairUser(currentPage, pageCount, rr.getSchoolId(), keyWord);

        return CommonResult.ok(users);
    }

    /**
     * 通讯录数据查询
     *
     * @param schoolId 校区ID
     * @param userId   用户ID
     * @param keyWord  关键字
     * @return
     */
    @Override
    public CommonResult getAddressBook(Integer schoolId, Integer userId, String keyWord) {
        List<AddressBookVo> abs = repairUserService.queryAddressBook(userId, schoolId, keyWord);

        List<AddressBookListVo> result = new ArrayList<>();
        for (int i = 0; i <= 1; i++) {
            AddressBookListVo data = new AddressBookListVo();
            data.setId(i);
            data.setName(i == 0 ? "校方人员" : "第三方人员");
            List<AddressBookVo> abDatas = abs.stream().filter(e -> e.getTeamId() == data.getId()).collect(Collectors.toList());
            data.setList(abDatas);
            result.add(data);
        }

        return CommonResult.ok(result);
    }

    /**
     * 编辑通讯录
     *
     * @param uabp          通讯录数据
     * @param bindingResult 是否为空判断
     * @return
     */
    @Override
    public CommonResult updateAddressBook(updateAddressBookRequest uabp, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        RepairUser data = repairUserService.getRepairById(uabp.getId());
        if (data == null) {
            return CommonResult.fail("当前数据不存在，编辑失败！");
        }

        data.setUserPhone(uabp.getPhone());
        data.setState(uabp.getState());
        data.setWorkType(uabp.getWorkType());
        data.setAcceptanceAssessTime(uabp.getAcceptanceTime());
        data.setMaintenanceAssessTime(uabp.getMaintenanceTime());
        int result = repairUserService.updateRepairUser(data);

        return result <= 0 ? CommonResult.fail("更新失败") : CommonResult.ok("更新成功");
    }

    /**
     * 协作人员分页数据查询
     *
     * @param currentPage 当前页数
     * @param pageCount   一页数据条数
     * @param schoolId    校区ID
     * @param userId      用户ID
     * @param keyWord     关键字
     * @return
     */
    @Override
    public CommonResult queryPageCollaborator(Integer currentPage, Integer pageCount, Integer schoolId, Integer userId, String keyWord, Integer recordId) {
        String dateNow = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        if (currentPage == null) {
            currentPage = 1;
        }
        if (pageCount == null) {
            pageCount = 100;
        }

        if (recordId != null) {
            RepairCollaborateRecord cdata = repairCollaborateRecordService.getRepairByRecordId(recordId);
            if (cdata == null) {
                return CommonResult.fail("协作申请无效，获取维修师傅数据失败");
            }
            userId = cdata.getUserId();
        }

        PageUtils<RepairWorkTypeVo> result = repairUserService.queryCollaboratorUser(currentPage, pageCount, schoolId, userId, dateNow, keyWord);

        return CommonResult.ok(result);
    }

    /**
     * 后勤首页工单完成排行榜
     *
     * @param currentPage 当前页数
     * @param pageCount   一页数据条数
     * @param schoolId    校区ID
     * @return
     */
    @Override
    public CommonResult queryPositiveReviewPage(int currentPage, int pageCount, Integer schoolId) {
        PageUtils<PositiveReviewVo> result = repairUserService.queryPositiveReviewPage(currentPage, pageCount, schoolId);
        return CommonResult.ok(result);
    }
}

