package com.repair.controller;

import com.repair.api.RepairUserControllerAPI;
import com.repair.common.utils.paramUtils;
import com.repair.model.enumModel.eUserZZ;
import com.repair.model.pojo.RepairRecord;
import com.repair.model.pojo.RepairUser;
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.RepairRecordService;
import com.repair.services.RepairUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

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;

    /**
     * 添加员工数据接口
     *
     * @param irur
     * @param bindingResult
     * @return
     */
    @Override
    public CommonResult InsertRepairUser(insertRepairUserRequest irur, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        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());
        }
        ru.setUserName(irur.getUserName());
        ru.setCardNumber(irur.getCardNumber());
        ru.setUserZzid(irur.getUserzzId());
        ru.setTeamId(irur.getTeamId());
        ru.setUserPhone(irur.getUserPhone());
        ru.setSchoolId(irur.getSchoolId());
        ru.setWorkType(irur.getWorkType());
        ru.setState(1);//设置大量接单
        ru.setArticle_id(StringUtils.join(irur.getArticleIds(), ','));
        ru.setBuildId(StringUtils.join(irur.getBuildIds(), ','));
        ru.setAcceptanceAssessTime(irur.getAcceptanceAssessTime());
        ru.setMaintenanceAssessTime(irur.getMaintenanceAssessTime());

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

        return result > 0 ? CommonResult.ok("添加成功") : CommonResult.fail("添加失败");
    }

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

        int result = repairUserService.updateRepairUser(data);

        return result > 0 ? CommonResult.ok("修改成功") : CommonResult.fail("修改失败");
    }

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

        for (RepairUserVo r : result.getList()) {
            if (r.getBuildId() != null) {
                r.setBuildIds(Arrays.asList(r.getBuildId().split(",")));
            }
            if (r.getBuildName() != null) {
                r.setBuildNames(Arrays.asList(r.getBuildName().split(",")));
            }
            if (r.getArticleId() != null) {
                r.setArticleIds(Arrays.asList(r.getArticleId().split(",")));
            }
            if (r.getArticleName() != null) {
                r.setArticleNames(Arrays.asList(r.getArticleName().split(",")));
            }
        }

        return CommonResult.ok(result);
    }

    /**
     * 根据ID删除用户数据
     *
     * @param id
     * @return
     */
    @Override
    public CommonResult deleteRepairUserById(int id) {

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

        int result = repairUserService.deleteRepairUserById(id);

        return result > 0 ? CommonResult.ok("删除成功") : CommonResult.fail("删除失败");
    }

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

    @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);
    }

    @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 = 1; i <= 2; i++) {
            AddressBookListVo data = new AddressBookListVo();
            data.setId(i);
            data.setName(i == 1 ? "校方人员" : "第三方人员");
            List<AddressBookVo> abDatas = abs.stream().filter(e -> e.getTeamId() == data.getId()).collect(Collectors.toList());
            data.setList(abDatas);
            result.add(data);
        }

        return CommonResult.ok(result);
    }

    @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("更新成功");
    }

    @Override
    public CommonResult queryPageCollaborator(int currentPage, int pageCount, Integer schoolId, Integer userId) {
        String dateNow = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        PageUtils<RepairWorkTypeVo> result = repairUserService.queryCollaboratorUser(currentPage, pageCount, schoolId, userId, dateNow);
        return CommonResult.ok(result);
    }

    @Override
    public CommonResult queryPositiveReviewPage(int currentPage, int pageCount, Integer schoolId) {
        PageUtils<PositiveReviewVo> result = repairUserService.queryPositiveReviewPage(currentPage, pageCount, schoolId);
        return CommonResult.ok(result);
    }
}

