package com.softwarebr.nunu.web.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.brframework.commoncms.annatotion.layout.EditAlertLayout;
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.brframework.commonwebadmin.aop.annotation.AOLog;
import com.softwarebr.nunu.domain.HotDemand;
import com.softwarebr.nunu.domain.InviteJob;
import com.softwarebr.nunu.dto.res.InviteParamDTO;
import com.softwarebr.nunu.dto.res.ProjectParamDTO;
import com.softwarebr.nunu.dto.res.PropertyParamDTO;
import com.softwarebr.nunu.dto.res.TalentParamDTO;
import com.softwarebr.nunu.entity.res.*;
import com.softwarebr.nunu.globals.SystemConst;
import com.softwarebr.nunu.json.admin.res.TalentDetailsResult;
import com.softwarebr.nunu.json.admin.res.TalentParam;
import com.softwarebr.nunu.json.admin.res.TalentResult;
import com.softwarebr.nunu.json.api.VerifyResult;
import com.softwarebr.nunu.json.api.center.*;
import com.softwarebr.nunu.service.SearchService;
import com.softwarebr.nunu.service.oper.AreaService;
import com.softwarebr.nunu.service.res.*;
import com.softwarebr.nunu.service.user.MemberService;
import com.softwarebr.nunu.util.AmountConversionUtil;
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.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

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

/**
 * @author lilin
 * @date 2020-02-21 11:49:00
 */

@RestController
@Api(tags = "创新资源交易区")
@RequestMapping("/api")
public class ApiResController {

    @Autowired
    private PropertyService propertyService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private InviteService inviteService;

    @Autowired
    private PropertyApplyService propertyApplyService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private SearchService searchService;

    @Autowired
    private TalentService talentService;

    @ApiOperation(value = "我的项目需求列表")
    @GetMapping("access/v1/center/request/project/page")
    public JSONResult<Page<ApiProjectResult>> requestProjectPageV1(PageParam page, ApiProjectQueryParam param) {
        param.setPublisher(Long.valueOf(SecurityContextHolder.getSubject().getId()));
        param.setMarker(SystemConst.MARKER_STATUS_NO);
        Page<ApiProjectResult> projectResultPage = ControllerPageHandle.jpaPageConvertToPage(projectService.page(page, param), page, ApiProjectResult.class);
        if (projectResultPage.getList().size() > 0) {
            Map<Integer, String> typeMap = projectService.typeMap();
            Map<Integer, String> statusMap = projectService.statusMap();
            projectResultPage.getList().forEach(r -> {
                r.setStatusName(statusMap.get(r.getStatus()));
                r.setTypeName(typeMap.get(r.getType()));
                r.setPrice(AmountConversionUtil.out(r.getPrice()));
            });
        }

        return JSONResult.ok(projectResultPage);
    }

    @ApiOperation(value = "我的招聘资源列表")
    @GetMapping("access/v1/center/request/invite/page")
    public JSONResult<Page<InviteResult>> requestInvitePageV1(PageParam page, InviteQueryParam param) {
        param.setPublisher(Long.valueOf(SecurityContextHolder.getSubject().getId()));
        param.setMarker(SystemConst.MARKER_STATUS_NO);
        Page<InviteResult> inviteResultPage = ControllerPageHandle.jpaPageConvertToPage(inviteService.page(page, param), page, InviteResult.class);
        for (InviteResult inviteResult : inviteResultPage.getList()) {
            inviteResult.setAddress(areaService.addressSplicing(inviteResult.getProvinceId(), inviteResult.getCityId(), inviteResult.getAreaId()));
            inviteResult.setJobs(JSONArray.parseArray(inviteResult.getJob(), InviteJob.class));
        }
        return JSONResult.ok(inviteResultPage);
    }

    @ApiOperation(value = "我的载体资源列表")
    @GetMapping("access/v1/center/request/property/page")
    public JSONResult<Page<PropertyResult>> requestPropertyPageV1(PageParam page, PropertyQueryParam param) {
        param.setMarker(SystemConst.MARKER_STATUS_NO);
        param.setPublisher(Long.valueOf(SecurityContextHolder.getSubject().getId()));
        Page<PropertyResult> propertyResultPage = ControllerPageHandle.jpaPageConvertToPage(propertyService.page(page, param), page, PropertyResult.class);
        for (PropertyResult propertyResult : propertyResultPage.getList()) {
            propertyResult.setPrice(AmountConversionUtil.out(propertyResult.getPrice()));
            propertyResult.setAddress(areaService.addressSplicing(propertyResult.getProvinceId(), propertyResult.getCityId(), propertyResult.getAreaId(), propertyResult.getStreetId()));
        }
        return JSONResult.ok(propertyResultPage);
    }

    @ApiOperation(value = "我的人才库简历列表")
    @GetMapping("access/v1/center/request/talent/page")
    public JSONResult<Page<TalentResult>> requestTalentPageV1(PageParam page, TalentQueryParam param) {
        param.setMarker(SystemConst.MARKER_STATUS_NO);
        param.setPublisher(Long.valueOf(SecurityContextHolder.getSubject().getId()));
        Page<TalentResult> talentResultPage = ControllerPageHandle.jpaPageConvertToPage(talentService.page(page, param), page, TalentResult.class);
        for (TalentResult talentResult : talentResultPage.getList()) {
            talentResult.setVerifyTitle(SystemConst.verifyHandle(talentResult.getVerify()));
            talentResult.setUpperTitle(SystemConst.statusUpperHandle(talentResult.getUpperStatus()));
            talentResult.setPublicityTitle(SystemConst.publicityHandle(talentResult.getPublicity()));
        }
        return JSONResult.ok(talentResultPage);
    }

    @ApiOperation(value = "修改项目需求对接状态")
    @PostMapping("access/v1/center/request/project/{projectId}")
    public JSONResult requestProjectUpdateV1(@PathVariable Long projectId, @Valid @RequestBody ProjectStatusParam param) {
        projectService.updateStatus(projectId, param.getStatus());
        return JSONResult.ok();
    }

    @ApiOperation(value = "修改载体资源状态")
    @PostMapping("access/v1/center/request/property/{propertyId}")
    public JSONResult requestPropertyUpdateV1(@ApiParam("载体资源ID") @PathVariable Long propertyId, @Valid @RequestBody PropertyStatusParam param) {
        propertyService.updateStatus(propertyId, param.getStatus());
        return JSONResult.ok();
    }

    @ApiOperation(value = "创新资源交易区列表")
    @GetMapping("access/v1/center/request/res/project/page")
    public JSONResult<Page<ApiProjectResult>> resProjectPageV1(PageParam page, ResProjectQueryParam param) {
        param.setMarker(SystemConst.MARKER_STATUS_NO);
        param.setUpperStatus(SystemConst.STATUS_UPPER_SHELF);
        if (StringUtils.isNotEmpty(param.getProjectName())) {
            searchService.increasingScore(param.getProjectName());
        }
        Page<ApiProjectResult> projectResultPage = ControllerPageHandle.jpaPageConvertToPage(projectService.pageV1(page, param), page, ApiProjectResult.class);
        Map<Integer, String> typeMap = projectService.typeMap();
        Map<Integer, String> statusMap = projectService.statusMap();
        for (ApiProjectResult projectResult : projectResultPage.getList()) {
            projectResult.setStatusName(statusMap.get(projectResult.getStatus()));
            projectResult.setTypeName(typeMap.get(projectResult.getType()));
            projectResult.setPrice(AmountConversionUtil.out(projectResult.getPrice()));
        }
        return JSONResult.ok(projectResultPage);
    }

    @ApiOperation(value = "首页->创新资源交易区")
    @GetMapping("v1/center/request/index/project/page")
    public JSONResult<Page<ApiProjectResult>> indexProjectPageV1(PageParam page) {
        ResProjectQueryParam param = new ResProjectQueryParam();
        param.setMarker(SystemConst.MARKER_STATUS_NO);
        param.setUpperStatus(SystemConst.STATUS_UPPER_SHELF);
        param.setIndexType(SystemConst.INDEX_TYPE_YES);
        Page<ApiProjectResult> projectResultPage = ControllerPageHandle.jpaPageConvertToPage(projectService.page(page, param), page, ApiProjectResult.class);
        Map<Integer, String> typeMap = projectService.typeMap();
        Map<Integer, String> statusMap = projectService.statusMap();
        for (ApiProjectResult projectResult : projectResultPage.getList()) {
            projectResult.setStatusName(statusMap.get(projectResult.getStatus()));
            projectResult.setTypeName(typeMap.get(projectResult.getType()));
            projectResult.setPrice(AmountConversionUtil.out(projectResult.getPrice()));
        }
        return JSONResult.ok(projectResultPage);
    }

    @ApiOperation(value = "项目资源详情")
    @GetMapping("access/v1/center/request/project/details/{id}")
    public JSONResult<ProjectDetailsResult> projectDetailsV1(@ApiParam("项目资源Id") @PathVariable Long id) {
        Long memberId = Long.valueOf(SecurityContextHolder.getSubject().getId());
        Map<Integer, String> typeMap = projectService.typeMap();
        Map<Integer, String> statusMap = projectService.statusMap();
        ProjectDetailsResult detailsResult = projectService.getProjectDetails(id, memberId);
        detailsResult.setStatusName(statusMap.get(detailsResult.getStatus()));
        detailsResult.setTypeName(typeMap.get(detailsResult.getType()));
        detailsResult.setPrice(AmountConversionUtil.out(detailsResult.getPrice()));
        return JSONResult.ok(detailsResult);
    }

    @ApiOperation(value = "载体资源列表")
    @GetMapping("access/v1/center/request/res/property/page")
    public JSONResult<Page<PropertyResult>> propertyPageV1(PageParam page, ResPropertyQueryParam param) {
        param.setMarker(SystemConst.MARKER_STATUS_NO);
        param.setUpperStatus(SystemConst.STATUS_UPPER_SHELF);
        if (StringUtils.isNotEmpty(param.getName())) {
            searchService.increasingScore(param.getName());
        }
        Page<PropertyResult> propertyResultPage = ControllerPageHandle.jpaPageConvertToPage(propertyService.page(page, param), page, PropertyResult.class);
        for (PropertyResult propertyResult : propertyResultPage.getList()) {
            propertyResult.setPrice(AmountConversionUtil.out(propertyResult.getPrice()));
            propertyResult.setAddress(areaService.addressSplicing(propertyResult.getProvinceId(), propertyResult.getCityId(), propertyResult.getAreaId(), propertyResult.getStreetId()));
        }
        return JSONResult.ok(propertyResultPage);
    }

    @ApiOperation(value = "载体资源详情")
    @GetMapping("access/v1/center/request/property/details/{id}")
    public JSONResult<PropertyDetailsResult> propertyDetailsV1(@ApiParam("载体资源Id") @PathVariable Long id) {
        Long memberId = Long.valueOf(SecurityContextHolder.getSubject().getId());
        PropertyDetailsResult detailsResult = propertyService.getPropertyDetails(id, memberId);
        detailsResult.setPrice(AmountConversionUtil.out(detailsResult.getPrice()));
        detailsResult.setAddress(areaService.addressSplicing(detailsResult.getProvinceId(), detailsResult.getCityId(), detailsResult.getAreaId(), detailsResult.getStreetId()));
        return JSONResult.ok(detailsResult);
    }

    @ApiOperation(value = "需求发布->申请信息")
    @GetMapping("access/v1/center/request/property/apply/page")
    public JSONResult<Page<PropertyApplyResult>> propertyApplyPageV1(PageParam page, PropertyApplyQueryParam param) {
        Long memberId = Long.valueOf(SecurityContextHolder.getSubject().getId());
        param.setPublisher(memberId);
        Page<PropertyApplyResult> propertyApplyResult = ControllerPageHandle.jpaPageConvertToPage(propertyApplyService.page(page, param), page, PropertyApplyResult.class);
        for (PropertyApplyResult applyResult : propertyApplyResult.getList()) {
            applyResult.setAccount(memberService.accessObject(applyResult.getProposer()).getPhone());
        }
        return JSONResult.ok(propertyApplyResult);
    }

    @ApiOperation(value = "需求发布->申请信息->操作")
    @PostMapping("access/v1/hall/property/apply/{id}")
    public JSONResult propertyApplyV1(@ApiParam("申请id") @PathVariable Long id, @Valid @RequestBody PropertyApplyVerifyParam param) {
        PropertyApply propertyApply = propertyApplyService.accessObject(id);
        propertyApply.setVerify(param.getVerify());
        propertyApplyService.save(propertyApply);
        return JSONResult.ok();
    }

    @ApiOperation(value = "招聘资源详情")
    @GetMapping("access/v1/center/request/invite/details/{id}")
    public JSONResult<InviteDetailsResult> inviteDetailsV1(@ApiParam("招聘资源Id") @PathVariable Long id) {
        Long memberId = Long.valueOf(SecurityContextHolder.getSubject().getId());
        InviteDetailsResult inviteDetails = inviteService.getInviteDetails(id, memberId);
        inviteDetails.setAddress(areaService.addressSplicing(inviteDetails.getProvinceId(), inviteDetails.getCityId(), inviteDetails.getAreaId()));
        inviteDetails.setJobs(JSONArray.parseArray(inviteDetails.getJob(), InviteJob.class));
        return JSONResult.ok(inviteDetails);
    }

    @ApiOperation(value = "联系项目申请")
    @PutMapping("access/v1/center/request/property/apply")
    public JSONResult propertyApplyV1(@Valid @RequestBody PropertyApplyParam param) {
        Long memberId = Long.valueOf(SecurityContextHolder.getSubject().getId());
        propertyApplyService.saveProperApply(param.getResourceType(), param.getTargetId(), memberId, param.getReason());
        return JSONResult.ok();
    }

    @ApiOperation(value = "热门需求创建")
    @PutMapping("access/v1/center/request/hot/demand")
    public JSONResult hotDemandV1(@Valid @RequestBody HotDemand param) {
        propertyApplyService.hotItemCreate(param);
        return JSONResult.ok();
    }

    @ApiOperation(value = "热门需求列表")
    @GetMapping("access/v1/center/request/hot/demand")
    public JSONResult<List<HotDemandResult>> hotDemandListV1() {
        List<HotDemandResult> hotDemand = propertyApplyService.getHotDemand();
        for (HotDemandResult hotDemandResult : hotDemand) {
            if (null != hotDemandResult.getPrice()) {
                hotDemandResult.setPrice(AmountConversionUtil.out(hotDemandResult.getPrice()));
            }
        }
        return JSONResult.ok(hotDemand);
    }

    @ApiOperation(value = "需求发布-项目需求资源")
    @PutMapping("access/v1/center/request/project")
    public JSONResult<ApiProjectResult> projectCreateV1(@Valid @RequestBody ProjectParam param) {
        Long memberId = Long.valueOf(SecurityContextHolder.getSubject().getId());
        Project project = projectService.saveProject(memberId, convertTo(param, ProjectParamDTO.class));
        ApiProjectResult projectResult = ControllerPageHandle.convertTo(project, ApiProjectResult.class);
        return JSONResult.ok(projectResult);
    }

    @ApiOperation(value = "项目需求资源审核结果")
    @GetMapping("access/v1/center/request/project/result/{id}")
    public JSONResult<VerifyResult> projectVerifyV1(@ApiParam("项目id") @PathVariable Long id) {
        VerifyResult verifyResult = ControllerPageHandle.convertTo(projectService.accessObject(id), VerifyResult.class);
        return JSONResult.ok(verifyResult);
    }


    @ApiOperation(value = "需求发布-招聘资源")
    @PutMapping("access/v1/center/request/invite")
    public JSONResult<InviteResult> inviteCreateV1(@Valid @RequestBody InviteParam param) {
        Long memberId = Long.valueOf(SecurityContextHolder.getSubject().getId());
        InviteParamDTO inviteParamDTO = convertTo(param, InviteParamDTO.class);
        inviteParamDTO.setJobJson(JSON.toJSONString(param.getJob()));
        Invite invite = inviteService.saveInvite(memberId, inviteParamDTO);
        InviteResult inviteResult = ControllerPageHandle.convertTo(invite, InviteResult.class);
        return JSONResult.ok(inviteResult);
    }

    @ApiOperation(value = "招聘资源审核结果")
    @GetMapping("access/v1/center/request/invite/result/{id}")
    public JSONResult<VerifyResult> inviteVerifyV1(@ApiParam("招聘资源id") @PathVariable Long id) {
        VerifyResult verifyResult = ControllerPageHandle.convertTo(inviteService.accessObject(id), VerifyResult.class);
        return JSONResult.ok(verifyResult);
    }

    @ApiOperation(value = "需求发布-载体资源")
    @PutMapping("access/v1/center/request/property")
    public JSONResult<PropertyResult> propertyCreateV1(@Valid @RequestBody PropertyParam param) {
        Long memberId = Long.valueOf(SecurityContextHolder.getSubject().getId());
        Property property = propertyService.saveProperty(memberId, convertTo(param, PropertyParamDTO.class));
        PropertyResult propertyResult = ControllerPageHandle.convertTo(property, PropertyResult.class);
        return JSONResult.ok(propertyResult);
    }

    @ApiOperation(value = "载体资源审核结果")
    @GetMapping("access/v1/center/request/property/result/{id}")
    public JSONResult<VerifyResult> propertyVerifyV1(@ApiParam("载体资源id") @PathVariable Long id) {
        VerifyResult verifyResult = ControllerPageHandle.convertTo(propertyService.accessObject(id), VerifyResult.class);
        return JSONResult.ok(verifyResult);
    }

    @ApiOperation(value = "招聘资源列表")
    @GetMapping("access/v1/center/request/res/invite/page")
    public JSONResult<Page<InviteResult>> invitePageV1(PageParam page, ResInviteQueryParam param) {
        param.setMarker(SystemConst.MARKER_STATUS_NO);
        param.setUpperStatus(SystemConst.STATUS_UPPER_SHELF);
        if (StringUtils.isNotEmpty(param.getInviteName())) {
            searchService.increasingScore(param.getInviteName());
        }
        Page<InviteResult> inviteResultPage = ControllerPageHandle.jpaPageConvertToPage(inviteService.page(page, param), page, InviteResult.class);
        for (InviteResult inviteResult : inviteResultPage.getList()) {
            inviteResult.setAddress(areaService.addressSplicing(inviteResult.getProvinceId(), inviteResult.getCityId(), inviteResult.getAreaId()));
            inviteResult.setJobs(JSONArray.parseArray(inviteResult.getJob(), InviteJob.class));
        }
        return JSONResult.ok(inviteResultPage);
    }

    @ApiOperation(value = "人才库资源列表")
    @GetMapping("access/v1/center/request/res/talent/page")
    public JSONResult<Page<TalentResult>> talentPageV1(PageParam page, ResTalentQueryParam param) {
        param.setMarker(SystemConst.MARKER_STATUS_NO);
        param.setUpperStatus(SystemConst.STATUS_UPPER_SHELF);
        if (StringUtils.isNotEmpty(param.getExpertise())) {
            searchService.increasingScore(param.getExpertise());
        }
        Page<TalentResult> talentResultPage = ControllerPageHandle.jpaPageConvertToPage(talentService.page(page, param), page, TalentResult.class);
        for (TalentResult talentResult : talentResultPage.getList()) {
            talentResult.setAddress(areaService.addressSplicing(talentResult.getProvinceId(), talentResult.getCityId(), talentResult.getAreaId()));
        }
        return JSONResult.ok(talentResultPage);
    }

    @ApiOperation(value = "查看人才简历信息", notes = "查看简历信息", produces = "text/plain")
    @GetMapping("access/v1/center/request/talent/details/{id}")
    public JSONResult<TalentDetailsResult> getTalent(@ApiParam("简历Id")@PathVariable Long id) {
        Talent talent = talentService.accessObject(id);
        TalentDetailsResult talentDetailsResult = convertTo(talent, TalentDetailsResult.class);
        talentDetailsResult.setArea(areaService.accessObject(talent.getAreaId()).getCityName());
        talentDetailsResult.setCity(areaService.accessObject(talent.getCityId()).getCityName());
        talentDetailsResult.setProvince(areaService.accessObject(talent.getProvinceId()).getCityName());

        return JSONResult.ok(talentDetailsResult);
    }


    @ApiOperation(value = "需求发布-人才库简历")
    @PutMapping("access/v1/center/request/talent")
    public JSONResult<TalentDetailsResult> talentCreateV1(@Valid @RequestBody TalentParam param) {
        Long memberId = Long.valueOf(SecurityContextHolder.getSubject().getId());

        TalentParamDTO talentParamDTO = convertTo(param, TalentParamDTO.class);
        Talent talent = talentService.saveTalent(memberId, talentParamDTO);
        TalentDetailsResult talentResult = ControllerPageHandle.convertTo(talent, TalentDetailsResult.class);
        return JSONResult.ok(talentResult);
    }


    @ApiOperation(value = "修改需求发布-人才库简历")
    @PutMapping("access/v1/center/request/talentEditV1/{id}")
    public JSONResult<TalentResult>  talentEditV1(@PathVariable Long id, @Valid @RequestBody TalentParam param) {
        Long memberId = Long.valueOf(SecurityContextHolder.getSubject().getId());

        TalentParamDTO talentParamDTO = convertTo(param, TalentParamDTO.class);
        TalentResult talentResult = ControllerPageHandle.convertTo(talentService.updateTalent(id, talentParamDTO), TalentResult.class);
        return JSONResult.ok(talentResult);
    }

    @ApiOperation(value = "人才库简历资源审核结果")
    @GetMapping("access/v1/center/request/talent/result/{id}")
    public JSONResult<VerifyResult> talentVerifyV1(@ApiParam("简历Id") @PathVariable Long id) {
        VerifyResult verifyResult = ControllerPageHandle.convertTo(talentService.accessObject(id), VerifyResult.class);
        return JSONResult.ok(verifyResult);
    }

}