/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 大恒泰山系统
 * 创建日期:2022/8/22
 */
package org.springblade.modules.baseinfo.servicePerson.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.apache.xmlbeans.impl.xb.xsdschema.Attribute;
import org.springblade.constant.BusinessConstant;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DigestUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.enums.OrderCloseEnum;
import org.springblade.enums.PostCategoryEnum;
import org.springblade.modules.auth.enums.UserEnum;
import org.springblade.modules.baseinfo.org.entity.DeptRegionEntity;
import org.springblade.modules.baseinfo.servicePerson.dto.ServicePersonDTO;
import org.springblade.modules.baseinfo.servicePerson.entity.ServicePersonEntity;
import org.springblade.modules.baseinfo.servicePerson.service.IServicePersonService;
import org.springblade.modules.baseinfo.servicePerson.vo.OrgPersonContactVO;
import org.springblade.modules.baseinfo.servicePerson.vo.OrgServicePersonVO;
import org.springblade.modules.baseinfo.servicePerson.vo.ServicePersonVO;
import org.springblade.modules.baseinfo.servicePerson.wrapper.ServicePersonWrapper;
import org.springblade.modules.business.check.order.dto.CheckOrderInfoDTO;
import org.springblade.modules.business.check.order.vo.OrgCheckOrderCountVO;
import org.springblade.modules.business.notice.entity.NoticeEntity;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.Post;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.entity.UserDept;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IPostService;
import org.springblade.modules.system.service.IUserDeptService;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.system.vo.UserVO;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.jws.soap.SOAPBinding;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/***
 * Date:2022/8/22
 * Title:文件所属模块（必须填写）
 * Description：对本文件的详细描述，原则上不能少于30字
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@RestController
@RequestMapping("galaxy-business/serviceperson")
@AllArgsConstructor
@Api(value = "项目运维人员管理", tags = "项目运维人员管理")
public class ServicePersonController extends BladeController {
    private final IServicePersonService servicePersonService;
    private final IUserService userService;
    private final IDeptService deptService;
    private final IUserDeptService userDeptService;
    private final IPostService postService;

    /**
     * 巡检保养工单系统
     * @param dto
     * @param query
     * @return
     */
    @GetMapping("/xjgd/org/user/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "personName", value = "人员名称", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "contactPhone", value = "联系电话", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "deptId", value = "机构部门ID", paramType = "query", dataType = "long"),
    })
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "分页")
    public R<IPage<ServicePersonVO>> xjgdServciePersonPage(@ApiIgnore ServicePersonDTO dto, Query query) {
        BladeUser user = AuthUtil.getUser();
        if (Func.isNull(dto.getTenantId())) {
            dto.setTenantId(user.getTenantId());
        }
        if (Func.isNull(dto.getDeptId())) {
            dto.setDeptId(Func.toLong(user.getDeptId()));
        }
        IPage<ServicePersonVO> pages = servicePersonService.selectServicePersonPage(Condition.getPage(query), dto);
        List<ServicePersonVO> list = pages.getRecords();
        for (ServicePersonVO vo : list) {
            ServicePersonWrapper.build().entityVO(vo);
        }
        return R.data(pages);
    }



    @GetMapping("/org/user/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "personName", value = "人员名称", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "contactPhone", value = "联系电话", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "deptId", value = "机构部门ID", paramType = "query", dataType = "long"),
    })
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "分页")
    public R<IPage<ServicePersonVO>> servciePersonPage(@ApiIgnore ServicePersonDTO dto, Query query) {
        BladeUser user = AuthUtil.getUser();
        if (Func.isNull(dto.getTenantId())) {
            dto.setTenantId(user.getTenantId());
        }
        if (Func.isNull(dto.getDeptId())) {
            dto.setDeptId(Func.toLong(user.getDeptId()));
        }
        dto.setId(user.getUserId());
        if (Func.notNull(dto.getPostCode())) {
            if (1 == dto.getPostCode()) {
                //工程师
                dto.setPostId(Func.toLong(BusinessConstant.POST_COMPANY_YW_ID));
            } else if (2 == dto.getPostCode()) {
                //服务员
                dto.setPostId(Func.toLong(BusinessConstant.POST_COMPANY_SERVICE_PERSON_ID));
            }
        }
        IPage<ServicePersonVO> pages = servicePersonService.selectServicePersonPage(Condition.getPage(query), dto);
        List<ServicePersonVO> list = pages.getRecords();
        for (ServicePersonVO vo : list) {
            ServicePersonWrapper.build().entityVO(vo);
        }
        return R.data(pages);
    }


    @GetMapping("/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "personName", value = "人员名称", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "contactPhone", value = "联系电话", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "deptId", value = "机构部门ID", paramType = "query", dataType = "long"),
    })
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "分页")
    public R<IPage<ServicePersonVO>> page(@ApiIgnore ServicePersonDTO dto, Query query) {
        BladeUser user = AuthUtil.getUser();
        if (Func.isNull(dto.getTenantId())) {
            dto.setTenantId(user.getTenantId());
        }
        if (Func.isNull(dto.getDeptId())) {
            dto.setDeptId(Func.toLong(user.getDeptId()));
        }
        IPage<ServicePersonVO> pages = servicePersonService.selectPage(Condition.getPage(query), dto);
        List<ServicePersonVO> list = pages.getRecords();
        for (ServicePersonVO vo : list) {
            ServicePersonWrapper.build().entityVO(vo);
        }
        return R.data(pages);
    }


    /**
     * 查询技术人员
     *
     * @param dto
     * @param query
     * @return
     */
    @GetMapping("/tech/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "personName", value = "人员名称", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "contactPhone", value = "联系电话", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "deptId", value = "机构部门ID", paramType = "query", dataType = "string"),
    })
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "分页")
    public R<IPage<ServicePersonVO>> techPage(@ApiIgnore ServicePersonDTO dto, Query query) {
        BladeUser user = AuthUtil.getUser();
        if (dto.getDeptId() == null) {
            dto.setDeptId(Func.toLong(user.getDeptId()));
        }
        dto.setCategory(PostCategoryEnum.CATEGORY_SERVICE.getCode());
        IPage<ServicePersonVO> pages = servicePersonService.selectPage(Condition.getPage(query), dto);
        List<ServicePersonVO> list = pages.getRecords();
        for (ServicePersonVO vo : list) {
            ServicePersonWrapper.build().entityVO(vo);
        }
        return R.data(pages);
    }

//    @GetMapping("/list")
//    @ApiOperationSupport(order = 2)
//    @ApiOperation(value = "列表")
//    public R<List<User>> list() {
//        BladeUser user = AuthUtil.getUser();
//        LambdaQueryWrapper<User> wrapper = Wrappers.<User>query().lambda();
//        wrapper.eq(User::getIsDeleted, 0);
//        wrapper.eq(User::getDeptId, Func.toLong(user.getDeptId()));
//        List<User> lists = userService.list(wrapper);
//        return R.data(lists);
//    }

    /**
     * 详情
     */
    @GetMapping("/detail")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "详情", notes = "传入 User")
    public R<ServicePersonEntity> detail(ServicePersonDTO dto) {
        ServicePersonEntity detail = this.servicePersonService.getPersonServiceInfo(dto);
        return R.data(detail);
    }

    /**
     * 新增
     */
    @PostMapping("/save")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "传入 User")
    public R save(@RequestBody ServicePersonEntity userEntity) {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>query().lambda();
        wrapper.eq(User::getAccount, userEntity.getUserAccount().trim());
        wrapper.eq(User::getIsDeleted, 0);
        List<User> list = this.userService.list(wrapper);
        if (null != list && list.size() > 0) {
            return R.fail("帐号已经存在");
        }
        User userDto = new User();
        userDto.setName(userEntity.getPersonName());
        userDto.setRealName(userEntity.getPersonName());
        userDto.setPhone(userEntity.getContactPhone());
        userDto.setEmail(userEntity.getMail());
        userDto.setAccount(userEntity.getUserAccount().trim());
        userDto.setPassword(DigestUtil.encrypt(userEntity.getUserAccount().trim() + BusinessConstant.ACCOUNT_PW_SUFFIX));
        BladeUser user = AuthUtil.getUser();
        userDto.setDeptId(user.getDeptId());
        if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
            userDto.setRoleId(BusinessConstant.ROLE_SYS_YW_ID);
        } else if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName())) {
            userDto.setRoleId(BusinessConstant.ROLE_ORG_YW_ID);
        } else if (BusinessConstant.ROLE_COMPANY_ADMIN.equals(user.getRoleName())) {
            userDto.setRoleId(BusinessConstant.ROLE_COMPANY_YW_ID);
        } else {
            return R.fail("用户创建错误！");
        }

        if (BusinessConstant.POST_SYS_ADMIN_ID.equals(user.getPostId())) {
            userDto.setPostId(BusinessConstant.POST_SYS_YW_ID);
        } else if (BusinessConstant.POST_ORG_ADMIN_ID.equals(user.getPostId())) {
            userDto.setPostId(BusinessConstant.POST_ORG_YW_ID);
        } else if (BusinessConstant.POST_COMPANY_ADMIN_ID.equals(user.getPostId())) {
            userDto.setPostId(BusinessConstant.POST_COMPANY_YW_ID);
        } else {
            return R.fail("用户创建错误！");
        }

        userDto.setUserType(UserEnum.WEB.getCategory());
        return R.status(this.userService.save(userDto));
    }

    /**
     * 新增
     */
    @PostMapping("/org/admin/save")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "传入 User")
    public R orgAdminSave(@RequestBody ServicePersonDTO userEntity) {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>query().lambda();
        wrapper.eq(User::getAccount, userEntity.getUserAccount().trim());
        wrapper.eq(User::getIsDeleted, 0);
        List<User> list = this.userService.list(wrapper);
        if (null != list && list.size() > 0) {
            return R.fail("帐号已经存在");
        }
        User userDto = new User();
        userDto.setName(userEntity.getPersonName());
        userDto.setRealName(userEntity.getPersonName());
        userDto.setPhone(userEntity.getContactPhone());
        userDto.setEmail(userEntity.getMail());
        userDto.setAccount(userEntity.getUserAccount().trim());
        userDto.setPassword(DigestUtil.encrypt(userEntity.getUserAccount().trim() + BusinessConstant.ACCOUNT_PW_SUFFIX));
        userDto.setDeptId(Func.toStr(userEntity.getDeptId()));
        userDto.setRoleId(BusinessConstant.ROLE_ORG_ADMIN_ID);
        userDto.setPostId(BusinessConstant.POST_ORG_ADMIN_ID);
        userDto.setUserType(UserEnum.APP.getCategory());
        this.userService.save(userDto);
        UserDept userDept = new UserDept();
        userDept.setUserId(userDto.getId());
        userDept.setDeptId(userEntity.getDeptId());
        userDeptService.save(userDept);
        return R.status(true);
    }


    /**
     * 新增
     */
    @PostMapping("/org/user/save")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "传入 User")
    public R servicePersonSave(@RequestBody ServicePersonDTO userEntity) {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>query().lambda();
        wrapper.eq(User::getAccount, userEntity.getUserAccount().trim());
        wrapper.eq(User::getIsDeleted, 0);
        List<User> list = this.userService.list(wrapper);
        if (null != list && list.size() > 0) {
            return R.fail("帐号已经存在");
        }
        User userDto = new User();
        userDto.setName(userEntity.getPersonName());
        userDto.setRealName(userEntity.getPersonName());
        userDto.setPhone(userEntity.getContactPhone());
        userDto.setEmail(userEntity.getMail());
        userDto.setAccount(userEntity.getUserAccount().trim());
        userDto.setPassword(DigestUtil.encrypt(userEntity.getUserAccount().trim() + BusinessConstant.ACCOUNT_PW_SUFFIX));
        BladeUser user = AuthUtil.getUser();
        userDto.setDeptId(user.getDeptId());
        userDto.setRoleId(BusinessConstant.ROLE_COMPANY_SERVICE_PERSON_ID);
        if (userEntity.getPostCode() == 1) {
            userDto.setPostId(BusinessConstant.POST_COMPANY_YW_ID);
        } else if (userEntity.getPostCode() == 2) {
            userDto.setPostId(BusinessConstant.POST_COMPANY_SERVICE_PERSON_ID);
        }
        userDto.setUserType(UserEnum.APP.getCategory());
        this.userService.save(userDto);
        UserDept userDept = new UserDept();
        userDept.setUserId(userDto.getId());
        userDept.setDeptId(Func.toLong(userDto.getDeptId()));
        userDeptService.save(userDept);
        return R.status(true);
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "修改", notes = "传入 User")
    public R update(@RequestBody ServicePersonDTO entity) {
        if (Objects.isNull(entity.getId())) {
            return R.fail("用户ID不能为空！");
        }
        User user = this.userService.getById(entity.getId());
        user.setRealName(entity.getPersonName());
        user.setName(entity.getPersonName());
        user.setPhone(entity.getContactPhone());
        user.setEmail(entity.getMail());
//        if (entity.getPostCode() == 1) {
//            user.setPostId(BusinessConstant.POST_COMPANY_YW_ID);
//        } else if (entity.getPostCode() == 2) {
//            user.setPostId(BusinessConstant.POST_COMPANY_SERVICE_PERSON_ID);
//        }
        return R.status(this.userService.updateById(user));
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "逻辑删除", notes = "传入 ids")
    public R remove(@ApiParam(value = "主键集合") @RequestParam String ids) {
        List<Long> list = Func.toLongList(ids);
        if (null != list && list.size() > 0) {
            for (Long id : list) {
                this.userService.removeById(id);
            }
        }
        return R.status(true);
    }

//    @PostMapping("/org/user/remove")
//    @ApiOperationSupport(order = 7)
//    @ApiOperation(value = "逻辑删除", notes = "传入 ids")
//    public R orgUserRemove(@ApiParam(value = "主键集合") @RequestParam String ids) {
//        List<Long> list = Func.toLongList(ids);
//        if (null != list && list.size() > 0) {
//            for (Long id : list) {
//                ServicePersonEntity entity= this.servicePersonService.getById(id);
//                if (Func.notNull(entity)){
//                    this.userService.removeById(entity.get());
//                }
//                this.servicePersonService.removeById(id);
//            }
//        }
//        return R.status(true);
//    }

    /**
     * 机构树
     *
     * @return
     */
//	@GetMapping("/org/dict")
//	@ApiOperationSupport(order = 1)
//	@ApiOperation(value = "详情")
//	public R<List<Dept>> orgTree() {
//		BladeUser user = AuthUtil.getUser();
//		List<Dept> list = new ArrayList<>();
//		if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_SUPER_ADMIN.equals(user.getRoleName())) {
//			List<Dept> root = this.deptService.getDeptChild(0L);
//			list = this.deptService.getDeptChild(root.get(0).getId());
//		} else if (BusinessConstant.ROLE_COMPANY_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_COMPANY_SERVICE_PERSON.equals(user.getRoleName())) {
//			Dept root = this.deptService.getById(Func.toLong(user.getDeptId()));
//			list.add(root);
//		}
//		return R.data(list);
//	}
    @GetMapping("/contact")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "通讯录")
    public R<List<OrgPersonContactVO>> contact() {
        BladeUser user = AuthUtil.getUser();
        List<OrgPersonContactVO> list = new LinkedList<>();
        if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
            LambdaQueryWrapper<Dept> wrapper = Wrappers.<Dept>query().lambda();
            wrapper.eq(Dept::getIsDeleted, 0);
            wrapper.eq(Dept::getParentId, Func.toLong(user.getDeptId()));
            List<Dept> root = this.deptService.list(wrapper);
            for (Dept dept : root) {
                OrgPersonContactVO contactVO = new OrgPersonContactVO();
                contactVO.setId(dept.getId());
                contactVO.setOrgName(dept.getDeptName());
                LambdaQueryWrapper<User> userLambdaQueryWrapper = Wrappers.<User>query().lambda();
                userLambdaQueryWrapper.eq(User::getIsDeleted, 0);
                userLambdaQueryWrapper.eq(User::getDeptId, Func.toStr(dept.getId()));
                List<User> userList = this.userService.list(userLambdaQueryWrapper);
                List<ServicePersonVO> personVOList = new LinkedList<>();
                for (User u : userList) {
                    ServicePersonVO vo = new ServicePersonVO();
                    vo.setId(u.getId());
                    vo.setPersonName(u.getRealName());
                    vo.setContactPhone(u.getPhone());
                    personVOList.add(vo);
                }
                contactVO.setServicePersonVOList(personVOList);
                list.add(contactVO);
            }
        } else if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName())) {
            LambdaQueryWrapper<Dept> wrapper = Wrappers.<Dept>query().lambda();
            wrapper.eq(Dept::getIsDeleted, 0);
            wrapper.eq(Dept::getParentId, Func.toLong(user.getDeptId()));
            List<Dept> root = this.deptService.list(wrapper);
            for (Dept dept : root) {
                OrgPersonContactVO contactVO = new OrgPersonContactVO();
                contactVO.setId(dept.getId());
                contactVO.setOrgName(dept.getDeptName());
                LambdaQueryWrapper<User> userLambdaQueryWrapper = Wrappers.<User>query().lambda();
                userLambdaQueryWrapper.eq(User::getIsDeleted, 0);
                userLambdaQueryWrapper.eq(User::getDeptId, Func.toStr(dept.getId()));
                List<User> userList = this.userService.list(userLambdaQueryWrapper);
                List<ServicePersonVO> personVOList = new LinkedList<>();
                for (User u : userList) {
                    ServicePersonVO vo = new ServicePersonVO();
                    vo.setId(u.getId());
                    vo.setPersonName(u.getRealName());
                    vo.setContactPhone(u.getPhone());
                    personVOList.add(vo);
                }
                contactVO.setServicePersonVOList(personVOList);
                list.add(contactVO);
            }
        } else if (BusinessConstant.ROLE_COMPANY_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_COMPANY_SERVICE_PERSON.equals(user.getRoleName())) {
            OrgPersonContactVO contactVO = new OrgPersonContactVO();
            contactVO.setId(Func.toLong(user.getDeptId()));
            Dept dept = this.deptService.getById(contactVO.getId());
            contactVO.setOrgName(dept.getDeptName());
            LambdaQueryWrapper<User> userLambdaQueryWrapper = Wrappers.<User>query().lambda();
            userLambdaQueryWrapper.eq(User::getIsDeleted, 0);
            userLambdaQueryWrapper.eq(User::getDeptId, Func.toStr(dept.getId()));
            List<User> userList = this.userService.list(userLambdaQueryWrapper);
            List<ServicePersonVO> personVOList = new LinkedList<>();
            for (User u : userList) {
                ServicePersonVO vo = new ServicePersonVO();
                vo.setId(u.getId());
                vo.setPersonName(u.getRealName());
                vo.setContactPhone(u.getPhone());
                personVOList.add(vo);
            }
            contactVO.setServicePersonVOList(personVOList);

            list.add(contactVO);
        }
        return R.data(list);
    }
}
