package com.softwarebr.nunu.web.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.brframework.commondb.core.ControllerPageHandle;
import com.brframework.commonsecurity.core.SecurityContextHolder;
import com.brframework.commonweb.json.JSONResult;
import com.brframework.commonweb.json.Page;
import com.brframework.commonweb.json.PageParam;
import com.google.common.collect.Lists;
import com.softwarebr.nunu.domain.Attachments;
import com.softwarebr.nunu.domain.InvestInfo;
import com.softwarebr.nunu.dto.hall.InvestParamDTO;
import com.softwarebr.nunu.dto.hall.TeamParamDTO;
import com.softwarebr.nunu.dto.org.InvestOrgParamDTO;
import com.softwarebr.nunu.entity.hall.Invest;
import com.softwarebr.nunu.entity.hall.InvestOrg;
import com.softwarebr.nunu.globals.SystemConst;
import com.softwarebr.nunu.json.api.VerifyResult;
import com.softwarebr.nunu.json.api.hall.*;
import com.softwarebr.nunu.service.SearchService;
import com.softwarebr.nunu.service.hall.InvestApplyService;
import com.softwarebr.nunu.service.hall.InvestOrgService;
import com.softwarebr.nunu.service.hall.InvestService;
import com.softwarebr.nunu.service.hall.TeamService;
import com.softwarebr.nunu.service.oper.AreaService;
import com.softwarebr.nunu.service.user.MemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import static com.brframework.commondb.core.ControllerPageHandle.convertListTo;
import static com.brframework.commondb.core.ControllerPageHandle.convertTo;

/**
 * @author lilin
 * @date 2020-02-25 12:03:51
 */

@RestController
@Api(tags = "创新项目路演厅")
@RequestMapping("/api")
public class ApiHallController {

    @Autowired
    private InvestService investService;

    @Autowired
    private TeamService teamService;

    @Autowired
    private InvestApplyService investApplyService;

    @Autowired
    private InvestOrgService investOrgService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private SearchService searchService;


    @ApiOperation(value = "我的创新项目列表")
    @GetMapping("access/v1/center/invest/project/page")
    public JSONResult<Page<ApiInvestResult>> investProjectPageV1(PageParam page, ApiInvestQueryParam param) {
        param.setPublisher(Long.valueOf(SecurityContextHolder.getSubject().getId()));
        Page<ApiInvestResult> investResultPage = ControllerPageHandle.jpaPageConvertToPage(investService.page(page, param), page, ApiInvestResult.class);
        if (investResultPage.getList().size() > 0) {
            Map<Integer, String> investStateMap = investService.investStateMap();
            Map<Integer, String> industryMap = investService.industryMap();
            investResultPage.getList().forEach(r -> {
                r.setInvestStateName(investStateMap.get(r.getInvestState()));
                r.setIndustryName(industryMap.get(r.getIndustry()));
                r.setApplyNumber(investApplyService.countApplyNumber(r.getId()));
                r.setArea(areaService.accessObject(r.getAreaId()).getCityName());
                r.setCity(areaService.accessObject(r.getCityId()).getCityName());
                r.setProvince(areaService.accessObject(r.getProvinceId()).getCityName());
            });
        }

        return JSONResult.ok(investResultPage);
    }

    @ApiOperation(value = "创新项目路演厅->首页")
    @GetMapping("v1/hall/invest/index/page")
    public JSONResult<Page<ApiInvestResult>> indexInvestPageV1(PageParam page) {
        ApiInvestQueryParam param = new ApiInvestQueryParam();
        param.setIndexType(SystemConst.INDEX_TYPE_YES);
        Page<ApiInvestResult> investResultPage = ControllerPageHandle.jpaPageConvertToPage(investService.page(page, param), page, ApiInvestResult.class);
        Map<Integer, String> investStateMap = investService.investStateMap();
        Map<Integer, String> industryMap = investService.industryMap();
        for(ApiInvestResult investResult : investResultPage.getList()){
            investResult.setIndustryName(industryMap.get(investResult.getIndustry()));
            investResult.setInvestStateName(investStateMap.get(investResult.getInvestState()));
            investResult.setProvince(areaService.accessObject(investResult.getProvinceId()).getCityName());
        }
        return JSONResult.ok(investResultPage);
    }

    @ApiOperation(value = "创新项目路演厅->项目展示")
    @GetMapping("access/v1/hall/invest/page")
    public JSONResult<Page<ApiInvestResult>> investPageV1(PageParam page, ApiInvestQueryParam param) {
        param.setUpperStatus(SystemConst.STATUS_UPPER_SHELF);
        if (StringUtils.isNotEmpty(param.getName())) {
            searchService.increasingScore(param.getName());
        }
        Page<ApiInvestResult> investResultPage = ControllerPageHandle.jpaPageConvertToPage(investService.page(page, param), page, ApiInvestResult.class);
        Map<Integer, String> investStateMap = investService.investStateMap();
        Map<Integer, String> industryMap = investService.industryMap();
        for(ApiInvestResult investResult : investResultPage.getList()){
            investResult.setIndustryName(industryMap.get(investResult.getIndustry()));
            investResult.setInvestStateName(investStateMap.get(investResult.getInvestState()));
            investResult.setCity(areaService.accessObject(investResult.getCityId()).getCityName());
        }
        return JSONResult.ok(investResultPage);
    }


    @ApiOperation(value = "创新项目路演厅->投资机构")
    @GetMapping("access/v1/hall/invest/org/page")
    public JSONResult<Page<InvestOrgResult>> investOrgPageV1(PageParam page, InvestOrgQueryParam param) {
        param.setStatus(SystemConst.STATUS_UPPER_SHELF);
        if (StringUtils.isNotEmpty(param.getCompanyName())) {
            searchService.increasingScore(param.getCompanyName());
        }
        Page<InvestOrgResult> investOrgResultPage = ControllerPageHandle.jpaPageConvertToPage(investOrgService.page(page, param), page, InvestOrgResult.class);
        return JSONResult.ok(investOrgResultPage);
    }

    @ApiOperation(value = "投资机构详情")
    @GetMapping("access/v1/hall/invest/org/details/{id}")
    public JSONResult<InvestOrgResult> investOrgDetailsV1(@ApiParam("投资机构Id") @PathVariable Long id) {
        InvestOrgResult investOrgResult = ControllerPageHandle.convertTo(investOrgService.accessObject(id), InvestOrgResult.class);
        investOrgResult.setInvests(JSONArray.parseArray(investOrgResult.getInvestInfos(), InvestInfo.class));
        return JSONResult.ok(investOrgResult);
    }


    @ApiOperation(value = "创新项目路演厅->项目入驻")
    @PutMapping("access/v1/hall/invest")
    public JSONResult<Invest> investCreateV1(@Valid @RequestBody InvestParam param) {
        Long memberId = Long.valueOf(SecurityContextHolder.getSubject().getId());
        InvestParamDTO investParamDTO = convertTo(param, InvestParamDTO.class);
        Invest invest = investService.saveInvest(memberId, investParamDTO, convertListTo(param.getTeams(), TeamParamDTO.class));
        return JSONResult.ok(invest);
    }

    @ApiOperation(value = "创新项目路演厅->项目入驻审核结果")
    @GetMapping("access/v1/hall/invest/result/{id}")
    public JSONResult<VerifyResult> investVerifyV1(@ApiParam("项目id") @PathVariable Long id) {
        VerifyResult verifyResult = ControllerPageHandle.convertTo(investService.accessObject(id), VerifyResult.class);
        return JSONResult.ok(verifyResult);
    }


    @ApiOperation(value = "个人中心->认证投资机构")
    @PutMapping("access/v1/hall/invest/org")
    public JSONResult<InvestOrg> investOrgCreateV1(@Valid @RequestBody InvestOrgParam param) {
        Long memberId = Long.valueOf(SecurityContextHolder.getSubject().getId());
        InvestOrg investOrg = investOrgService.saveInvestOrg(memberId, ControllerPageHandle.convertTo(param, InvestOrgParamDTO.class));
        return JSONResult.ok(investOrg);
    }

    @ApiOperation(value = "个人中心->投资机构认证结果")
    @GetMapping("access/v1/hall/invest/org/result")
    public JSONResult<VerifyResult> investOrgVerifyV1() {
        Long memberId = Long.valueOf(SecurityContextHolder.getSubject().getId());
        VerifyResult verifyResult = ControllerPageHandle.convertTo(investOrgService.getInvestOrgResult(memberId), VerifyResult.class);
        return JSONResult.ok(verifyResult);
    }


    @ApiOperation(value = "项目入驻->申请信息")
    @GetMapping("access/v1/hall/invest/apply/page")
    public JSONResult<Page<InvestApplyResult>> investApplyPageV1(PageParam page, InvestApplyQueryParam param) {
        Long memberId = Long.valueOf(SecurityContextHolder.getSubject().getId());
        param.setPublisher(memberId);
        Page<InvestApplyResult> investResultPage = ControllerPageHandle.jpaPageConvertToPage(investApplyService.page(page, param), page, InvestApplyResult.class);
        for (InvestApplyResult investApplyResult:investResultPage.getList()){
            investApplyResult.setAccount(memberService.accessObject(investApplyResult.getProposer()).getPhone());
        }
        return JSONResult.ok(investResultPage);
    }

    @ApiOperation(value = "项目入驻->申请信息->操作")
    @PostMapping("access/v1/hall/invest/apply/{id}")
    public JSONResult investApplyV1(@ApiParam("申请id") @PathVariable Long id, @Valid @RequestBody InvestApplyVerifyParam param) {
        List<Long> list = Lists.newArrayList();
        list.add(id);
        investApplyService.openInvestApply(list, param.getVerify(), SystemConst.AUDITOR_PUBLISHER);
        return JSONResult.ok();
    }

    @ApiOperation(value = "创新项目路演厅->入驻详情")
    @GetMapping("access/v1/hall/invest/details/{id}")
    public JSONResult<InvestDetailsResult> investDetailsV1(@ApiParam("创新项目Id")@PathVariable Long id) {
        Invest invest = investService.accessObject(id);
        InvestDetailsResult detailsResult = ControllerPageHandle.convertTo(invest, InvestDetailsResult.class);
        detailsResult.setDetailImagesUris(investService.detailImagesUrisHandle(invest.getDetailImagesUri()));
        detailsResult.setAttachments(JSON.parseArray(invest.getAttachment(), Attachments.class));
        investDetailsResultHandle(detailsResult);
        return JSONResult.ok(detailsResult);
    }

    @ApiOperation(value = "项目展示详情")
    @GetMapping("access/v1/hall/invest/display/details/{id}")
    public JSONResult<InvestDetailsResult> investDisplayDetailsV1(@ApiParam("创新项目Id")@PathVariable Long id) {
        Long memberId = Long.valueOf(SecurityContextHolder.getSubject().getId());
        InvestDetailsResult investDetails = investService.getInvestDetails(id, memberId);
        investDetailsResultHandle(investDetails);
        return JSONResult.ok(investDetails);
    }

    /**
     * 项目路演厅数据处理
     * @param investDetails
     */
    private void investDetailsResultHandle(InvestDetailsResult investDetails){
        Map<Integer, String> investStateMap = investService.investStateMap();
        Map<Integer, String> industryMap = investService.industryMap();
        investDetails.setTeamList(ControllerPageHandle.convertListTo(teamService.findTeamByInvestId(investDetails.getId()), ApiTeamResult.class));
        investDetails.setArea(areaService.accessObject(investDetails.getAreaId()).getCityName());
        investDetails.setCity(areaService.accessObject(investDetails.getCityId()).getCityName());
        investDetails.setProvince(areaService.accessObject(investDetails.getProvinceId()).getCityName());
        investDetails.setIndustryName(industryMap.get(investDetails.getIndustry()));
        investDetails.setInvestStateName(investStateMap.get(investDetails.getInvestState()));
    }

    @ApiOperation(value = "项目联系方式申请")
    @PutMapping("access/v1/hall/invest/contact/apply")
    public JSONResult investContactApplyV1(@Valid @RequestBody InvestApplyParam param) {
        Long memberId = Long.valueOf(SecurityContextHolder.getSubject().getId());
        investApplyService.investContactApply(memberId, param.getInvestId(), param.getReason());
        return JSONResult.ok();
    }

    @ApiOperation(value = "团队介绍详情")
    @GetMapping("access/v1/hall/invest/team/details/{id}")
    public JSONResult<ApiTeamResult> investTeamDetailsV1(@ApiParam("团队Id")@PathVariable Long id) {
        ApiTeamResult teamResult = ControllerPageHandle.convertTo(teamService.accessObject(id), ApiTeamResult.class);
        return JSONResult.ok(teamResult);
    }

    @ApiOperation(value = "文件地址转文件流")
    @GetMapping("v1/down/load/file")
    public void downLoadFileV1(String filePath, HttpServletResponse response) throws IOException {
        if (StringUtils.isNotBlank(filePath)) {
            investService.downLoadFile(filePath, response);
        }
    }

}