package cn.com.countrygarden.bi.main.controller.ck.ksh;

import cn.com.countrygarden.bi.main.controller.BaseController;
import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.ck.ksh.CkKshBasicMapper;
import cn.com.countrygarden.bi.main.dao.ck.ksh.CkKshExpandMapper;
import cn.com.countrygarden.bi.main.dao.sys.UserRolesMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbSysOrganMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbSysUserMapper;
import cn.com.countrygarden.bi.main.dto.advise.ProjectListVO;
import cn.com.countrygarden.bi.main.dto.advise.RegionListVO;
import cn.com.countrygarden.bi.main.dto.ck.CkCleanerQueyr;
import cn.com.countrygarden.bi.main.dto.ck.CkCleanerTableVo;
import cn.com.countrygarden.bi.main.dto.ck.CkCleanerTableVo2;
import cn.com.countrygarden.bi.main.dto.ck.CkCleanerTableVo3;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.ck.CkCleanerFieldConfig;
import cn.com.countrygarden.bi.main.model.ck.ksh.CkKshBasic;
import cn.com.countrygarden.bi.main.model.ck.ksh.CkKshUnlockApplication;
import cn.com.countrygarden.bi.main.model.sys.UserRoles;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysUser;
import cn.com.countrygarden.bi.main.service.ck.CkKshExpandService;
import cn.com.countrygarden.bi.main.util.DateUtil;
import cn.com.countrygarden.bi.main.util.ExcelCopyUtil;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

@RestController("CkKshBasicController")
@RequestMapping("/api/ckKsh")
public class CkKshBasicController extends BaseController {
    @Autowired
    private CkKshExpandService ckKshExpandService;
    @Autowired
    private CkKshExpandMapper ckKshExpandMapper;
    @Autowired
    private CkKshBasicMapper ckKshBasicMapper;

    @Autowired
    private TbSysOrganMapper tbSysOrganMapper;

    @Autowired
    private TbSysUserMapper tbSysUserMapper;

    @Autowired
    private UserRolesMapper userRolesMapper;

    @GetMapping(value = "/config", produces = "application/json;charset=utf-8")
    public Result config(CkCleanerFieldConfig ckCleanerFieldConfig,
                         @RequestParam(value = "role", required = false) String role,
                         HttpServletRequest request) {
        return ckKshExpandService.getDTableConfig(role,getAccessToken(request));
    }

    @GetMapping(value = "/addConfig", produces = "application/json;charset=utf-8")
    public Result addConfig(
            @RequestParam(value = "basicId")  Integer basicId,
                         @RequestParam(value = "role", required = false) String role,
                         HttpServletRequest request) {
        role="ck_ksh_admin";
        return ckKshExpandService.getaddConfig(basicId,role,getAccessToken(request));
    }

    @GetMapping(value = "/list", produces = "application/json;charset=utf-8")
    public Result list(CkCleanerQueyr cleanerQueyr,
                       HttpServletRequest request) {
        return ckKshExpandService.queryPageList(cleanerQueyr,getAccessToken(request));
    }

    @GetMapping(value = "/listTobeFilledIn", produces = "application/json;charset=utf-8")
    public Result listTobeFilledIn(CkCleanerQueyr cleanerQueyr,
                       HttpServletRequest request) {
        return ckKshExpandService.listTobeFilledIn(cleanerQueyr,getAccessToken(request));
    }

    @PostMapping(value = "/addOrEdit")
    public Result addOrEdit(@RequestParam(value = "data", required = true) String data,
                            @RequestParam(value = "isSubmit", required = true) Integer isSubmit,
                            HttpServletRequest request) {
        return ckKshExpandService.addOrEdit(isSubmit,data, getAccessToken(request),null);
    }

    @PostMapping(value = "/addSubmitEdit")
    public Result addSubmitEdit(
            @RequestParam(value = "basicId") Integer basicId,
            @RequestParam(value = "isSubmit") Integer isSubmit,
                                @RequestParam(value = "selectData") String selectData,
                                @RequestParam(value = "valueData") String valueData,
                            HttpServletRequest request) {
        return ckKshExpandService.addSubmitEdit(basicId,isSubmit,selectData,valueData,getAccessToken(request));
    }

    //提交
    @PostMapping(value = "/submitByid")
    public Result submitByid(@RequestParam(value = "basicIds", required = true) String basicIds,
                            HttpServletRequest request) {
        return ckKshExpandService.submitByid(basicIds, getAccessToken(request));
    }

    //申请解锁
    @PostMapping(value = "/applyUnlock")
    public Result applyUnlock(CkKshUnlockApplication unlockApplication,
                              HttpServletRequest request) {
        return ckKshExpandService.applyUnlock(unlockApplication, getAccessToken(request));
    }

    //申请解锁详细信息
    @GetMapping(value = "/applyUnlockInformation")
    public Result applyUnlockInformation(@RequestParam(value = "basicId") Integer basicId,
                              HttpServletRequest request) {
        return ckKshExpandService.applyUnlockInformation(basicId, getAccessToken(request));
    }

    //解锁操作
    @PostMapping(value = "/unlocking")
    public Result unlocking(@RequestParam(value = "basicId") Integer basicId,
                              HttpServletRequest request) {
        return ckKshExpandService.unlocking(basicId, getAccessToken(request));
    }

    @DeleteMapping(value = "/del")
    public Result del(@RequestParam(value = "basicIds", required = true) List<Integer> basicIds,
                      @RequestParam(value = "dataClassification", required = false) String dataClassification,
                      HttpServletRequest request) {
        return ckKshExpandService.del(basicIds,dataClassification,getAccessToken(request));
    }

    @PostMapping(value = "/inherit", produces = "application/json;charset=utf-8")
    public Result inheritInfo(CkKshBasic ckCleanerBasic) {
        return Response.response(ckKshExpandService.inheritInfo(ckCleanerBasic));
    }

    //添加对外配置
    @PostMapping(value = "/addckexpand", produces = "application/json;charset=utf-8")
    public Result addckexpand(@RequestParam(value = "basicId",required = true) Integer basicId,HttpServletRequest request
            ,@RequestParam(value = "data",required = false) String data) {
        return Response.response(ckKshExpandService.addckexpand(basicId,data,getAccessToken(request)));
    }

    //查询对外配置
    @GetMapping(value = "/ckexpandkedKeys", produces = "application/json;charset=utf-8")
    public Result ckexpandkedKeys(@RequestParam(value = "basicId") Integer basicId) {
        return Response.response(ckKshExpandService.ckexpandkedKeys(basicId));
    }

    //对外配置接口
    @GetMapping(value = "/ckexpand", produces = "application/json;charset=utf-8")
    public Result ckexpand(@RequestParam(value = "commId") Integer[] commId,
                           @RequestParam(value = "year") Integer year,
                           @RequestParam(value = "month") Integer month) {
        return Response.response(ckKshExpandService.ckexpand(commId,year,month));
    }

    //对外配置数据同步接口
    @GetMapping(value = "/allData", produces = "application/json;charset=utf-8")
    public Result allData(@RequestParam(value = "year", required = false) Integer year,
                          @RequestParam(value = "month", required = false) Integer month,
                          @RequestParam(value="page",required=false,defaultValue="1") int page,
                          @RequestParam(value="size",required=false,defaultValue="10") int size,
                          @RequestParam(value="updateDate",required=false) String updateDate) {
        return ckKshExpandService.allData(year,month,page,size,updateDate);
    }

    @GetMapping(value = "/statisticsProject", produces = "application/json;charset=utf-8")
    public Result statisticsProject(@RequestParam(value = "month", required = false) Integer month,
                                    @RequestParam(value = "year", required = false) Integer year,
                                    @RequestParam(value = "orgCode", required = false) String orgCode
    ,HttpServletRequest request) {
        return ckKshExpandService.statisticsProject(year,month,orgCode,getAccessToken(request));
    }

    @GetMapping(value = "/statisProjDetad", produces = "application/json;charset=utf-8")
    public Result statisProjDetad(@RequestParam(value = "page", required = false, defaultValue = "10") int page,
                                  @RequestParam(value = "size", required = false, defaultValue = "1") int size,
                                  @RequestParam(value = "type",required = false) String type,
                                  @RequestParam(value = "month", required = false) Integer month,
                                  @RequestParam(value = "year", required = false) Integer year,
                                  @RequestParam(value = "nianyueStr", required = false) String nianyueStr,
                                  @RequestParam(value = "orgCode", required = false) String orgCode,HttpServletRequest request) throws ParseException {
        return ckKshExpandService.statisProjDetad(year,month,orgCode,type,page,size,nianyueStr,getAccessToken(request));
    }

    @GetMapping(value = "/getRegionDate", produces = "application/json;charset=utf-8")
    public Result getRegionDate(HttpServletRequest request) {

        return Response.response(ckKshExpandService.getRegionDate(getAccessToken(request)));
    }

    @GetMapping(value = "/statisticsProjecttishi", produces = "application/json;charset=utf-8")
    public Result statisticsProjecttishi(
            HttpServletRequest request) {
        return ckKshExpandService.statisticsProjecttishi(getAccessToken(request));
    }

    @GetMapping(value = "/getPojDate", produces = "application/json;charset=utf-8")
    public Result getPojDate(HttpServletRequest request,
                             @RequestParam(value = "organCode",required = true) String organCode) {

        return Response.response(ckKshExpandService.getPojDate(getAccessToken(request),organCode));
    }

    //导出录入和未录入数据
    @GetMapping(value = "/exportEntered", produces = "multipart/form-data")
    public void exportEntered(
            @RequestParam(value = "month", required = false) Integer month,
            @RequestParam(value = "year", required = false) Integer year,
            @RequestParam(value = "orgCode", required = false) String orgCode,
            @RequestParam(value = "entered", required = false) String entered,
            @RequestParam(value = "notEntered", required = false) String notEntered, AccessToken accessToken, HttpServletRequest request, HttpServletResponse response) throws ParseException, IOException {

        List<String> rolesList = queryRoleCodes(null, getAccessToken().getUserCode());
        boolean ckRegionRole=false;
        boolean ckProjectRole=false;
        List<ProjectListVO> projectList2=new ArrayList<>();
        List<RegionListVO> regionList=new ArrayList<>();
        if (rolesList.contains("admin") || rolesList.contains("ck_admin") ||  rolesList.contains("ck_ksh_admin") || rolesList.contains("ck_ksh_region_admin")) {
            //if ( rolesList.contains("admin") || rolesList.contains("ck_admin")) {
            String code=null;
            if(rolesList.contains("admin") || rolesList.contains("ck_admin")){
                code=null;
            }else {
                code=getAccessToken().getUserCode();
                ckRegionRole=true;
            }
            List<RegionListVO> areaList = tbSysOrganMapper.findArea(null, code);
            regionList.addAll(areaList);

        }else {
            throw new ServiceException("此账号无权限导出");
        }

        LocalDate date= LocalDate.now();
        int YesValue=0;
        int MonthValue=0;
 /*       if(date.getMonthValue()-1==0){
            YesValue=date.getYear()-1;
            MonthValue=12;
        }else {
            YesValue=date.getYear();
            MonthValue=date.getMonthValue()-1;
        }*/
        Calendar cal=Calendar.getInstance();
        String startTime=null;
        String endTime=null;

        if (month != null && year != null) {
            YesValue = year;
            MonthValue = month;
            startTime= DateUtil.getMonthStart(year,month);
            endTime=DateUtil.getMonthEnd(year,month);
        }else {
            if(date.getDayOfMonth()>25 || date.getDayOfMonth()<6){
                YesValue=date.getYear();
                MonthValue=date.getMonthValue();

            }else {
                if(date.getMonthValue()-1==0){
                    YesValue=date.getYear()-1;
                    MonthValue=12;
                }else {
                    YesValue=date.getYear();
                    MonthValue=date.getMonthValue()-1;
                }
            }

          /*  cal.add(Calendar.MONTH, 0);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            Date time=cal.getTime();
            startTime=new SimpleDateFormat("yyyy-MM-dd").format(time)+" 00:00:00";

            cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
            Date time1=cal.getTime();
            endTime=new SimpleDateFormat("yyyy-MM-dd").format(time1)+" 23:59:59";*/
        }

        startTime=DateUtil.getMonthStart(YesValue,MonthValue);
        endTime=DateUtil.getMonthEnd(YesValue,MonthValue);

        String[] tiset=startTime.split("-");
        SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       //List<String> listComm=new ArrayList<>();
        List<CkCleanerTableVo> enList=ckKshExpandMapper.statisProjDetad(YesValue,MonthValue,orgCode,ckRegionRole,regionList);
        for (int i = 0; i < enList.size(); i++) {
            TbSysUser user=tbSysUserMapper.findByUserCodeNew(enList.get(i).getCreateBy());
            if(user!=null){
                enList.get(i).setMobileTel(user.getMobileTel());
            }
            enList.get(i).setUpdateTimeStr(time.format(enList.get(i).getUpdateTime()));
        }

        String nianyue=null;
        if(MonthValue<=9){
            nianyue=YesValue+"-"+"0"+MonthValue+"-25";
        }else {
            nianyue=YesValue+"-"+MonthValue+"-25";
        }
        List<CkCleanerTableVo2> notEnList=ckKshBasicMapper.statisProjDetadNot(YesValue,MonthValue,orgCode,null,ckRegionRole,regionList);
       //List<ProjectListVO> notEnList = tbSysOrganMapper.findProjectBasicInfoSelect(listComm);
        for (int i = 0; i < notEnList.size(); i++) {
            notEnList.get(i).setMobileTel("无");
            notEnList.get(i).setCreateName("无");
            notEnList.get(i).setYear(String.valueOf(YesValue));
            notEnList.get(i).setMonth(String.valueOf(MonthValue));
        }

        List<ProjectListVO> projectList = tbSysOrganMapper.findProjectBasicInfoSelect(startTime,endTime,ckRegionRole,regionList,orgCode);
        for (int i = 0; i < projectList.size(); i++) {
            projectList.get(i).setCreateName("无");
            projectList.get(i).setYear(String.valueOf(tiset[0]));
            projectList.get(i).setMonth(String.valueOf(tiset[1]));
            projectList.get(i).setMobileTel("无");
            projectList.get(i).setContractProperty(projectList.get(i).getContractProperty().substring(0,10));
        }

        List<ProjectListVO> projectListrt = tbSysOrganMapper.findProjectBasicInfoCommIdNum(startTime,endTime,ckRegionRole,regionList,orgCode);

        List<CkCleanerTableVo3> listQuwa = ckKshBasicMapper.statisProjDetQuyuWahu(YesValue, MonthValue, orgCode,null,ckRegionRole,regionList);

        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(2);
        for (int i = 0; i <listQuwa.size() ; i++) {
            for (int j = 0; j <projectListrt.size() ; j++) {
                if(listQuwa.get(i).getOrgCode().equals(projectListrt.get(j).getOrganCode())){
                    listQuwa.get(i).setMaintained(listQuwa.get(i).getYilu()+listQuwa.get(i).getWeilu()-projectListrt.get(j).getCommIdNum());
                    if(listQuwa.get(i).getMaintained()!=0){
                        listQuwa.get(i).setComplete(nf.format( Double.valueOf(listQuwa.get(i).getYilu())/Double.valueOf(listQuwa.get(i).getMaintained())*100)+"%");
                    }else{
                        listQuwa.get(i).setComplete("0%");
                    }
                }
            }
        }

        for (int i = 0; i <listQuwa.size() ; i++) {
            if (StringUtil.isBlank(listQuwa.get(i).getComplete())){
                listQuwa.get(i).setMaintained(listQuwa.get(i).getYilu()+listQuwa.get(i).getWeilu());
                if(listQuwa.get(i).getMaintained()!=0){
                    listQuwa.get(i).setComplete(nf.format(Double.valueOf(listQuwa.get(i).getYilu())/Double.valueOf(listQuwa.get(i).getMaintained())*100)+"%");
                }else{
                    listQuwa.get(i).setComplete("0%");
                }
            }
        }

        ExportParams params = new ExportParams("本月区域录入情况", "已录入", ExcelType.XSSF);
        XSSFWorkbook workbook = (XSSFWorkbook) ExcelExportUtil.exportExcel(params, CkCleanerTableVo.class, enList);

        ExportParams params2 = new ExportParams("本月区域录入情况", "未录入", ExcelType.XSSF);
        XSSFWorkbook workbook2 = (XSSFWorkbook) ExcelExportUtil.exportExcel(params2, CkCleanerTableVo2.class, notEnList);


        ExportParams params3 = new ExportParams("本月区域录入情况", "本月新增项目", ExcelType.XSSF);
        XSSFWorkbook workbook3 = (XSSFWorkbook) ExcelExportUtil.exportExcel(params3, ProjectListVO.class, projectList);

        ExportParams params4 = new ExportParams("本月区域录入情况", "区域完成情况统计表", ExcelType.XSSF);
        XSSFWorkbook workbook4 = (XSSFWorkbook) ExcelExportUtil.exportExcel(params4, CkCleanerTableVo3.class, listQuwa);

        workbook.createSheet("未录入");
        workbook.createSheet("本月新增项目");
        workbook.createSheet("区域完成情况统计表");

        ExcelCopyUtil.copySheet(workbook,workbook2.getSheetAt(0),workbook.getSheetAt(1),true);
        ExcelCopyUtil.copySheet(workbook,workbook3.getSheetAt(0),workbook.getSheetAt(2),true);
        ExcelCopyUtil.copySheet(workbook,workbook4.getSheetAt(0),workbook.getSheetAt(3),true);

        downloadExcelData(workbook, "本月区域录入情况");

    }

    @GetMapping(value = "/updateConttPrrty", produces = "application/json;charset=utf-8")
    public void updateConttPrrty() throws ParseException {
        ckKshExpandService.updateConttPrrty();
    }


    @GetMapping(value = "/updateadd", produces = "application/json;charset=utf-8")
    public void updateadd() throws ParseException {
        ckKshExpandService.updateadd();
    }

    @GetMapping(value = "/updateaddXiugai", produces = "application/json;charset=utf-8")
    public void updateaddXiugai() throws ParseException {
        ckKshExpandService.updateaddXiugai();
    }

    @GetMapping(value = "/roleadd", produces = "application/json;charset=utf-8")
    public void roleadd() throws ParseException {
        ckKshExpandService.roleadd();
    }


    @GetMapping(value = "/xiufuadd", produces = "application/json;charset=utf-8")
    public void xiufuadd() throws ParseException {
        ckKshExpandService.xiufuadd();
    }

    public List<String> queryRoleCodes(String[] roles, String userCode) {
        //保洁模块的权限问题：admin=ck_admin>区域>项目>其他
        Condition condition = new Condition(UserRoles.class);
        condition.selectProperties("roleCode");
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("userCode", userCode);
        if (roles != null && roles.length > 0) {
            criteria.andIn("roleCode", Arrays.asList(roles));
        }

        List<UserRoles> rolesList = userRolesMapper.selectByCondition(condition);
        if (CollectionUtils.isNotEmpty(rolesList)) {
            return rolesList.stream().map(e -> e.getRoleCode()).collect(Collectors.toList());
        }
        // 权限不足
        throw new ServiceException("权限不足");
    }

    @GetMapping(value = "/updateEnterTime", produces = "application/json;charset=utf-8")
    public void updateEnterTime() throws ParseException {
        ckKshExpandService.updateEnterTime();
    }
}
