package xiaoqu.home.open.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import xiaoqu.home.open.aop.AvoidRepeatSubmit;

import xiaoqu.home.open.controller.export.operation.ObjectOperationUnionOutput;
import xiaoqu.home.open.controller.export.operation.ObjectParentOperationUnionOutput;
import xiaoqu.home.open.controller.export.scenes.ObjectFlag;
import xiaoqu.home.open.controller.input.matter.MatterInsert;
import xiaoqu.home.open.controller.input.matter.MatterPageInput;
import xiaoqu.home.open.controller.input.matter.MatterUpdate;
import xiaoqu.home.open.model.db1.User;
import xiaoqu.home.open.model.db2.Matter;
import xiaoqu.home.open.model.db2.Object;
import xiaoqu.home.open.model.db2.Operation;
import xiaoqu.home.open.model.db2.Tools;
import xiaoqu.home.open.publicBean.BaseOutput;
import xiaoqu.home.open.publicBean.PageOutput;
import xiaoqu.home.open.service.RedisService4;
import xiaoqu.home.open.service.db2.AuthorityService;
import xiaoqu.home.open.service.db2.MatterService;
import xiaoqu.home.open.service.db2.ObjectService;
import xiaoqu.home.open.task.bean.DeleteEntityNotice;
import xiaoqu.home.open.task.bean.NameModifyNotice;
import xiaoqu.home.open.utils.DateToConverter;
import xiaoqu.home.open.utils.ResultResponseBeanUtil;
import xiaoqu.home.open.utils.UserUtils;
import xiaoqu.home.open.utils.WrapperUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 *
 */
@Api(value = "事项相关")
@Controller
@RequestMapping("/matter")
@Slf4j
public class MatterController {
    @Autowired
    MatterService matterService;
    @Autowired
    ObjectService objectService;
    //    @Autowired
//    MatterService matterService;
    @Autowired
    AuthorityService authorityService;
    @Autowired
    RedisService4 redisService4;

    @ApiOperation(value = "事项分页查询")
    @ResponseBody
    @RequestMapping(value = "/matterPageList", method = RequestMethod.POST)
    public BaseOutput<PageOutput<Matter>> matterPageList(HttpServletRequest request, @RequestBody MatterPageInput input) {
        User user = UserUtils.getUser(request);
        log.info("【matterPageList】input" + JSONObject.toJSONString(input));
        QueryWrapper<Matter> wrapper = WrapperUtils.getWrapper(false);
        PageOutput<Matter> output = new PageOutput<Matter>();
        if(input.getTreeFlag()!=null&&input.getTreeFlag()==1){
            wrapper.and(wrapperq -> wrapperq.eq("object_name", input.getObjectName()).or().eq("parent_name", input.getObjectName()));
            input.setObjectId(null);
            input.setObjectName(null);
        }
        input.setTreeFlag(null);

        wrapper = WrapperUtils.beanToWrapper(wrapper, input);
        Page<Matter> pageList = new Page<Matter>(input.getPage(), input.getRows());
        List<Matter> matterList = matterService.page(pageList, wrapper).getRecords();
        for (Matter matter:matterList
        ) {
            if(matter.getModifyId()==0){
                matter.setModifyTime(null);
            }
        }
        output.setPage(pageList.getCurrent());
        output.setRecords(pageList.getTotal());
        output.setTotal(pageList.getPages());
        output.setRows(matterList);
        return ResultResponseBeanUtil.success(output);
    }

    @ApiOperation(value = "添加事项信息")
    @ResponseBody
    @AvoidRepeatSubmit
    @RequestMapping(value = "/addMatter", method = RequestMethod.POST)
    public BaseOutput<String> addMatter(HttpServletRequest request, @RequestBody MatterInsert input) {
        User user = UserUtils.getUser(request);
        if (input.getDistrictId() == null || input.getDistrictId() == 0) {
            return ResultResponseBeanUtil.fail("请选择站点");
        }
//        log.info("【addOrUpdateMatter】User:" +user.getName()+",参数："+ JSONMatter.toJSONString(input));
        if (input.getMatterList().isEmpty()) {
            return ResultResponseBeanUtil.fail("请添加事项");

        } else {
            Object object = objectService.getById(input.getObjectId());
            if (object == null) {
                return ResultResponseBeanUtil.fail("请选择事项关联的对象");
            }
            List<MatterUpdate> matterList = input.getMatterList();
            List<Matter> savematters = new ArrayList<>();
            HashSet<String> checkSet = new HashSet<>();
            try {
                StringBuilder stringBuilder = new StringBuilder();
                for (MatterUpdate matterUpdate : matterList) {
                    QueryWrapper<Matter> wrapper = WrapperUtils.getWrapper(false);
                    wrapper.eq("object_id", object.getId());
                    wrapper.eq("name", matterUpdate.getName());
                    int count = matterService.count(wrapper);
                    if (count > 0) {
                        stringBuilder.append(object.getName()).append("对象").append(matterUpdate.getName()).append("事项,");
                    }
                    if(checkSet.contains(object.getId()+"_"+matterUpdate.getName())){
                        stringBuilder.append(object.getName()).append("对象").append(matterUpdate.getName()).append("事项重复添加");
                        return ResultResponseBeanUtil.fail(stringBuilder.toString());

                    }
                    checkSet.add(object.getId()+"_"+matterUpdate.getName());



                    Matter matter = new Matter();
                    matter.setMemo(matterUpdate.getMemo());
                    matter.setName(matterUpdate.getName());
                    matter.setSort(matterUpdate.getSort());
                    matter.setStatus(matterUpdate.getStatus());
                    matter.setParentId(object.getParentId());
                    matter.setParentName(object.getParentName());
                    matter.setObjectId(object.getId());
                    matter.setObjectName(object.getName());
                    matter.setParentName(object.getParentName());
                    matter.setParentId(object.getParentId());
                    matter.setDistrictId(object.getDistrictId());
                    matter.setDistrictName(object.getDistrictName());
                    matter.setPropertyId(object.getPropertyId());
                    matter.setPropertyName(object.getPropertyName());
                    matter.setAgentId(object.getAgentId());
                    matter.setAgentName(object.getAgentName());
                    savematters.add(matter);
                }
                if (stringBuilder.length() > 0) {
                    stringBuilder.append("记录已存在，请修改后再提交");
                    return ResultResponseBeanUtil.fail(stringBuilder.toString());
                }
                for (Matter matter : savematters) {
                    matterService.save(matter);

                }
            } catch (Exception e) {
                e.printStackTrace();
                return ResultResponseBeanUtil.fail("添加失败");

            }
            return ResultResponseBeanUtil.success("添加成功");
        }
    }

    @ApiOperation(value = "修改事项信息")
    @ResponseBody
    @AvoidRepeatSubmit
    @RequestMapping(value = "/updateMatter", method = RequestMethod.POST)
    public BaseOutput<String> updateMatter(HttpServletRequest request, @RequestBody MatterUpdate input) {
        User user = UserUtils.getUser(request);
        log.info("【addOrUpdateMatter】User:" + user.getName() + ",参数：" + JSONObject.toJSONString(input));
        if (input.getId() != null) {
            Matter curMatter = matterService.getById(input.getId());

            if (curMatter == null) {
                return ResultResponseBeanUtil.fail("记录不存在,请确认");
            }
            NameModifyNotice nameModifyNotice = null;

            if (!curMatter.getName().equals(input.getName())) {

                QueryWrapper<Matter> wrapper = WrapperUtils.getWrapper(false);
                wrapper.eq("district_id", curMatter.getDistrictId());
                wrapper.eq("name", input.getName());
                wrapper.eq("object_id", curMatter.getObjectId());
                int count = matterService.count(wrapper);
                if (count > 0) {
                    return ResultResponseBeanUtil.fail("记录已存在，请修改后再提交");
                }
                nameModifyNotice = new NameModifyNotice();

                nameModifyNotice.setId(input.getId());
                nameModifyNotice.setLevel(1);
                nameModifyNotice.setNewName(input.getName());
                nameModifyNotice.setOldName(curMatter.getName());
                nameModifyNotice.setType(3);
                nameModifyNotice.setClassName("Matter");
                // 更新名称
                curMatter.setName(input.getName());
            }


            curMatter.setStatus(input.getStatus());
            curMatter.setMemo(input.getMemo()!=null?input.getMemo():"");
            curMatter.setSort(input.getSort());
            matterService.updateById(curMatter);
            //防止修改失败
            if (nameModifyNotice != null) {
                redisService4.lPush("NameModifyNotice", JSON.toJSONString(nameModifyNotice));
            }
            return ResultResponseBeanUtil.success("修改成功");

        }
        return ResultResponseBeanUtil.fail("请选择记录");


    }

    @ApiOperation(value = "删除事项信息")
    @ResponseBody
    @AvoidRepeatSubmit
    @RequestMapping(value = "/removeMatter", method = RequestMethod.POST)
    public BaseOutput<String> removeMatter(HttpServletRequest request, @RequestBody MatterUpdate input) {
        User user = UserUtils.getUser(request);

//        log.info("【addOrUpdateMatter】User:" +user.getName()+",参数："+ JSONMatter.toJSONString(input));
        if (input.getId() != null) {
            Matter curMatter = matterService.getById(input.getId());
            if (curMatter != null) {
                curMatter.setSoftDelete(1);
                matterService.updateById(curMatter);
                DeleteEntityNotice deleteEntityNotice = new DeleteEntityNotice();
                deleteEntityNotice.setId(curMatter.getId());
                deleteEntityNotice.setLevel(1);
                deleteEntityNotice.setType(3);
                redisService4.lPush("DeleteEntityNotice", JSON.toJSONString(deleteEntityNotice));
            } else {
                return ResultResponseBeanUtil.fail("当前对象未找到");
            }
        }
        return ResultResponseBeanUtil.success("删除成功");

    }


    @ApiOperation(value = "服务事项记录导出")
    @PostMapping("/matterExport")
    public void matterExport(HttpServletRequest request, HttpServletResponse response, @RequestBody MatterPageInput input) throws IOException {
        QueryWrapper<Matter> wrapper = WrapperUtils.getWrapper(false);
        User user = UserUtils.getUser(request);
        log.info("【matterExport】user:" + user.getName() + ",参数：" + JSONObject.toJSONString(input));

//        Boolean aBoolean = authorityService.checkAuthorityIsagent(user.getAuthorityId());
//        wrapper = WrapperUtils.getByIsAgent(aBoolean, user.getAgentId(), wrapper);

        if(input.getTreeFlag()!=null&&input.getTreeFlag()==1){
            wrapper.and(wrapperq -> wrapperq.eq("object_id", input.getObjectId()).or().eq("parent_id", input.getObjectId()));
            input.setObjectId(null);
            input.setObjectName(null);
        }
        input.setTreeFlag(null);
        wrapper = WrapperUtils.beanToWrapper(wrapper, input);
        List<Matter> mattersList = matterService.list(wrapper);
        Map<Long, ObjectParentOperationUnionOutput> objectParentMap = new HashMap<>();
        Map<Long, ObjectOperationUnionOutput> objectMap = new HashMap<>();
        List<ObjectParentOperationUnionOutput> exportList = new ArrayList<>(objectParentMap.values());

        for (Matter matter : mattersList) {

            if (objectParentMap.containsKey(matter.getParentId())) {
                ObjectParentOperationUnionOutput objectParentOperationUnionOutput = objectParentMap.get(matter.getParentId());
                if (objectMap.containsKey(matter.getObjectId())) {
                    ObjectOperationUnionOutput objectOperationUnionOutput = objectMap.get(matter.getObjectId());
                    ObjectFlag objectFlag = new ObjectFlag();
                    objectFlag.setObFlag(matter.getName());
                    objectOperationUnionOutput.getMatterName().add(objectFlag);
                } else {
                    ObjectOperationUnionOutput objectOperationUnionOutput = new ObjectOperationUnionOutput();
                    objectOperationUnionOutput.setObjectId(matter.getObjectId());
                    objectOperationUnionOutput.setObjectName(matter.getObjectName());
                    List<ObjectFlag> mattersName = new ArrayList<>();
                    ObjectFlag objectFlag = new ObjectFlag();
                    objectFlag.setObFlag(matter.getName());
                    mattersName.add(objectFlag);
                    objectOperationUnionOutput.setMatterName(mattersName);
                    objectMap.put(matter.getObjectId(), objectOperationUnionOutput);
                    objectParentOperationUnionOutput.getObjectOperationUnionOutputs().add(objectOperationUnionOutput);
                }

            } else {
                ObjectParentOperationUnionOutput objectParentOperationUnionOutput = new ObjectParentOperationUnionOutput();
                objectParentOperationUnionOutput.setObjectParentId(matter.getParentId());
                objectParentOperationUnionOutput.setObjectParentName(matter.getParentName());
                ObjectOperationUnionOutput objectOperationUnionOutput = new ObjectOperationUnionOutput();
                objectOperationUnionOutput.setObjectId(matter.getObjectId());
                objectOperationUnionOutput.setObjectName(matter.getObjectName());
                List<ObjectFlag> mattersName = new ArrayList<>();
                ObjectFlag objectFlag = new ObjectFlag();
                objectFlag.setObFlag(matter.getName());
                mattersName.add(objectFlag);
                objectOperationUnionOutput.setMatterName(mattersName);
                objectMap.put(matter.getObjectId(), objectOperationUnionOutput);
                ArrayList<ObjectOperationUnionOutput> objects = new ArrayList<>();
                objects.add(objectOperationUnionOutput);
                objectParentOperationUnionOutput.setObjectOperationUnionOutputs(objects);
                objectParentMap.put(matter.getParentId(), objectParentOperationUnionOutput);
                exportList.add(objectParentOperationUnionOutput);

            }
        }

        Map<String, java.lang.Object> map = new HashMap<String, java.lang.Object>();
        String fileTemplate = "./temp/matterTem.xlsx";
        File fileOut = new File(fileTemplate);
        //从jar里读取文件 然后建立临时文件模板  如果temp 目录已经有了就不读取了
        if (!fileOut.exists()) {
            File dirPath = new File("./temp");
            if (!dirPath.exists()) {
                dirPath.mkdir();
            }
            fileOut.createNewFile();//将模板文件放到临时目录
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/matterTem.xlsx");
            FileOutputStream fos = new FileOutputStream(fileTemplate);
            byte[] b = new byte[1024];
            while ((inputStream.read(b)) != -1) {
                fos.write(b);// 写入数据
            }
            inputStream.close();
            fos.close();// 保存数据
        }
        TemplateExportParams params = new TemplateExportParams(fileTemplate);
//        params.setColForEach(true);
//        log.info("场景导出对象=" + JSON.toJSONString(list));
        map.put("list", exportList);

        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        String fileName = "服务事项记录" + DateUtil.format(new Date(), "yyyMMddHHmmss") + ".xlsx";
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "iso8859-1"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        BufferedOutputStream bufferedOutPut = new BufferedOutputStream(response.getOutputStream());
        workbook.write(bufferedOutPut);
        bufferedOutPut.flush();
        bufferedOutPut.close();
    }


}
