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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.dao.InformationInfoDAO;
import com.jpsoft.shinestar.modules.base.dto.InformationDTO;
import com.jpsoft.shinestar.modules.base.entity.CompanyInfo;
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.CompanyInfoService;
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 com.jpsoft.shinestar.modules.sys.entity.DataDictionary;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
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("/mobile/information")
public class InformationController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private InformationInfoService informationInfoService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private PersonPopedomService personPopedomService;

    @Autowired
    private CompanyInfoService companyInfoService;


    @ApiOperation(value="业主列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "type", value = "1:投诉建议，2：报事报修", paramType = "form"),
            @ApiImplicitParam(name = "status", value = "状态（/0待处理/1已处理）", paramType = "form"),
    })
    public MessageResult<Map> pageList(
            String token,
            @RequestParam(value="type",defaultValue="") String type,
            @RequestParam(value="status",defaultValue="") String status,
            @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(type)) {
                searchParams.put("type",type);
            }

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

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

            searchParams.put("popedom",personInfo.getPopedom());

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

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

            for (InformationInfo informationInfo:page) {
                InformationDTO informationDTO = new InformationDTO();

                informationDTO.setId(informationInfo.getId());

                informationDTO.setCreateTime(informationInfo.getCreateTime());

                informationDTO.setStatus(informationInfo.getStatus());

                informationDTO.setContent(informationInfo.getContent());

                informationDTO.setReturnContent(informationInfo.getReturnContent());
                informationDTO.setReturnTime(informationInfo.getReturnTime());
                informationDTO.setImg(informationInfo.getImg());
                informationDTO.setCategory(informationInfo.getCategory());


                List<DataDictionary> list;

                if(informationInfo.getType().equals("1")){
                    list = dataDictionaryService.findByCatalogName("投诉建议");
                }
                else{
                    list = dataDictionaryService.findByCatalogName("报事报修");
                }

                for (DataDictionary item:list) {
                    if(item.getValue().equals(informationInfo.getCategory())){
                        informationDTO.setCategoryN(item.getName());
                        break;
                    }
                }

                String statusN;

                if(type.equals("1")) {
                    if (informationInfo.getStatus().equals("0")) {
                        statusN = "待回复";
                    } else if (informationInfo.getStatus().equals("1")) {
                        statusN = "已回复";
                    } else {
                        statusN = "已结束";
                    }
                }
                else{
                    if (informationInfo.getStatus().equals("0")) {
                        statusN = "待解决";
                    } else if (informationInfo.getStatus().equals("1")) {
                        statusN = "已解决";
                    } else {
                        statusN = "已结束";
                    }
                }

                informationDTO.setStatusN(statusN);
                pageDto.add(informationDTO);
            }

            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);
        }

        return msgResult;
    }


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

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

            InformationDTO informationDTO = new InformationDTO();

            if(informationInfo!=null){

                informationDTO.setId(informationInfo.getId());

                informationDTO.setCreateTime(informationInfo.getCreateTime());

                informationDTO.setStatus(informationInfo.getStatus());

                informationDTO.setCommunity(informationInfo.getCommunity());

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

                PersonInfo personInfo = personInfoService.get(personPopedom.getPersonId());

                if(personInfo!=null) {
                    informationDTO.setName(personInfo.getName());
                    informationDTO.setPhone(personInfo.getPhone());
                }

                String statusN;

                if(informationInfo.getStatus().equals("0")){
                    statusN="待回复";
                }
                else if(informationInfo.getStatus().equals("1")){
                    statusN="已回复";
                }
                else{
                    statusN="已结束";
                }

                informationDTO.setStatusN(statusN);

                informationDTO.setContent(informationInfo.getContent());

                informationDTO.setReturnContent(informationInfo.getReturnContent());

                informationDTO.setReturnTime(informationInfo.getReturnTime());

                informationDTO.setImg(informationInfo.getImg());
                informationDTO.setCategory(informationInfo.getCategory());

                List<DataDictionary> list;

                if(informationInfo.getType().equals("1")){
                    list = dataDictionaryService.findByCatalogName("投诉建议");
                }
                else{
                    list = dataDictionaryService.findByCatalogName("报事报修");
                }

                for (DataDictionary item:list) {
                    if(item.getValue().equals(informationInfo.getCategory())){
                        informationDTO.setCategoryN(item.getName());
                        break;
                    }
                }
            }

            if (informationInfo != null) {
                msgResult.setResult(true);
                msgResult.setData(informationDTO);
            } 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("add")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "content", value = "内容", paramType = "form"),
            @ApiImplicitParam(name = "type", value = "1:投诉建议，2：报事报修", paramType = "form"),
    })
    public MessageResult<InformationInfo> add(String content,String type,String img,int category,String token,@RequestAttribute String subject){
        MessageResult<InformationInfo> msgResult = new MessageResult<>();

        try {
            InformationInfo informationInfo = new InformationInfo();

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

            informationInfo.setId(UUID.randomUUID().toString());
            informationInfo.setDelFlag(false);
            informationInfo.setCreateBy(subject);
            informationInfo.setPopedom(personInfo.getPopedom());
            informationInfo.setPersonId(Long.parseLong(subject));
            informationInfo.setCompanyId(personInfo.getCompanyId());
            informationInfo.setCreateTime(new Date());
            informationInfo.setStatus("0");
            informationInfo.setContent(content);
            informationInfo.setType(type);
            informationInfo.setImg(img);
            informationInfo.setCategory(category);

            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="物业投诉建议及报事报修查看列表")
    @RequestMapping(value = "propertyPageList",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "type", value = "1:投诉建议，2：报事报修", paramType = "form"),
            @ApiImplicitParam(name = "status", value = "状态（/0待处理/1已处理）", paramType = "form"),
    })
    public MessageResult<Map> propertyPageList(
            String token,
            @RequestParam(value="type",defaultValue="") String type,
            @RequestParam(value="status",defaultValue="") String status,
            @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(type)) {
                searchParams.put("type",type);
            }

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

            List<CompanyInfo> companyList = companyInfoService.findByRelationCompanyId(personInfo.getCompanyId());

            List<CompanyInfo> companyListTotal = new ArrayList<>();

            for (CompanyInfo companyInfo:companyList) {
                List<CompanyInfo> companyInfos = companyInfoService.findAllCompanyByCode("%"+companyInfo.getId()+"%");
                companyListTotal.addAll(companyInfos);
            }

            if (companyList.size()>0) {
                searchParams.put("companyList",companyListTotal);
            }

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

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

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

            for (InformationInfo informationInfo:page) {
                InformationDTO informationDTO = new InformationDTO();

                informationDTO.setId(informationInfo.getId());

                informationDTO.setCreateTime(informationInfo.getCreateTime());

                informationDTO.setStatus(informationInfo.getStatus());

                informationDTO.setContent(informationInfo.getContent());

                informationDTO.setReturnContent(informationInfo.getReturnContent());
                informationDTO.setReturnTime(informationInfo.getReturnTime());

                informationDTO.setCommunity(informationInfo.getCommunity());

                informationDTO.setImg(informationInfo.getImg());
                informationDTO.setCategory(informationInfo.getCategory());

                List<DataDictionary> list;

                if(informationInfo.getType().equals("1")){
                    list = dataDictionaryService.findByCatalogName("投诉建议");
                }
                else{
                    list = dataDictionaryService.findByCatalogName("报事报修");
                }

                for (DataDictionary item:list) {
                    if(item.getValue().equals(informationInfo.getCategory())){
                        informationDTO.setCategoryN(item.getName());
                        break;
                    }
                }

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

                PersonInfo person = personInfoService.get(personPopedom.getPersonId());

                if(person!=null) {
                    informationDTO.setName(person.getName());
                    informationDTO.setPhone(person.getPhone());
                }

                String statusN;

                if(type.equals("1")) {
                    if (informationInfo.getStatus().equals("0")) {
                        statusN = "待回复";
                    } else if (informationInfo.getStatus().equals("1")) {
                        statusN = "已回复";
                    } else {
                        statusN = "已结束";
                    }
                }
                else{
                    if (informationInfo.getStatus().equals("0")) {
                        statusN = "待解决";
                    } else if (informationInfo.getStatus().equals("1")) {
                        statusN = "已解决";
                    } else {
                        statusN = "已结束";
                    }
                }

                informationDTO.setStatusN(statusN);
                pageDto.add(informationDTO);
            }

            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);
        }

        return msgResult;
    }


    @ApiOperation(value="回复解决方案")
    @PostMapping("update")
    public MessageResult<InformationInfo> update(String id,String content,@RequestAttribute String subject){
        MessageResult<InformationInfo> msgResult = new MessageResult<>();

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

            Date now = new Date();
            informationInfo.setUpdateBy(subject);
            informationInfo.setUpdateTime(now);
            informationInfo.setStatus("1");
            informationInfo.setReturnTime(now);
            informationInfo.setReturnContent(content);

            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="物业投诉建及报事报修类别列表")
    @RequestMapping(value = "categoryList",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "type", value = "1:投诉建议，2：报事报修", paramType = "form"),
    })
    public MessageResult<List<Map<String,String>>> categoryList(String type,String token){

        MessageResult<List<Map<String,String>>> msgResult = new MessageResult<>();

        List<Map<String,String>> mapList = new ArrayList<>();

        List<DataDictionary> list;

        if(type.equals("1")){
            list = dataDictionaryService.findByCatalogName("投诉建议");
        }
        else{
            list = dataDictionaryService.findByCatalogName("报事报修");
        }

        for (DataDictionary item:list) {
            Map<String,String> map = new HashMap<>();
            map.put("value",item.getValue());
            map.put("name",item.getName());
            mapList.add(map);
        }

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

        return msgResult;
    }

    @ApiOperation(value="撤销")
    @PostMapping("cancel")
    public MessageResult<Integer> cancel(String id,String token,@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;
    }
}
