package com.jpsoft.shinestar.modules.base.controller;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.dao.InformationInfoDAO;
import com.jpsoft.shinestar.modules.base.dto.InformationInfoDTO;
import com.jpsoft.shinestar.modules.base.entity.InformationInfo;
import com.jpsoft.shinestar.modules.base.entity.PersonInfo;
import com.jpsoft.shinestar.modules.base.entity.PersonPopedom;
import com.jpsoft.shinestar.modules.base.service.InformationInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonPopedomService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/base/informationInfo")
public class InformationInfoController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private InformationInfoService informationInfoService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private PersonPopedomService personPopedomService;

    @ApiOperation(value="创建空记录")
    @GetMapping("create")
    public MessageResult<InformationInfo> create(){
        MessageResult<InformationInfo> msgResult = new MessageResult<>();

        InformationInfo informationInfo = new InformationInfo();

        msgResult.setData(informationInfo);
        msgResult.setResult(true);

        return msgResult;
    }

    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<InformationInfo> add(@RequestBody InformationInfo informationInfo,@RequestAttribute String subject){
        MessageResult<InformationInfo> msgResult = new MessageResult<>();

        try {
            informationInfo.setId(UUID.randomUUID().toString());
            informationInfo.setDelFlag(false);
            informationInfo.setCreateBy(subject);
            informationInfo.setCreateTime(new Date());
            informationInfo.setStatus("0");

            int affectCount = informationInfoService.insert(informationInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(informationInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库添加失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="获取信息")
    @GetMapping("edit/{id}")
    public MessageResult<InformationInfo> edit(@PathVariable("id") String id){
        MessageResult<InformationInfo> msgResult = new MessageResult<>();

        try {
            InformationInfo informationInfo = informationInfoService.get(id);

            if (informationInfo != null) {
                msgResult.setResult(true);
                msgResult.setData(informationInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="更新用户")
    @PostMapping("update")
    public MessageResult<InformationInfo> update(@RequestBody InformationInfo informationInfo,@RequestAttribute String subject){
        MessageResult<InformationInfo> msgResult = new MessageResult<>();

        try {
            Date now = new Date();
            informationInfo.setUpdateBy(subject);
            informationInfo.setUpdateTime(now);
            informationInfo.setStatus("1");
            informationInfo.setReturnTime(now);
            
            int affectCount = informationInfoService.update(informationInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(informationInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库更新失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

	@ApiOperation(value="删除")
    @PostMapping("delete/{id}")
    public MessageResult<Integer> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            InformationInfo informationInfo = informationInfoService.get(id);
            informationInfo.setDelFlag(true);
            informationInfo.setUpdateBy(subject);
            informationInfo.setUpdateTime(new Date());

            int affectCount = informationInfoService.update(informationInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value="批量删除")
    @PostMapping("batchDelete")
    public MessageResult<Integer> batchDelete(@RequestBody List<String> idList,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            for (String id : idList) {
                InformationInfo informationInfo = informationInfoService.get(id);
                informationInfo.setDelFlag(true);
                informationInfo.setUpdateBy(subject);
                informationInfo.setUpdateTime(new Date());

                affectCount += informationInfoService.update(informationInfo);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="结束")
    @PostMapping("finished/{id}")
    public MessageResult<Integer> finished(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            InformationInfo informationInfo = informationInfoService.get(id);
            informationInfo.setStatus("2");
            informationInfo.setUpdateBy(subject);
            informationInfo.setUpdateTime(new Date());

            int affectCount = informationInfoService.update(informationInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("结束失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            String name,String createTimeRanges,String status,
            @RequestParam(value="type",defaultValue="") String type,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);

        MessageResult<Map> msgResult = new MessageResult<>();

        try {

            Map<String, Object> searchParams = new HashMap<>();

            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("create_time", "desc"));

            if (StringUtils.isNotEmpty(name)) {
                searchParams.put("name", "%" + name + "%");
            }

            if (StringUtils.isNotEmpty(type)) {
                searchParams.put("type", type);
            }

            if (StringUtils.isNotEmpty(status)) {
                searchParams.put("status", status);
            }

            if (StringUtils.isNotEmpty(createTimeRanges)) {
                String[] timeRangeArray = createTimeRanges.split(",");
                String beginTime = "";
                String endTime = "";
                if (timeRangeArray.length == 1) {
                    beginTime = timeRangeArray[0];
                    beginTime += " 00:00:00";
                } else if (timeRangeArray.length == 2) {
                    beginTime = timeRangeArray[0];
                    endTime = timeRangeArray[1];
                    beginTime += " 00:00:00";
                    endTime += " 23:59:59";
                }

                searchParams.put("beginTime", beginTime);
                searchParams.put("endTime", endTime);
            }

            Page<InformationInfo> page = informationInfoService.pageSearch(searchParams, pageIndex, pageSize, sortList);

            Page<InformationInfoDTO> pageDto = new Page<>();

            for (InformationInfo informationInfo : page) {
                InformationInfoDTO informationInfoDTO = new InformationInfoDTO();

                informationInfoDTO.setId(informationInfo.getId());
                informationInfoDTO.setCommunity(informationInfo.getCommunity());
                informationInfoDTO.setContent(informationInfo.getContent());
                informationInfoDTO.setCreateTime(informationInfo.getCreateTime());
                informationInfoDTO.setStatus(informationInfo.getStatus());
                informationInfoDTO.setReturnContent(informationInfo.getReturnContent());
                informationInfoDTO.setReturnTime(informationInfo.getReturnTime());


                PersonPopedom personPopedom = personPopedomService.get(informationInfo.getPopedom());

                if(personPopedom!=null) {
                    PersonInfo personInfo = personInfoService.get(personPopedom.getPersonId());
                    if (personInfo != null) {
                        informationInfoDTO.setName(personInfo.getName());
                        informationInfoDTO.setPhone(personInfo.getPhone());
                    }
                }

                pageDto.add(informationInfoDTO);
            }

            pageDto.setPageSize(page.getPageSize());
            pageDto.setTotal(page.getTotal());
            pageDto.setPageNum(page.getPageNum());


            msgResult.setResult(true);
            msgResult.setData(PojoUtils.pageWrapper(pageDto));

        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @PostMapping(value="addMobile")
    @ApiImplicitParams({
            @ApiImplicitParam(name="content",value="内容",dataType="string",paramType = "query"),
            @ApiImplicitParam(name="type",value="类型/1投诉/2报修",dataType="string",paramType = "query")
    })
    public MessageResult<InformationInfo> addMobile(
            String ownerId,
            String content,
            String type,
            @RequestAttribute String subject){
        MessageResult<InformationInfo> msgResult = new MessageResult<>();
        InformationInfo informationInfo = new InformationInfo();
        try {
            informationInfo.setId(UUID.randomUUID().toString());
            informationInfo.setDelFlag(false);
            informationInfo.setCreateBy(ownerId);
            informationInfo.setCreateTime(new Date());
            informationInfo.setStatus("0");
            informationInfo.setContent(content);

            PersonInfo personInfo = personInfoService.get(Long.parseLong(subject));

            informationInfo.setPopedom(personInfo.getPopedom());
            informationInfo.setType(type);
            informationInfo.setCommunity("1-2-1601");

            int affectCount = informationInfoService.insert(informationInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(informationInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库添加失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }
}
