package com.blueland.render.rest;


/**
 * @author 代码自动生成工具
 * @version 1.0
 * @since
 */

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blueland.annotation.ApiVersion;
import com.blueland.annotation.Log;
import com.blueland.bo.Org;
import com.blueland.bo.TreeEntity;
import com.blueland.bo.TucStaffEntity;
import com.blueland.bo.UpdatephtotEntity;
import com.blueland.constant.RedisConstant;
import com.blueland.core.util.UserUtils;
import com.blueland.dao.StaffDao;
import com.blueland.enums.Version;
import com.blueland.model.TUcOrg;
import com.blueland.model.TUcStaff;
import com.blueland.result.R;
import com.blueland.service.ITucOrgService;
import com.blueland.service.ITucStaffService;
import com.blueland.service.SysRedisService;
import com.blueland.vo.StaffPostVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.blueland.constant.CommonConstant.*;
import static com.blueland.constant.ResponseConstant.*;


@Slf4j
@RestController
@RequestMapping(value = "/staff")
public class StaffRest {
    @Autowired
    private ITucStaffService tucStaffServiceImpl;
    @Autowired
    private ITucOrgService tucOrgServiceImpl;

    @Autowired
    private SysRedisService sysRedisService;

    @Resource
    StaffDao staffDao;

    /**
     * 搜索对象
     **/
    @ApiOperation(value = "分页查询员工", notes = "分页查询员工")
    @RequestMapping(value = "", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public R<Page<TucStaffEntity>> list(TucStaffEntity tucStaffEntity) {
        Page<TucStaffEntity> page = this.tucStaffServiceImpl.findPage(tucStaffEntity);
        return R.ok(page);
    }


    /**
     * 搜索对象
     **/
    @ApiOperation(value = "不分页查询员工", notes = "不分页查询员工")
    @RequestMapping(value = "/findlist", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public R<List<TucStaffEntity>> findlist(TucStaffEntity tucStaffEntity) {
        String appId = UserUtils.getTenantId();
        tucStaffEntity.setAppId(appId);
        List<TucStaffEntity> page = this.tucStaffServiceImpl.findList(tucStaffEntity);
        return R.ok(page);
    }

    /**
     * 查看对象
     **/
    @ApiOperation(value = "根据staffId查询员工", notes = "根据staffId查询员工")
    @RequestMapping(value = "/{staffId}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public R<TUcStaff> view(@PathVariable String staffId) {
        TUcStaff tucStaffEntity = tucStaffServiceImpl.getById(staffId);
        return R.ok(tucStaffEntity);
    }

    /**
     * 查看对象（支持多条件查询）
     **/
    @ApiOperation(value = "查看员工（支持多条件查询）", notes = "查看员工（支持多条件查询）")
    @RequestMapping(value = "get", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public R<TUcStaff> get(TucStaffEntity model) {

        TUcStaff tucStaffEntity = tucStaffServiceImpl.get(model);
        return R.ok(tucStaffEntity);
    }

    /**
     * 根据多个staffCode查询用户信息
     **/
    @ApiOperation(value = "根据codes查询员工", notes = "根据codes查询员工")
    @RequestMapping(value = "/getListByCodes", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public R<List<TucStaffEntity>> getListByCodes(@RequestBody List<String> codes) {
        List<TucStaffEntity> list = tucStaffServiceImpl.getListByCodes(codes);
        return R.ok(list);
    }

    /**
     * 新增对象
     **/
    @ApiOperation(value = "新增员工", notes = "新增员工")
    @RequestMapping(value = "", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public R<TucStaffEntity> save(@RequestBody TucStaffEntity model) {
        if (ObjectUtil.isEmpty(model.getDeptId())) {
            throw new RuntimeException("部门ID不能为空");
        }
        List<TUcStaff> addList = tucStaffServiceImpl.handleStaff(model);
        if (ObjectUtil.isNotEmpty(addList)) {
            for (TUcStaff staff : addList) {
                staffDao.insert(staff);
            }
            // 更新缓存
            sysRedisService.flushStaff(addList);
        }
        return R.ok(model, "成功");
    }

    /**
     * 批量新增对象
     **/
    @ApiOperation(value = "批量新增员工", notes = "批量新增员工")
    @RequestMapping(value = "/batch", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public R<Boolean> batchSave(@RequestBody List<TucStaffEntity> model) {
        for (TucStaffEntity staffEntity : model) {
            if (ObjectUtil.isEmpty(staffEntity.getDeptId())) {
                throw new RuntimeException("部门ID不能为空");
            }
            List<TUcStaff> addList = tucStaffServiceImpl.handleStaff(staffEntity);
            if (ObjectUtil.isNotEmpty(addList)) {
                for (TUcStaff staff : addList) {
                    staffDao.insert(staff);
                }
            }
            // 更新缓存
            sysRedisService.flushStaff(addList);
        }
        return R.ok();
    }


    /**
     * 更新对象
     *
     * @return
     **/
    @ApiOperation(value = "修改员工", notes = "修改员工")
    @RequestMapping(value = "", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public R<Boolean> update(@RequestBody TucStaffEntity model) {
        TUcStaff old = tucStaffServiceImpl.getById(model.getStaffId());
        if (ObjectUtil.isEmpty(old)) {
            throw new RuntimeException("员工信息错误");
        }
        if (!Objects.equals(old.getDeptId(), model.getDeptId())) {
            List<TUcStaff> addList = tucStaffServiceImpl.handleStaff(model);
            if (ObjectUtil.isNotEmpty(addList)) {
                for (TUcStaff staff : addList) {
                    if (tucStaffServiceImpl.countStaffByNum(staff.getStaffId(), staff.getAppId()) > 0) {
                        // 更新
                        if (ObjectUtil.isNotEmpty(staff.getStaffBirthday())) {
                            model.setStaffBirthday(DateUtil.format(staff.getStaffBirthday(), "yyyy-MM-dd"));
                            tucStaffServiceImpl.updateByNum(model);
                        }
                    } else {
                        // 新增
                        staffDao.insert(staff);
                    }
                }
                // 更新缓存
                sysRedisService.flushStaff(addList);
            }
        } else {
            TUcStaff staff = BeanUtil.copyProperties(model, TUcStaff.class);
            staffDao.updateById(staff);
            // 更新缓存
            sysRedisService.saveOrUpdateStaff(model);
        }
        return R.ok(true, "成功");
    }

    /**
     * 更新对象
     *
     * @return
     **/
    @ApiOperation(value = "根据staffcode修改员工", notes = "根据staffcode修改员工")
    @RequestMapping(value = "/update/code", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public R<Boolean> updateByCode(@RequestBody TucStaffEntity model) {
//        List<TUcStaff> addList = tucStaffServiceImpl.handleStaff(model);
//        if (ObjectUtil.isNotEmpty(addList)) {
//            for (TUcStaff staff : addList) {
//                if (tucStaffServiceImpl.countStaffByNum(staff.getStaffNum(), staff.getAppId()) > 0) {
//                    // 更新
////                    TUcStaff s = BeanUtil.copyProperties(staff, TUcStaff.class);
//                    model.setStaffBirthday(DateUtil.format(staff.getStaffBirthday(), "yyyy-MM-dd"));
//                    tucStaffServiceImpl.updateByNum(model);
//                } else {
//                    // 新增
//                    staffDao.insert(staff);
//                }
//            }
//            // 更新缓存
//            sysRedisService.flushStaff(addList);
//        }
        if(ObjectUtil.isNotEmpty(model.getStaffBirthday())) {
            Date date = new Date(Long.valueOf(model.getStaffBirthday()));
            model.setStaffBirthday(DateUtil.format(date, "yyyy-MM-dd"));
        }
        tucStaffServiceImpl.updateByNum(model);
        // 更新缓存
        sysRedisService.saveOrUpdateStaff(model);
        return R.ok(true, "成功");
    }

    /**
     * 20210202 add
     * 批量更新员工上级工号（用于初始化员工上级人工号即staffFax字段）
     *
     * @return
     **/
    @ApiOperation(value = "根据staffcode批量修改员工上级人工号", notes = "根据staffcode批量修改员工上级人工号")
    @RequestMapping(value = "/batchupdate/staffFax", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public R<List<TucStaffEntity>> batchupdateStaffFax(@RequestBody List<TucStaffEntity> stafflist) {
        if (null != stafflist && stafflist.size() > 0) {
            tucStaffServiceImpl.batchupdateStaffFax(stafflist);
        }
        return R.ok(stafflist);
    }

    /**
     * 删除对象
     *
     * @return
     **/
    @ApiOperation(value = "根据staffId删除员工", notes = "根据staffId删除员工")
    @RequestMapping(value = "/{staffId}", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public R<Boolean> delete(@PathVariable String staffId) {
        TUcStaff staff = staffDao.selectById(staffId);
        staffDao.deleteById(staffId);
        // 更新缓存
        sysRedisService.removeStaff(staff.getAppId(), staff.getStaffPostCode());
        return R.ok();
    }

    /**
     * 删除对象
     *
     * @return
     **/
    @ApiOperation(value = "根据staffCode删除员工", notes = "根据staffCode删除员工")
    @RequestMapping(value = "/delete/code/{staffCode}", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public R<Boolean> deleteByCode(@PathVariable String staffCode) {
        tucStaffServiceImpl.deleteBycode(staffCode);
        List<TUcStaff> staffs = tucStaffServiceImpl.getByStaffCode(staffCode);
        if (ObjectUtil.isNotEmpty(staffs)) {
            for (TUcStaff staff : staffs) {
                // 更新缓存
                sysRedisService.removeStaff(staff.getAppId(), staff.getStaffPostCode());
            }
        }
        return R.ok();
    }

    /**
     * 组织下的所有用户-内部抵用
     **/
    @ApiOperation(value = "查询组织下的所有的员工", notes = "查询组织下的所有的员工")
    @RequestMapping(value = "/substaffs", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Page<TucStaffEntity> subStaffs(@RequestBody TucStaffEntity staff) {
        if (StringUtils.isEmpty(staff.getStaffType())) {
            throw new RuntimeException("非法参数");
        }
        boolean flag = false;

        if (ObjectUtil.isNotEmpty(staff.getOrgId())) {
            //查询是否是顶级组织，如果是，用mysql函数递归肯定会丢失数据，所以这里就需要直接查询全部
            //获取组织顶级节点
            List<Org> topOrgList = tucOrgServiceImpl.getTopOrg(staff.getStaffType());
            for (Org org : topOrgList) {
                if (staff.getOrgId().equals(org.getOrgId())) {
                    flag = true;
                    break;
                }
            }
            if (flag) {//这里为什么不用sub_staff_type，因为暂时没有维护好这个字段，所以用org_sub_type字段
//                TUcOrg org = tucOrgServiceImpl.getById(staff.getOrgId());
                Page<TucStaffEntity> pageInfo = tucStaffServiceImpl.getStaffInfoByOrgTop(staff);
                return pageInfo;
            }
        }
        Page<TucStaffEntity> pageInfo = null;
        if (staff.getOrgId().contains(",")) {
            pageInfo = this.tucStaffServiceImpl.getStaffByOrgs(staff);
        } else {
            pageInfo = this.tucStaffServiceImpl.getSubStaffs(staff);
        }

        return pageInfo;

    }

    /**
     * 根据staffCode获取员工
     **/
    @ApiOperation(value = "根据ivuser获取员工", notes = "根据ivuser获取员工")
    @RequestMapping(value = "/ivuser/{staffCode}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public R<TucStaffEntity> getByStaffId(@PathVariable String staffCode,
                                          @RequestHeader(value = "iv-user", required = false) String ivUser) {
        String params = "";
        if (!StringUtils.isEmpty(ivUser)) {
            params = ivUser;
        } else if (!StringUtils.isEmpty(staffCode)) {
            params = staffCode;
        }
        TucStaffEntity tucStaffEntity = tucStaffServiceImpl.getStaffByStaffId(params);
        return R.ok(tucStaffEntity);
    }

    /**
     * 功能描述:选择组件搜索人员(组件专用，勿动)
     *
     * @param: [tucStaffEntity]
     * @return: com.blueland.framework.model.ServiceResponse<java.util.List < com.blueland.model.TreeEntity>>
     * @auther: lg 540923947@qq.com
     * @date: 2019/5/9 11:19
     */
    @ApiOperation(value = "选择组件搜索人员", notes = "选择组件搜索人员")
    @RequestMapping(value = "searchUser", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public R<List<TreeEntity>> searchUser(TucStaffEntity model) {
        TucStaffEntity tucStaffEntity = new TucStaffEntity();
        tucStaffEntity.setStaffStatus("QY");
        tucStaffEntity.setSortColumns("staff_sort");
        tucStaffEntity.setQueryStaff(model.getStaffName());
        tucStaffEntity.setStaffType(model.getStaffType());
        tucStaffEntity.setQueryOrgId(model.getOrgId());
        List<TreeEntity> list = this.tucStaffServiceImpl.searchUser(tucStaffEntity);
        return R.ok(list);
    }


    /**
     * 根据staffCode或者staffNum 更新员工设备码
     **/
    @ApiOperation(value = "/updatedevicecode", notes = "根据staffCode或者staffNum 更新员工设备码")
    @RequestMapping(value = "/updatedevicecode", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public R<TUcStaff> update(
            @RequestParam(value = "staffCode", required = false) String staffCode,
            @RequestParam(value = "staffNum", required = false) String staffNum,
            @RequestParam(value = "devicecode", required = true) String devicecode
    ) {
        String msg = RESULT_CODE_SUCCESS_MSG;
        int code = RESULT_CODE_SUCCESS_CODE;
        TUcStaff tucStaffEntity = null;
        try {
            if ((StringUtils.isEmpty(staffCode) && StringUtils.isEmpty(staffNum))
                    || StringUtils.isEmpty(devicecode)) {
                msg = "缺少必要参数";
                code = RESULT_CODE_ERROR_CODE;
            } else {
                TucStaffEntity param = new TucStaffEntity();
                if (!StringUtils.isEmpty(staffCode)) {
                    param.setStaffCode(staffCode);
                    param.setStaffStatus("QY");
                    tucStaffEntity = tucStaffServiceImpl.get(param);
                } else {
                    param.setStaffNum(staffNum);
                    param.setStaffStatus("QY");
                    tucStaffEntity = tucStaffServiceImpl.get(param);
                }
                if (tucStaffEntity == null) {
                    msg = "用户不存在或者已被禁用";
                    code = RESULT_CODE_ERROR_CODE;
                } else {
                    tucStaffEntity.setStaffPhoneBak(devicecode);
                    tucStaffEntity.setStaffLastupdateTime(new Date());
                    tucStaffServiceImpl.updateById(tucStaffEntity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg = "系统错误，" + e.getMessage();
            code = RESULT_SERVER_ERR_CODE;
        }
        return R.ok(tucStaffEntity);
    }

    /**
     * 清空设备码
     **/
    @ApiOperation(value = "/clearDevicecode", notes = "清空设备码")
    @RequestMapping(value = "/clearDevicecode", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public R<Boolean> update(
            @RequestParam(value = "devicecode", required = true) String devicecode
    ) {
        String msg = RESULT_CODE_SUCCESS_MSG;
        int code = RESULT_CODE_SUCCESS_CODE;
        TucStaffEntity tucStaffEntity = null;
        try {
            if (StringUtils.isEmpty(devicecode)) {
                msg = "缺少必要参数";
                code = RESULT_CODE_ERROR_CODE;
            } else {
                tucStaffServiceImpl.updateByStaffPhoneBak(devicecode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg = "系统错误，" + e.getMessage();
            code = RESULT_SERVER_ERR_CODE;
        }
        return R.ok();
    }

    /**
     * 修改员工头像
     **/
    @ApiOperation(value = "/updatephoto", notes = "修改员工头像")
    @RequestMapping(value = "/updatephoto", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public R<Boolean> updatephoto(
            @RequestBody UpdatephtotEntity updatephtotEntity
    ) {
        TUcStaff staff = null;
        String msg = RESULT_CODE_SUCCESS_MSG;
        int code = RESULT_CODE_SUCCESS_CODE;
        try {
            if (StringUtils.isEmpty(updatephtotEntity.getStaffEducation()) || StringUtils.isEmpty(updatephtotEntity.getStaffId())) {
                msg = "缺少必要参数";
                code = RESULT_CODE_ERROR_CODE;
            } else {
                staff = new TUcStaff();
                staff.setStaffId(updatephtotEntity.getStaffId());
                staff.setStaffEducation(updatephtotEntity.getStaffEducation());
                staff.setStaffLastupdateTime(new Date());
                tucStaffServiceImpl.updateById(staff);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg = "系统错误，" + e.getMessage();
            code = RESULT_SERVER_ERR_CODE;
        }
        return R.ok();
    }

    /**
     * 根据姓名查询列表
     */
    @ApiOperation(value = "/getStaffList", notes = "查询列表")
    @RequestMapping(value = "/getStaffList", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public R<List<TucStaffEntity>> getStaffList(
            @RequestParam(value = "name", required = true) String name
    ) {
        List<TucStaffEntity> list = new ArrayList<>();
        if (StringUtils.isEmpty(name)) {
            throw new RuntimeException("确实关键参数");
        }
        list = tucStaffServiceImpl.getStaffList(name);
        return R.ok(list);
    }


    @ApiOperation(value = "加载员工号对应员工信息redis数据")
    @GetMapping("/initStaffNumStaff")
    public R initStaffNumStaff() {
        sysRedisService.initStaff();
        return R.ok();
    }

    // 6.0.0多租户多岗位版本

    @ApiVersion(groups = Version.SIX)
    @ApiOperation(value = "查询岗位信息集合")
    @GetMapping("/findStaffPostList")
    public List<StaffPostVO> findStaffPostList() {
        return tucStaffServiceImpl.findStaffPostList();
    }

    @ApiVersion(groups = Version.SIX)
    @ApiOperation(value = "根据postCode删除员工", notes = "根据postCode删除员工")
    @GetMapping("/delete/code/{postCode}")
    public R<Boolean> deleteByPostCode(@PathVariable String postCode) {
        tucStaffServiceImpl.deleteByPostCode(postCode);
        // 更新缓存
        TucStaffEntity staff = tucStaffServiceImpl.getUserByCode(postCode);
        sysRedisService.removeStaff(staff.getAppId(), staff.getStaffPostCode());
        return R.ok();
    }

    @ApiVersion(groups = Version.SIX)
    @ApiOperation(value = "根据postCode获取员工", notes = "根据postCode获取员工")
    @GetMapping("/postCode/{postCode}")
    public R<TucStaffEntity> getByStaffId(@PathVariable String postCode) {
        TucStaffEntity tucStaffEntity = tucStaffServiceImpl.getStaffByPostCode(postCode);
        return R.ok(tucStaffEntity);
    }

    @ApiVersion(groups = Version.SIX)
    @ApiOperation(value = "根据postCode批量修改员工上级人工号", notes = "根据postCode批量修改员工上级人工号")
    @PutMapping("/batchUpdateByPostCode/staffFax")
    public R<List<TucStaffEntity>> batchUpdateFaxByPostCode(@RequestBody List<TucStaffEntity> stafflist) {
        if (null != stafflist && stafflist.size() > 0) {
            tucStaffServiceImpl.batchUpdateFaxByPostCode(stafflist);
        }
        return R.ok(stafflist);
    }

    @ApiVersion(groups = Version.SIX)
    @ApiOperation(value = "根据PostCodes查询员工", notes = "根据PostCodes查询员工")
    @PostMapping("/getListByPostCodes")
    public R<List<TucStaffEntity>> getListByPostCodes(@RequestBody List<String> codes) {
        List<TucStaffEntity> list = tucStaffServiceImpl.selectStaffByPostCodes(codes);
        return R.ok(list);
    }

    @ApiVersion(groups = Version.SIX)
    @ApiOperation(value = "选择组件搜索人员", notes = "选择组件搜索人员")
    @GetMapping("/searchUserNew")
    public R<List<TreeEntity>> searchUserNew(TucStaffEntity model) {
        TucStaffEntity tucStaffEntity = new TucStaffEntity();
        tucStaffEntity.setStaffStatus("QY");
        tucStaffEntity.setSortColumns("staff_sort");
        tucStaffEntity.setQueryOrgId(model.getOrgId());
        tucStaffEntity.setStaffPostCode(model.getStaffPostCode());
//        tucStaffEntity.setStaffPostType(model.getStaffPostType());
        List<TreeEntity> list = this.tucStaffServiceImpl.searchUser(tucStaffEntity);
        return R.ok(list);
    }

    @ApiVersion(groups = Version.SIX)
    @ApiOperation(value = "根据岗位编码获取用户信息", notes = "根据岗位编码获取用户信息")
    @GetMapping("/getUserByCode")
    @CrossOrigin
    public R<TucStaffEntity> getUserByCode(@RequestParam("code") String code) {
        TucStaffEntity tucStaffEntity = tucStaffServiceImpl.getUserByCode(code);
        return R.ok(tucStaffEntity);
    }
}



