package cn.com.countrygarden.bi.main.controller.experience;

import cn.com.countrygarden.bi.main.controller.BaseController;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.core.ResultCode;
import cn.com.countrygarden.bi.main.dto.experience.WcxEmployeeDto;
import cn.com.countrygarden.bi.main.dto.experience.WcxEmployeeManageDto;
import cn.com.countrygarden.bi.main.model.experience.WcxEmployeesManage;
import cn.com.countrygarden.bi.main.model.experience.WcxPublishMessage;
import cn.com.countrygarden.bi.main.service.experience.WcxExperienceService;
import cn.com.countrygarden.bi.main.util.EmptyUtils;
import cn.com.countrygarden.bi.main.util.PageUtils;
import cn.com.countrygarden.bi.main.util.Query;
import cn.com.countrygarden.bi.main.util.wcx.ExcepExportUtil;
import org.apache.commons.lang.StringUtils;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController("WcxExperienceController")
@RequestMapping("/api/experience")
public class WcxExperienceController extends BaseController {

    @Autowired
    WcxExperienceService wcxExperienceService;

    /**
     * 查询总部/中心部门
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/findSysDepartment",produces = "application/json;charset=utf-8")
    public Result findSysDepartment(HttpServletRequest request) throws Exception{
        return wcxExperienceService.findSysDepartment();
    }


    /**
     * 查询员工管理列表
     * @param dto
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/getEmployeesList",produces = "application/json;charset=utf-8")
    public Result getEmployeesList(@RequestBody(required = false) WcxEmployeeDto dto,
                                   HttpServletRequest request) throws Exception{
        Result result = new Result();

        try {
            Map<String,Object> params = new HashMap<String,Object>();
            params.put("name",dto.getName());
            params.put("phone",dto.getPhone());
            params.put("organCode",dto.getOrganCode());
            params.put("commId",dto.getCommId());
            params.put("page",StringUtils.isEmpty(String.valueOf(dto.getPage()))?1:dto.getPage());
            params.put("limit",StringUtils.isEmpty(String.valueOf(dto.getSize()))?10:dto.getSize());
            params.put("identification","0");
            Query query = new Query(params);
            List<WcxEmployeesManage> list = wcxExperienceService.queryPageList(query);
            int total = wcxExperienceService.count(query);
            PageUtils pageUtils = new PageUtils(list,total);
            return result.setResultCode(ResultCode.SUCCESS).setData(pageUtils);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return result.setResultCode(ResultCode.FAIL).setResultMsg(e.getMessage()).setData(false);
        }
    }

    /**
     * 新增/更新员工信息
     * @param dto
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/createOrUpdate",produces = "application/json;charset=utf-8")
    public Result createOrUpdate(@RequestBody WcxEmployeeManageDto dto,HttpServletRequest request) throws Exception{

        Result result = new Result();

        if (EmptyUtils.isEmpty(dto)){
            return result.setResultCode(ResultCode.FAIL).setResultMsg("请求参数不能为空!").setData(false);
        }

        if (EmptyUtils.isEmpty(StringUtils.trimToEmpty(dto.getName())) || EmptyUtils.isEmpty(StringUtils.trimToEmpty(dto.getPhone()))){
            return result.setResultCode(ResultCode.FAIL).setResultMsg("姓名或电话不能为空!").setData(false);
        }

        if (dto.getName().length()>16){
            return result.setResultCode(ResultCode.FAIL).setResultMsg("姓名不能超过16个字符!").setData(false);
        }

        if (EmptyUtils.isNotEmpty(StringUtils.trimToEmpty(dto.getPhone()))){
            if (!StringUtils.isNumeric(dto.getPhone())){
                return result.setResultCode(ResultCode.FAIL).setResultMsg("电话号码必须为数字!").setData(false);
            }
        }

        if (EmptyUtils.isNotEmpty(StringUtils.trimToEmpty(dto.getAge()))){
            if (!StringUtils.isNumeric(dto.getAge())){
                return result.setResultCode(ResultCode.FAIL).setResultMsg("年龄必须为数字!").setData(false);
            }
        }


        try {
            WcxEmployeesManage manage = wcxExperienceService.createOrUpdate(dto,getAccessToken());
            return result.setResultCode(ResultCode.SUCCESS).setData(manage);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return result.setResultCode(ResultCode.FAIL).setResultMsg(e.getMessage()).setData(false);
        }

    }


    /**
     * 设置账号启用/停用
     * @param dto
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/setEnable",produces = "application/json;charset=utf-8")
    public Result setEnable(@RequestBody WcxEmployeeDto dto) throws Exception{

        Result result = new Result();

        if (StringUtils.isBlank(String.valueOf(dto.getEnabled()))
                || StringUtils.isBlank(String.valueOf(dto.getId()))){
            return result.setResultCode(ResultCode.FAIL).setResultMsg("请求参数不能为空").setData(false);
        }

        try {
            int i = wcxExperienceService.setEnable(dto);
            return result.setResultCode(ResultCode.SUCCESS).setData(i);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            return result.setResultCode(ResultCode.FAIL).setResultMsg(e.getMessage()).setData(false);
        }
    }


    /**
     * 删除员工数据
     * @param request
     * @param dto
     * @return
     */
    @PostMapping(value = "/delete",produces = "application/json;charset=utf-8")
    public Result delete(HttpServletRequest request,@RequestBody WcxEmployeeDto dto){
        Result result = new Result();
        if (StringUtils.isBlank(String.valueOf(dto.getId()))){
            return result.setResultCode(ResultCode.FAIL).setResultMsg("请求参数不能为空").setData(false);
        }

        try {

            WcxEmployeesManage manage = wcxExperienceService.queryById(dto.getId());
            if (EmptyUtils.isEmpty(manage)){
                return result.setResultCode(ResultCode.FAIL).setResultMsg("删除的记录不存在").setData(false);
            }

            List<WcxPublishMessage> publishMessage = wcxExperienceService.queryPublishList(manage.getPhone());
            if(EmptyUtils.isNotEmpty(publishMessage)){
                return result.setResultCode(ResultCode.FAIL).setResultMsg("该账号发表过体验反馈不能删除!").setData(false);
            }


            int i = wcxExperienceService.delete(dto.getId());
            return result.setResultCode(ResultCode.SUCCESS).setData(i);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            return result.setResultCode(ResultCode.FAIL).setResultMsg(e.getMessage()).setData(false);
        }

    }

    /**
     * 模板下载
     * @param request
     * @param response
     * @return
     */
    @GetMapping(value = "/downloadEmployeeTemplate")
    public Result downloadEmployeeTemplate(HttpServletRequest request,
                                           HttpServletResponse response) throws Exception{
        Result result = new Result();

        try {
            wcxExperienceService.downloadEmployeeTemplate(request,response);
            return result.setResultCode(ResultCode.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(),e);
            return result.setResultCode(ResultCode.FAIL).setData(false);
        }
    }

    /**
     * 导入员工用户数据
     * @param file
     * @param request
     * @return
     */
    @PostMapping(value = "/importEmployees")
    public Result importEmployees(@RequestBody MultipartFile file,HttpServletRequest request) throws Exception{

        Result result = new Result();

        if (file.getSize() > 5242880){
            return result.setResultCode(ResultCode.FAIL).setResultMsg("文件大小限制在5MB内").setData(false);
        }

        try {

            if (file!=null){
                String fileName = file.getOriginalFilename();
                String fileType = fileName.substring(fileName.lastIndexOf("."));
                if(file.isEmpty() && !fileType.equals(".xls") && !fileType.equals(".xlsx")) {
                    return result.setResultCode(ResultCode.FAIL).setResultMsg("文件格式错误，请检查！").setData(false);
                }

                result = wcxExperienceService.importEmployees(file.getInputStream(),fileName,fileType,getAccessToken());
            }else {
                return result.setResultCode(ResultCode.FAIL).setResultMsg("文件为空，请检查！");
            }

            return result;
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return result.setResultCode(ResultCode.FAIL).setResultMsg(e.getMessage()).setData(false);
        }
    }
    /**
     * 体验官数据导出
     * https://ahr-test2.bgyfw.com:8013/ahr/motivate/project/config/export
     * /motivateProjectConfig?AccessToken=GAYTMNZQGQ5FQ5LOLFUTAMJDHEZTAOJQGEZGMOBZMY3TIZBSGA4GGOBVHFQTMYJTGUYDENBXHEZQ&id=57&status=&grantCycle=&name=
     * */
    @RequestMapping(value = "/exportEmployeesList",produces = "multipart/form-data")
    public void exportEmployeesList(@ModelAttribute WcxEmployeeDto dto,
                                   HttpServletRequest request,HttpServletResponse response) throws Exception{
        Result result = new Result();
        try {
            Map<String,Object> params = new HashMap<String,Object>();
            params.put("name",dto.getName());
            params.put("phone",dto.getPhone());
            params.put("organCode",dto.getOrganCode());
            params.put("commId",dto.getCommId());
            params.put("identification","0");
            Query query = new Query(params);
            List<WcxEmployeesManage> list = wcxExperienceService.queryPageList(query);
            ExcepExportUtil<WcxEmployeesManage> excepExportUtil=new ExcepExportUtil<WcxEmployeesManage>();
            /**
             * fileName 导出文件名含后缀
             * fileLocalUrl 服务器存放模板文件
             * sheetName sheet名
             * list 导出数据
             * <T>  导出实体内
             * num 从第N行开始写入
             * */
            SimpleDateFormat sb=new SimpleDateFormat("yyyy-MM-dd");
            String format = sb.format(new Date());
            excepExportUtil.export(format+".xlsx","excel/experience/员工数据导出模板.xlsx","员工用户管理",response,list,2);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
    }
}
