package xiaoqu.home.open.controller;

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 com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
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.ToolsExport;
import xiaoqu.home.open.controller.input.ToolsInsert;
import xiaoqu.home.open.controller.input.ToolsPageInput;
import xiaoqu.home.open.model.db1.District;
import xiaoqu.home.open.model.db1.User;
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.RedisService5;
import xiaoqu.home.open.service.db1.DistrictService;
import xiaoqu.home.open.service.db2.AuthorityService;
import xiaoqu.home.open.service.db2.ToolsService;
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 xiaoqu.home.open.utils.poi.ExcelUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 */
@Api(value = "工具")
@Controller
@RequestMapping("/tools")
@Slf4j
public class ToolsController {
    @Autowired
    ToolsService toolsService;
    @Autowired
    AuthorityService authorityService;
    @Autowired
    DistrictService districtService;
    @Autowired
    RedisService4 redisService4;
    @Autowired
    RedisService5 redisService5;

    @ApiOperation(value = "工具分页查询")
    @ResponseBody
    @RequestMapping(value = "/toolsPageList", method = RequestMethod.POST)
    public BaseOutput<PageOutput<Tools>> toolsPageList(HttpServletRequest request, @RequestBody ToolsPageInput input) {
        User user = UserUtils.getUser(request);
        log.info("【toolsPageList】input" + JSONObject.toJSONString(input));
        QueryWrapper<Tools> wrapper = WrapperUtils.getWrapper(false);
        PageOutput<Tools> output = new PageOutput<Tools>();
        wrapper = WrapperUtils.beanToWrapper(wrapper, input);
        Page<Tools> pageList = new Page<Tools>(input.getPage(), input.getRows());
        List<Tools> toolsList = toolsService.page(pageList, wrapper).getRecords();
        for (Tools tools:toolsList
             ) {
            if(tools.getModifyId()==0){
                tools.setModifyTime(null);
            }
        }
        output.setPage(pageList.getCurrent());
        output.setRecords(pageList.getTotal());
        output.setTotal(pageList.getPages());
        output.setRows(toolsList);
        return ResultResponseBeanUtil.success(output);
    }


    @ApiOperation(value = "增加/修改工具信息")
    @ResponseBody
    @AvoidRepeatSubmit
    @RequestMapping(value = "/addOrUpdateTools", method = RequestMethod.POST)
    public BaseOutput<String> addOrUpdateTools(HttpServletRequest request, @RequestBody ToolsInsert input) {
        User user = UserUtils.getUser(request);
        if (input.getDistrictId() == null || input.getDistrictId()==0) {
            return ResultResponseBeanUtil.fail("请选择站点");
        }
//        log.info("【addOrUpdateTools】User:" +user.getName()+",参数："+ JSONObject.toJSONString(input));
        if (input.getId() != null) {
            Tools curTools = toolsService.getById(input.getId());



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

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

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

                nameModifyNotice.setId(input.getId());
                nameModifyNotice.setLevel(1);
                nameModifyNotice.setNewName(input.getName());
                nameModifyNotice.setOldName(curTools.getName());
                nameModifyNotice.setType(5);
                nameModifyNotice.setClassName("Tools");
                // 更新名称
                curTools.setName(input.getName());
            }
            curTools.setStatus(input.getStatus());
            curTools.setMemo(input.getMemo()!=null?input.getMemo():"");
            toolsService.updateById(curTools);
            //防止修改失败
            if (nameModifyNotice != null) {
                redisService4.lPush("NameModifyNotice", JSON.toJSONString(nameModifyNotice));
            }
            return ResultResponseBeanUtil.success("修改成功");

        } else {
            QueryWrapper<Tools> wrapper = WrapperUtils.getWrapper(false);
            wrapper.eq("district_id", input.getDistrictId());
            wrapper.eq("name", input.getName());
            int count = toolsService.count(wrapper);
            if (count > 0) {
                return ResultResponseBeanUtil.fail("记录已存在，请修改后再提交");
            }
            Tools tools = new Tools();
            BeanUtils.copyProperties(input, tools);

            tools.setId(null);
            District district = districtService.getById(input.getDistrictId());
            String agentName = redisService5.get("name:Agent:" + district.getAgentId());
            String propertyName = redisService5.get("name:Properyt:" + district.getPropertyId());
            tools.setAgentId(district.getAgentId());
            tools.setAgentName(agentName);
            tools.setPropertyId(district.getPropertyId());
            tools.setPropertyName(propertyName);
            tools.setDistrictName(district.getDistrictName());
            toolsService.save(tools);
            return ResultResponseBeanUtil.success("添加成功");

        }

    }


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

//        log.info("【addOrUpdateTools】User:" +user.getName()+",参数："+ JSONObject.toJSONString(input));
        if (input.getId() != null) {
            Tools curTools = toolsService.getById(input.getId());
            if(curTools.getLevel()==1){
                QueryWrapper<Tools> wrapper = WrapperUtils.getWrapper(false);
                wrapper.eq("parent_id", input.getId());
                int count = toolsService.count(wrapper);
                if(count>0){
                    return ResultResponseBeanUtil.fail("存在二级工具，不允许删除");
                }
            }
            if (curTools != null) {
                curTools.setSoftDelete(1);
                toolsService.updateById(curTools);
                DeleteEntityNotice deleteEntityNotice = new DeleteEntityNotice();
                deleteEntityNotice.setId(curTools.getId());
                deleteEntityNotice.setType(5);
                deleteEntityNotice.setMemo(curTools.getName());
                redisService4.lPush("DeleteEntityNotice", JSON.toJSONString(deleteEntityNotice));
            } else {
                return ResultResponseBeanUtil.fail("当前工具未找到");
            }
        }
        return ResultResponseBeanUtil.success("删除成功");

    }


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

//        Boolean aBoolean = authorityService.checkAuthorityIsagent(user.getAuthorityId());
//        wrapper = WrapperUtils.getByIsAgent(aBoolean, user.getAgentId(), wrapper);
        wrapper = WrapperUtils.beanToWrapper(wrapper, input);
        List<Tools> toolsList = toolsService.list(wrapper);
        List<ToolsExport> newList = new ArrayList<ToolsExport>();
        ArrayList<String> strings = new ArrayList<>();

        String[] columns = new String[strings.size()];
        strings.toArray(columns);

//        String[] columns = (String[]) strings.toArray();
        for (Tools tools : toolsList) {
            ToolsExport toolsExport = new ToolsExport();
            BeanUtils.copyProperties(tools, toolsExport);


            if (tools.getStatus() == 0) {
                toolsExport.setStatusString("停用");
            } else if (tools.getStatus() == 1) {
                toolsExport.setStatusString("启用");
            }
            toolsExport.setLevelString(tools.getLevel() + "级");

            newList.add(toolsExport);
        }
        String formattedDate = DateToConverter.getFormattedDate(new Date(), 10);
        ExcelUtil<ToolsExport> util = new ExcelUtil<ToolsExport>(ToolsExport.class);
        util.exportExcelByColumns(response, newList, "工具数据列表记录" + formattedDate, columns);
    }

}
