package com.storlead.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.storlead.framework.common.result.Result;
import com.storlead.system.dto.CompanyDTO;
import com.storlead.system.util.SystemSettingCacheCheckUtil;
import com.storlead.user.pojo.entity.CompanyEntity;
import com.storlead.user.pojo.entity.DeptEntity;
import com.storlead.user.pojo.entity.SubCompanyEntity;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.service.ICompanyService;
import com.storlead.user.service.IDepartService;
import com.storlead.user.service.ISubCompanyService;
import com.storlead.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Resource;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @program: sp-sales
 * @description:
 * @author: chenkq
 * @create: 2022-06-29 17:42
 */


@Api(tags = "平台中心 - 系统: 子公司数据维护")
@RestController
@RequestMapping("/sys/subcompany")
public class SubCompanyApiController {

    @Resource
    private ISubCompanyService subCompanyService;

    @Resource
    private IDepartService departService;

    @Resource
    private ICompanyService companyService;

    @Resource
    private IUserService userService;


    @ApiOperation("新增子公司")
    @PostMapping("save")
    public Result save(SubCompanyEntity subCompany) {
        Result r = SystemSettingCacheCheckUtil.checkAddDataMode();
        if (!r.isSuccess()) {
            return r;
        }
        if(Objects.isNull(subCompany.getId())) {
            subCompany.setDataSource(1);

            LambdaQueryWrapper<CompanyEntity> lm = new LambdaQueryWrapper();
            lm.eq(CompanyEntity::getId,subCompany.getCompanyId());
            lm.last("limit 1");
            CompanyEntity company = companyService.getOne(lm);
            if (Objects.isNull(company)) {
                return Result.error("公司需要绑定在总公司下面,请绑定总公司");
            }
            LambdaQueryWrapper<SubCompanyEntity> subQWrapper = new LambdaQueryWrapper();
            subQWrapper.eq(SubCompanyEntity::getCompanyId,subCompany.getCompanyId());
            subQWrapper.orderByDesc(SubCompanyEntity::getRouteCode);
            subQWrapper.last("limit 1");
            SubCompanyEntity subCompany1 = subCompanyService.getOne(subQWrapper);
            if (Objects.isNull(subCompany1)) {
                subCompany.setRouteCode(company.getRouteCode()+",100");
            }else {
                String [] routeCodes = subCompany1.getRouteCode().split(",");
                String lastCode = routeCodes[routeCodes.length-1];
                lastCode = String.valueOf(Integer.valueOf(lastCode)+1);
                routeCodes[routeCodes.length-1] = lastCode;
                String routeCode = StringUtils.join(routeCodes,",");
                subCompany.setRouteCode(routeCode);
            }
        }
        subCompanyService.saveOrUpdate(subCompany);
        return Result.ok();
    }

    @ApiOperation("分页查询子公司")
    @PostMapping("pagelist")
    public Result pagelist(CompanyDTO param) {
        IPage<SubCompanyEntity> page = new Page<>(param.getPageIndex(),param.getPageSize());
        IPage<SubCompanyEntity> companys = subCompanyService.page(page);
        return Result.result(companys);
    }

    @ApiOperation("查询所有的子公司")
    @PostMapping("list")
    public Result list(CompanyDTO param) {
        IPage<SubCompanyEntity> page = new Page<>(param.getPageIndex(),param.getPageSize());
        IPage<SubCompanyEntity> companys = subCompanyService.page(page);
        return Result.result(companys);
    }

    @ApiOperation("删除子公司信息")
    @PostMapping("delete")
    public Result delete(Long [] ids) {
        if (ids == null || ids.length == 0) {
            return Result.error("参数错误");
        }
        Integer exist = departService.count(new LambdaQueryWrapper<DeptEntity>().in(DeptEntity::getSubCompanyId, Arrays.asList(ids)));
        if (!Objects.equals(exist,Integer.valueOf(0))) {
            return Result.error("公司有关联的部门,无法删除!");
        }
        subCompanyService.removeByIds(Arrays.asList(ids));
        return Result.ok();
    }

    @ApiOperation("设置子公司负责人")
    @PostMapping("setLeaderId")
    public Result setLeaderId(Integer subCompanyId,Long leaderId) {
        if (Objects.isNull(subCompanyId)) {
            return Result.error("参数错误");
        }
        LambdaUpdateWrapper<SubCompanyEntity> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(SubCompanyEntity::getId,subCompanyId);
        UserEntity user = userService.getById(leaderId);
        if (Objects.nonNull(user)) {
            updateWrapper.set(SubCompanyEntity::getLeaderId,leaderId);
            updateWrapper.set(SubCompanyEntity::getLeaderName,user.getRealName());
        } else {
            updateWrapper.set(SubCompanyEntity::getLeaderId,null);
            updateWrapper.set(SubCompanyEntity::getLeaderName,"");
        }
        SubCompanyEntity subCompany = subCompanyService.getById(subCompanyId);
        Boolean b =  subCompanyService.update(updateWrapper);
        if (b) {
            if (Objects.nonNull(subCompany)) {
                if (!leaderId.equals(subCompany.getLeaderId())) {
                    LambdaQueryWrapper subCompanyLq =  new LambdaQueryWrapper<SubCompanyEntity>().eq(SubCompanyEntity::getLeaderId,subCompany.getLeaderId()).ne(SubCompanyEntity::getId,subCompanyId);
                    Integer scCount = subCompanyService.count(subCompanyLq);
                    if (scCount == 0) {
                        LambdaUpdateWrapper<UserEntity> rmLeaderUpdate = new LambdaUpdateWrapper();
                        LambdaQueryWrapper userDeptLq =  new LambdaQueryWrapper<DeptEntity>().eq(DeptEntity::getManagerId,subCompany.getLeaderId());
                        Integer c = departService.count(userDeptLq);
                        if (c > 0) {
                            rmLeaderUpdate.set(UserEntity::getIsLeader,Integer.valueOf(2));
                        } else {
                            rmLeaderUpdate.set(UserEntity::getIsLeader,Integer.valueOf(0));
                        }
                        rmLeaderUpdate.eq(UserEntity::getId,subCompany.getLeaderId());
                        userService.update(rmLeaderUpdate);
                    }
                }
            }
            LambdaUpdateWrapper<UserEntity> userUpdate = new LambdaUpdateWrapper();
            userUpdate.set(UserEntity::getIsLeader,Integer.valueOf(1));
            userUpdate.eq(UserEntity::getId,leaderId);
            userService.update(userUpdate);
        }
        return Result.ok();
    }

    @GetMapping(value = "/subCompany/listHasAllCompany")
    @ApiOperation(value = "公共接口-分公司-包含所有公司列表", notes = "公共接口-分公司-包含所有公司列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = SubCompanyEntity.class)
    })
    public Result<?> listHasAllCompany() {
        List<SubCompanyEntity> list = new ArrayList<>();
        SubCompanyEntity subCompany = new SubCompanyEntity();
        subCompany.setId(0L);
        subCompany.setName("所有公司");
        subCompany.setDesc("所有公司");
        list.add(subCompany);
        // Step.1 组装查询条件
        QueryWrapper<SubCompanyEntity> queryWrapper = new QueryWrapper<SubCompanyEntity>();
        queryWrapper.select("id,company_id,`desc`,name,sort,enabled");
        queryWrapper.eq("enabled", 1);
        queryWrapper.orderByAsc("sort");
        List<SubCompanyEntity> subCompanyEntityList = subCompanyService.list(queryWrapper);
        list.addAll(subCompanyEntityList);
        return Result.result(list);
    }

    @ApiOperation("启用禁用子公司")
    @PostMapping("/enable")
    public Result setEnable(Long id,Boolean enable) {
        LambdaUpdateWrapper<SubCompanyEntity> update = new LambdaUpdateWrapper();
        update.in(SubCompanyEntity::getId, Arrays.asList(id));
        update.set(SubCompanyEntity::getEnabled,enable);
        Boolean re = subCompanyService.update(update);
        if (re) {
            return Result.ok();
        } else {
            return Result.error("操作失败");
        }
    }

}

