package com.yunzhi.marketing.drainage.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunzhi.marketing.base.BaseController;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.drainage.entity.TaDrainage;
import com.yunzhi.marketing.drainage.entity.TaDrainageRecord;
import com.yunzhi.marketing.drainage.service.ITaDrainageRecordService;
import com.yunzhi.marketing.drainage.service.ITaDrainageService;
import com.yunzhi.marketing.excel.handler.CustomCellWriteHandler;
import com.yunzhi.marketing.third.entity.TaThirdPartyMiniappConfig;
import com.yunzhi.marketing.third.service.ITaThirdPartyMiniappConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
    * 引流记录表 全网引流记录表 前端控制器
    * </p>
 *
 * @author jobob
 * @since 2019-10-18
 */
@RestController
@RequestMapping("/api")
public class TaDrainageRecordController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(TaDrainageRecordController.class);

    @Autowired
    public ITaDrainageRecordService iTaDrainageRecordService;
    
    @Autowired
    public ITaThirdPartyMiniappConfigService iTaThirdPartyMiniappConfigService;

    @Autowired
    private ITaDrainageService taDrainageService;
    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/admin/taDrainageRecord",method= RequestMethod.GET)
    public ResponseBean taDrainageRecordList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                             @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                             @RequestParam(value = "drainageId") Integer drainageId,
                                             @RequestParam(value = "startTime",required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startTime,
                                             @RequestParam(value = "endTime",required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endTime,
                                             HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
		    IPage<TaDrainageRecord> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaDrainageRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("drainage_id",drainageId);
            queryWrapper.eq("org_id",getOrgId(request));
            queryWrapper.gt(null != startTime,"create_date",startTime);
            queryWrapper.lt(null != endTime,"create_date",endTime);
            queryWrapper.orderByDesc("create_date");

            IPage<TaDrainageRecord> result = iTaDrainageRecordService.page(pg, queryWrapper);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taDrainageRecordList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
    
    
    /**
     * 导出数据
     * @return
     */
    @RequestMapping(value="/admin/taDrainageRecord/export",method= RequestMethod.GET)
    public void taDrainageRecordList(@RequestParam(value = "drainageId") Integer drainageId,
                                             @RequestParam(value = "startTime",required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
                                             @RequestParam(value = "endTime",required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime,
                                             HttpServletRequest request, HttpServletResponse response) throws IOException {
            //使用分页插件
            QueryWrapper<TaDrainageRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("drainage_id",drainageId);
            queryWrapper.eq("org_id",getOrgId(request));
            queryWrapper.gt(null != startTime,"create_date",startTime);
            queryWrapper.lt(null != endTime,"create_date",endTime);
            queryWrapper.orderByDesc("create_date");
    
            List<TaDrainageRecord> list = iTaDrainageRecordService.list(queryWrapper);
            List<List<String>> resList = new ArrayList<List<String>>();
            
            //构造表头
            if (list.size() > 0) {
                List<String> headerList = new ArrayList<>();
                TaDrainageRecord taDrainageRecord = list.get(0);
                headerList.add("提交时间");
                JSONArray arr= JSONArray.parseArray(taDrainageRecord.getContent());
                arr.forEach(e -> {
                    JSONObject jsonObject = JSONObject.parseObject(e.toString());
                    headerList.add(jsonObject.getString("label"));
                });
                resList.add(headerList);
            }
            
            //构造表数据
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            list.forEach(e -> {
                List<String> bodyList = new ArrayList<>();
                bodyList.add(e.getCreateDate().format(formatter));
                JSONArray arr= JSONArray.parseArray(e.getContent());
                arr.forEach(json -> {
                    JSONObject jsonObject = JSONObject.parseObject(json.toString());
                    bodyList.add(jsonObject.getString("value"));
                });
                resList.add(bodyList);
            });
    
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=引流详情.xlsx");
            // 设置读取的class
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerWriteHandler(new CustomCellWriteHandler()).build();
            // 设置 sheet, 同一个sheet只需要设置一次
            WriteSheet writeSheet = EasyExcel.writerSheet("引流详情").build();
            
            
            excelWriter.write(resList, writeSheet);
    
            /// finish 会帮忙关闭流
            excelWriter.finish();
    }

    /**
     * 保存对象
     * @param taDrainageRecord 实体对象
     * @return
     */
    @RequestMapping(value="/taDrainageRecord",method= RequestMethod.POST)
    public ResponseBean taDrainageRecordAdd(@RequestBody TaDrainageRecord taDrainageRecord){
        ResponseBean responseBean = new ResponseBean();
        try {
            if (iTaDrainageRecordService.save(taDrainageRecord)){
                responseBean.addSuccess(taDrainageRecord);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taDrainageRecordAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @ResponseBody
    @RequestMapping(value="/taDrainageRecord/{id}", method= RequestMethod.DELETE)
    public ResponseBean taDrainageRecordDelete(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            if(iTaDrainageRecordService.removeById(id)){
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taDrainageRecordDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param taDrainageRecord 实体对象
     * @return
     */
    @RequestMapping(value="/taDrainageRecord/{id}",method= RequestMethod.PUT)
    public ResponseBean taDrainageRecordUpdate(@PathVariable Integer id,
                                        @RequestBody TaDrainageRecord taDrainageRecord){
        ResponseBean responseBean = new ResponseBean();
        try {
            if (iTaDrainageRecordService.updateById(taDrainageRecord)){
                responseBean.addSuccess(taDrainageRecord);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taDrainageRecordUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/taDrainageRecord/{id}",method= RequestMethod.GET)
    public ResponseBean taDrainageRecordGet(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iTaDrainageRecordService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taDrainageRecordDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
    
    /**
     * 保存对象
     *
     * @return
     */
    @RequestMapping(value="/third/taDrainageRecord",method= RequestMethod.POST)
    public ResponseBean thirdDrainageRecordAdd(@RequestBody String jsonString,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            //获取H5项目相关信息
            String appid = request.getHeader("x-appid");
            QueryWrapper<TaThirdPartyMiniappConfig> taThirdPartyMiniappConfigQueryWrapper = new QueryWrapper<>();
            
            taThirdPartyMiniappConfigQueryWrapper.eq("appid", appid);
            TaThirdPartyMiniappConfig taThirdPartyMiniappConfig = iTaThirdPartyMiniappConfigService.getOne(taThirdPartyMiniappConfigQueryWrapper);
            if (null == taThirdPartyMiniappConfig){
                return ResponseBean.error("不存在的项目",ResponseBean.ERROR_UNAVAILABLE);
            }
            //保存信息
            JSONObject jsonParse = JSONObject.parseObject(jsonString);
            TaDrainageRecord taDrainageRecord = new TaDrainageRecord();
            taDrainageRecord.setContent(jsonParse.getString("content"));
            JSONArray jsonArray = jsonParse.getJSONArray("content");
            jsonArray.forEach(e -> {
                JSONObject jsonObject = (JSONObject)e;
                if (jsonObject.getString("key").equals("phone")){
                    taDrainageRecord.setPhone(jsonParse.getString("phone"));
                }
                if (jsonObject.getString("key").equals("userName")){
                    taDrainageRecord.setUserName(jsonParse.getString("userName"));
                }
            });
            
            taDrainageRecord.setCreateDate(LocalDateTime.now());
            taDrainageRecord.setDrainageId(taThirdPartyMiniappConfig.getTargetId());
            taDrainageRecord.setOrgId(taThirdPartyMiniappConfig.getOrgId());
            //获取buildingID
            TaDrainage taDrainage = taDrainageService.getById(taThirdPartyMiniappConfig.getTargetId());
            taDrainageRecord.setBuildingId(taDrainage.getBuildingId());
            if (iTaDrainageRecordService.save(taDrainageRecord)){
                //反更新enlist_num字段
                if (null == taDrainage.getEnlistNum()){
                    taDrainage.setEnlistNum(0);
                }
                taDrainage.setEnlistNum(taDrainage.getEnlistNum() + 1);
                taDrainageService.updateById(taDrainage);
                return ResponseBean.success(taDrainageRecord);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taDrainageRecordAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
