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


import cn.com.countrygarden.bi.main.controller.BaseController;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dto.HouseKeeperDTO;
import cn.com.countrygarden.bi.main.dto.HouseKeeperParamVo;
import cn.com.countrygarden.bi.main.model.review.ReviewEvaluate;
import cn.com.countrygarden.bi.main.model.routine.RoutineManager;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.dup.impl.ExcelHelper;
import cn.com.countrygarden.bi.main.service.routine.IRoutineManagerService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
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.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;


@RestController("RoutineManagerController")
@RequestMapping("/api/routine/manager")
public class RoutineManagerController extends BaseController{

    @Autowired
    private IRoutineManagerService routineManagerService;
    @Autowired
    private AccessTokenService accessTokenService;

    @GetMapping(value = "/list", produces = "application/json;charset=utf-8")
    public Result selectList(RoutineManager routineManager,
        @RequestParam(value = "size", required = false, defaultValue = "10") int size,
        @RequestParam(value = "page", required = false, defaultValue = "1") int page){
        return routineManagerService.selectList(routineManager,size,page);
    }

    @GetMapping(value = "/one", produces = "application/json;charset=utf-8")
    public Result queryById(@RequestParam(value = "id", required = true)Integer id,
                            HttpServletRequest request){
        return  routineManagerService.queryById(id);
    }

    @PostMapping(value = "/update", produces = "application/json;charset=utf-8")
    public Result add(RoutineManager routineManager,
                      HttpServletRequest request){

        return  routineManagerService.addOrUpdate(routineManager,getAccessToken(request));
    }

    @DeleteMapping(value="/del", produces = "application/json;charset=utf-8")
    public Result del(@RequestParam(value = "id", required = true)Integer id){
        return  routineManagerService.del(id);
    }


    /**
     * 导出数据
     *
     * @param requestData
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/exportExcel", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public Result exportExcel(RoutineManager routineManager,
                                HttpServletRequest request, HttpServletResponse response) {

        List<RoutineManager> list = routineManagerService.selectExcelData(routineManager);
        ExcelHelper helper = new ExcelHelper();
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();

        //创建头部
        helper.createRoutineManagerHeader(workbook, sheet,routineManager.getYear(),routineManager.getMonth());
        //创建正文体
        helper.createRoutineManagerBody(list, workbook, sheet);
        response.setContentType("multipart/form-data");
        String fileName = "excel.xlsx";
        try {
            fileName = URLEncoder.encode("常规管家信息.xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception ex) {

        } finally {
            try {
                workbook.close();
            } catch (Exception ex) {

            }
        }
        return null;
    }

    /**
     * 导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", produces = "application/json; charset=utf-8", method = RequestMethod.POST)
    public Result importExcel(@RequestParam("file") MultipartFile excelFile,@RequestParam("data") String data,HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        RoutineManager routineManager = JSONObject.parseObject(data, RoutineManager.class);
        try {
            String accessToken = request.getParameter("AccessToken");
            cn.com.countrygarden.bi.main.model.AccessToken token = null;
            if (accessToken != null){
                token = accessTokenService.findByToken(accessToken);
                if(token==null){
                    result.setResultCode(500);
                    result.setResultMsg("登录失效！");
                }
            }
            Map<String, Object> resultMap = routineManagerService.importExcel(excelFile,routineManager,token);
//            result.setMessage((String) resultMap.get("returnMsg"));
//            result.setCode((Integer) resultMap.get("returnCode"));
            result.setData(resultMap);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setResultMsg(e.getMessage());
            return result.setResultCode(500);
        }
    }

    @GetMapping(value = "/organ/tree", produces = "application/json;charset=utf-8")
    public Result queryOrganTree(){
        return  routineManagerService.queryOrganTree();
    }
}
