package com.huimv.receive.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.huimv.receive.common.utils.*;
import com.huimv.receive.entity.SysAccountMultilevel;
import com.huimv.receive.entity.SysUser;
import com.huimv.receive.entity.pojo.UserPagePojo;
import com.huimv.receive.entity.vo.UserVo;
import com.huimv.receive.service.ISysAccountMultilevelService;
import com.huimv.receive.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/user")
@CrossOrigin
public class SysUserController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysAccountMultilevelService accountMultilevelService;

    @Autowired
    private UploadImage uploadImage;


//    @PostMapping("/list")
//    public JSONObject listUser(@RequestBody Map map) {
//        System.out.println();
//        int pageNum = (Integer)map.get("pageNum");
//        int pageSize = (Integer)map.get("pageSize");
//        String searchStr = (String)map.get("searchStr");
//        return iUserService.findUserAccount(searchStr,pageNum,pageSize);
//    }
    //员工分页查询
    @PostMapping("/page")
    public Result page(@RequestBody UserPagePojo userPagePojo) {
        return sysUserService.pageAll(userPagePojo);
    }
    //员工查询
    @PostMapping("/list")
    public Result list(@RequestBody Map map) {
        return sysUserService.list(map);
    }

    @PostMapping("/getOneById")
    public Result getOneById(@RequestBody Map<String,Integer> map) {
        Integer id = map.get("id");

        return new Result(ResultCode.SUCCESS,sysUserService.getById(id));
    }

    //员工新增
    @PostMapping("/add")
    public Result add(@RequestParam("userId") String userId,
                      @RequestParam(value = "userName",required = false) String userName,
                      @RequestParam(value = "gender",required = false) String gender,
                      @RequestParam(value = "nation",required = false) String nation,
                      @RequestParam(value = "nativePlace",required = false) String nativePlace,
                      @RequestParam(value = "birthday",required = false) String birthday,
                      @RequestParam(value = "politicsPace",required = false) String politicsPace,
                      @RequestParam(value = "peopleType",required = false) String peopleType,
                      @RequestParam(value = "educationalLevel",required = false) String educationalLevel,
                      @RequestParam(value = "cardType",required = false) String cardType,
                      @RequestParam(value = "cardNum",required = false) String cardNum,
                      @RequestParam(value = "userPhone",required = false) String userPhone,
                      @RequestParam(value = "publicPhone",required = false) String publicPhone,
                      @RequestParam(value = "userMali",required = false) String userMali,
                      @RequestParam(value = "publicMali",required = false) String publicMali,
                      @RequestParam(value = "entryTime",required = false) String entryTime,
                      @RequestParam(value = "probation",required = false) String probation,
                      @RequestParam(value = "department",required = false) String department,
                      @RequestParam(value = "job",required = false) String job,
                      @RequestParam(value = "jobType",required = false) String jobType,
                      @RequestParam(value = "workLocation",required = false) String workLocation,
                      @RequestParam(value = "workLocationType",required = false) String workLocationType,
                      @RequestParam(value = "farmId",required = false) String farmId,
                      @RequestParam(value = "emergentUser",required = false) String emergentUser,
                      @RequestParam(value = "emergentUserPhone",required = false) String emergentUserPhone,
                      @RequestParam(value = "sheng",required = false) String sheng,
                      @RequestParam(value = "shi",required = false) String shi,
                      @RequestParam(value = "xxdz",required = false) String xxdz,
                      @RequestParam(value = "yzbm",required = false) String yzbm,
                      @RequestParam("imgUrl") MultipartFile imgUrl,
                      @RequestParam(value = "isAllFarm",required = false) Integer isAllFarm) throws IOException {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        sysUser.setUserId(userId);
        sysUser.setGender(Integer.parseInt(gender));
        sysUser.setNation(nation);
        sysUser.setNativePlace(nativePlace);
        sysUser.setIsAllFarm(isAllFarm);
        sysUser.setBirthday(DateUtil.parse(birthday,"yyyy-MM-dd"));
        sysUser.setPoliticsPace(politicsPace);
        sysUser.setPeopleType(peopleType);
        sysUser.setEducationalLevel(educationalLevel);
        sysUser.setCardType(cardType);
        sysUser.setCardNum(cardNum);
        sysUser.setUserPhone(userPhone);
        sysUser.setPublicPhone(publicPhone);
        sysUser.setUserMali(userMali);
        sysUser.setPublicMali(publicMali);
        if (StringUtils.isNotBlank(entryTime)){
            sysUser.setEntryTime(DateUtil.parse(entryTime,"yyyy-MM-dd"));
        }

        sysUser.setProbation(probation);
        sysUser.setDepartment(department);
        sysUser.setJob(job);
        sysUser.setJobType(jobType);
        sysUser.setWorkLocation(workLocation);
        sysUser.setWorkLocationType(workLocationType);
        sysUser.setFarmId(farmId);
        sysUser.setEmergentUser(emergentUser);
        sysUser.setEmergentUserPhone(emergentUserPhone);
        sysUser.setSheng(sheng);
        sysUser.setShi(shi);
        sysUser.setXxdz(xxdz);
        sysUser.setYzbm(yzbm);

        if (ObjectUtil.isNotEmpty(imgUrl)) {
            String imageCom = uploadImage.getImageCom(imgUrl);
            if ("上传失败".equals(imageCom)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return new Result(10001, "图片上传失败", false);
            }else {
                sysUser.setImgUrl(imageCom);
            }
        }
        if ("身份证".equals(cardType) && !IDCardValidator.isValidIDCard(cardNum)) {
            return new Result(10001,"身份证格式不正确",false);
        }

        if (!PhoneNumberValidator.isValidPhoneNumber(userPhone)) {
            return new Result(10001,"手机号格式不正确",false);
        }

        int count = sysUserService.count(new QueryWrapper<SysUser>().eq("card_type", cardType).eq("card_num", cardNum));
        if (count >0) {
            return new Result(10001,"身份证已存在",false);
        }

        int countUserPhone = sysUserService.count(new QueryWrapper<SysUser>().eq("user_phone", userPhone));
        if (countUserPhone >0) {
            return new Result(10001,"手机号已存在",false);
        }
        if (ObjectUtil.isNotEmpty(sysUser.getBirthday())){
            sysUser.setAge(DateUtil.ageOfNow(sysUser.getBirthday()));
        }
        sysUserService.save(sysUser);
        return new Result(10000,"保存成功",true);
    }


    //查询工作地点
    @PostMapping("/listWorkLocation")
    public Result listWorkLocation(@RequestBody Map map) {
        return sysUserService.listWorkLocation(map);
    }

    @PostMapping("/update")
    public Result update(@RequestBody UserVo sysUser) {
        String cardType = sysUser.getCardType();
        String cardNum = sysUser.getCardNum();

        String userPhone = sysUser.getUserPhone();
        if(StringUtils.isNotBlank(userPhone)){
            if (!PhoneNumberValidator.isValidPhoneNumber(userPhone)) {
                return new Result(10001,"手机号格式不正确",false);
            }
            int count = sysUserService.count(new QueryWrapper<SysUser>().eq("user_phone", userPhone).ne("id",sysUser.getId())) ;
            if (count >0) {
                return new Result(10001,"手机号已存在",false);
            }
        }
        if(StringUtils.isNotBlank(cardNum)){
            if (StringUtils.isNotBlank(cardNum) && "身份证".equals(cardType) && !IDCardValidator.isValidIDCard(cardNum)) {
                return new Result(10001,"身份证格式不正确",false);
            }
            int countUserPhone = sysUserService.count(new QueryWrapper<SysUser>().eq("card_type", cardType).eq("card_num", cardNum).ne("id",sysUser.getId()));
            if (countUserPhone >0) {
                return new Result(10001,"身份证已存在",false);
            }
        }

        if (ObjectUtil.isNotEmpty(sysUser.getBirthday())){
            sysUser.setAge(DateUtil.ageOfNow(sysUser.getBirthday()));
        }
        SysUser user = new SysUser();
        user.setId(sysUser.getId());
        user.setAge(sysUser.getAge());
        user.setBirthday(sysUser.getBirthday());
        user.setCardNum(sysUser.getCardNum());
        user.setCardType(sysUser.getCardType());
        user.setDepartment(sysUser.getDepartment());
        user.setEducationalLevel(sysUser.getEducationalLevel());
        user.setEmergentUser(sysUser.getEmergentUser());
        user.setEmergentUserPhone(sysUser.getEmergentUserPhone());
        user.setEntryTime(sysUser.getEntryTime());
        user.setFarmId(sysUser.getFarmId());
        user.setGender(sysUser.getGender());
        user.setNation(sysUser.getNation());
        user.setNativePlace(sysUser.getNativePlace());
        user.setPeopleType(sysUser.getPeopleType());
        user.setPoliticsPace(sysUser.getPoliticsPace());
        user.setProbation(sysUser.getProbation());
        user.setPublicMali(sysUser.getPublicMali());
        user.setPublicPhone(sysUser.getPublicPhone());
        user.setSheng(sysUser.getSheng());
        user.setShi(sysUser.getShi());
        user.setUserId(sysUser.getUserId());
        user.setUserMali(sysUser.getUserMali());
        user.setUserName(sysUser.getUserName());
        user.setUserPhone(sysUser.getUserPhone());
        user.setWorkLocation(sysUser.getWorkLocation());
        user.setWorkLocationType(sysUser.getWorkLocationType());
        user.setXxdz(sysUser.getXxdz());
        user.setYzbm(sysUser.getYzbm());
        user.setImgUrl(sysUser.getImgUrl());
        user.setJobType(sysUser.getJobType());

        if (ObjectUtil.isNotEmpty(sysUser.getJob())){
            String s = "";
            List<String> job = sysUser.getJob();
            //TODO 判空
            s = String.join(",",job);
            user.setJob(s);
        }
        sysUserService.updateById(user);

        accountMultilevelService.updateByUser(user);
        return new Result(10000,"修改成功",true);
    }

    @PostMapping("/uploadUserImg")
    public Result uploadUserImg(@RequestParam("imgUrl") MultipartFile imgUrl,
                         @RequestParam("id") Integer id) throws IOException {

       return sysUserService.uploadUserImg(imgUrl,id);

    }

    @PostMapping("/remove")
    @Transactional
    public Result remove(@RequestBody Map<String,String> map) {
        String ids = map.get("ids");
        if (StringUtils.isBlank(ids)) {
            return new Result(10001,"所选用户不存在",false);
        }
        List<String> collection = Arrays.stream(ids.split(","))
                .collect(Collectors.toList());
         sysUserService.removeByIds(collection);
         //删除账号
        accountMultilevelService.remove(new QueryWrapper<SysAccountMultilevel>().in("user_id",collection));
        return new Result(10000,"删除成功",true);
    }

    //账号查询
    @PostMapping("/pageAccount")
    public Result pageAccount(@RequestBody UserPagePojo userPagePojo) {
        return  sysUserService.pageAccount( userPagePojo);
    }



    //账号增加
    @PostMapping("/addAccount")
    public Result addAccount(@RequestBody Map<String,Object> map) {
        return  sysUserService.addAccount(map);
    }

    //账号修改
    @PostMapping("/updateAccount")
    public Result updateAccount(@RequestBody Map<String,Object> map) {
        return  sysUserService.updateAccount(map);
    }

    @GetMapping("/printUser")
    public void printUser(HttpServletResponse response, @RequestParam(name = "ids") String ids) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("ids", ids);
        sysUserService.printUser(response, map);
        String path = "/opt/huatong/user.xls";
        PdfUtil.returnPdfStream3(response, path, "人员列表");
    }
    //账号删除
    @PostMapping("/removeAccount")
    @Transactional
    public Result removeAccount(@RequestBody Map<String,String> map) {
        return  sysUserService.removeAccount(map);
    }

    //性别年龄分布
    @PostMapping("/userAgeAndGender")
    public Result userAgeAndGender(@RequestBody Map<String,String> map) {
        return  sysUserService.userAgeAndGender(map);
    }

    //岗位分布
    @PostMapping("/userJob")
    public Result userJob(@RequestBody Map<String,String> map) {
        return  sysUserService.userJob(map);
    }

}
