package com.softwarebr.nunu.web.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.brframework.common.utils.ConvertObjectUtil;
import com.brframework.commoncms.annatotion.AdminMenu;
import com.brframework.commoncms.annatotion.layout.EditAlertLayout;
import com.brframework.commoncms.annatotion.layout.EditLayout;
import com.brframework.commoncms.annatotion.layout.PageLayout;
import com.brframework.commoncms.annatotion.option.CmsOption;
import com.brframework.commoncms.core.Icons;
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.Attachments;
import com.softwarebr.nunu.domain.VerifyPageTotal;
import com.softwarebr.nunu.dto.hall.InvestParamDTO;
import com.softwarebr.nunu.dto.hall.TeamParamDTO;
import com.softwarebr.nunu.entity.hall.Invest;
import com.softwarebr.nunu.entity.hall.Team;
import com.softwarebr.nunu.globals.SystemConst;
import com.softwarebr.nunu.json.admin.hall.*;
import com.softwarebr.nunu.service.hall.InvestApplyService;
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 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.Arrays;
import java.util.List;

import static com.brframework.commondb.core.ControllerPageHandle.*;

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

@RestController
@Api(tags = "创新项目路演厅管理")
@AdminMenu(menuName = "创新项目路演厅管理", icon = Icons.TABLE)
@RequestMapping("/admin/access")
public class AdminHallController {

	@Autowired
	private InvestService investService;

	@Autowired
	private MemberService memberService;

	@Autowired
	private TeamService teamService;

	@Autowired
	private InvestApplyService investApplyService;

	@Autowired
	private AreaService areaService;

	@ApiOperation(value = "创新项目列表", notes = "创新项目列表", produces = "text/plain")
	@GetMapping("/v1/invest/page")
	@AdminMenu(menuName = "创新项目路演厅管理", order = 1, url = "ProjectRoadshow")
	@PreAuthorize("hasRole('hall-invest-query')")
	@PageLayout(
			options = {
					@CmsOption(name = "添加", uriMappingMethod = "investCreateV1")
			},
			columnOptions = {
					@CmsOption(name = "查看", uriMappingMethod = "getInvest"),
					@CmsOption(name = "修改", uriMappingMethod = "investEditV1"),
					@CmsOption(name = "上架", uriMappingMethod = "investUpperV1"),
					@CmsOption(name = "下架", uriMappingMethod = "investLowerV1"),
					@CmsOption(name = "公开申请列表", uriMappingMethod = "investApplyListV1"),
					@CmsOption(name = "公开", uriMappingMethod = "investApplyOpenV1"),
					@CmsOption(name = "首页推荐", uriMappingMethod = "investIndexYesV1"),
					@CmsOption(name = "取消推荐", uriMappingMethod = "investEditV1"),
					@CmsOption(name = "审核", uriMappingMethod = "investVerifyV1")
			}
	)
	public JSONResult<Page<InvestResult>> investListV1(PageParam pageParam, InvestQueryParam param) {
		if (null != param.getAccount()) {
			param.setPublisher(memberService.findMemberIdByPhone(param.getAccount()));
		}
		if (null != param.getApplyStatus()) {
			param.setId(investApplyService.getAwaitVerifyInvestIds());
		}
		Page<InvestResult> page = jpaPageConvertToPage(investService.page(pageParam, param), pageParam, InvestResult.class);
		for (InvestResult investResult : page.getList()) {
			investResult.setIndustryTitle(investService.industryMap().get(investResult.getIndustry()));
			investResult.setInvestStateTitle(investService.investStateMap().get(investResult.getInvestState()));
			if (investResult.getPublisher() > 0) {
				investResult.setAccount(memberService.accessObject(investResult.getPublisher()).getPhone());
			} else {
				investResult.setAccount("平台");
			}
			investResult.setAddress(areaService.addressSplicing(investResult.getProvinceId(), investResult.getCityId(), investResult.getAreaId()));
			investResult.setStateTitle(investResult.getState().equals(1) ? "初创期" : "成长期");
			investResult.setHandleTotal(investResult.getPublicity().equals(SystemConst.PUBLICITY_PUBLIC) ? 0 :
					investApplyService.countInvestHandleTotal(investResult.getId()).intValue());
		}
		return JSONResult.ok(page);
	}

    @ApiOperation(value = "创新项目路演厅状态数据统计", notes = "创新项目路演厅状态数据统计", produces = "text/plain")
    @PreAuthorize("hasRole('hall-invest-query')")
    @GetMapping("/v1/invest/count")
    public JSONResult<VerifyPageTotal> getInvestCount(InvestQueryParam param) {
        VerifyPageTotal verifyPageResult = new VerifyPageTotal();
        if(null != param.getAccount()){
            param.setPublisher(memberService.findMemberIdByPhone(param.getAccount()));
        }
		if(null != param.getApplyStatus()){
			param.setId(investApplyService.getAwaitVerifyInvestIds());
		}
        verifyPageResult.setTotalCount(investService.count(param));
        param.setUpperStatus(SystemConst.STATUS_LOWER_SHELF);
        verifyPageResult.setLowerCount(investService.count(param));
        param.setUpperStatus(SystemConst.STATUS_UPPER_SHELF);
        verifyPageResult.setUpperCount(investService.count(param));
        param.setUpperStatus(null);
        param.setVerify(SystemConst.VERIFY_AWAIT);
        verifyPageResult.setVerifyAwaitCount(investService.count(param));
        param.setVerify(SystemConst.VERIFY_ADOPT);
        verifyPageResult.setVerifyAdoptCount(investService.count(param));
        param.setVerify(SystemConst.VERIFY_REJECT);
        verifyPageResult.setVerifyRejectCount(investService.count(param));
        return JSONResult.ok(verifyPageResult);
    }

	@ApiOperation(value = "修改创新项目信息", notes = "修改创新项目信息", produces = "text/plain")
	@PostMapping("/v1/invest/{id}")
	@PreAuthorize("hasRole('hall-invest-edit-v1')")
	@AOLog
	@EditAlertLayout(
		paddingMappingMethod = "getInvest"
	)
	public JSONResult investEditV1(@PathVariable Long id, @Valid @RequestBody InvestParam param) {
		investService.updateInvest(id, convertTo(param, InvestParamDTO.class), convertListTo(param.getTeams(), TeamParamDTO.class));
		return JSONResult.ok();
	}

	@ApiOperation(value = "添加创新项目信息", notes = "添加创新项目信息", produces = "text/plain")
	@PutMapping("/v1/invest/add")
	@PreAuthorize("hasRole('hall-invest-create-v1')")
	@AOLog
	@EditLayout
	public JSONResult investCreateV1(@Valid @RequestBody InvestParam param) {
		InvestParamDTO investParamDTO = convertTo(param, InvestParamDTO.class);
		investParamDTO.setPublicity(SystemConst.PUBLICITY_PUBLIC);
		investService.saveInvest(-1L, investParamDTO, convertListTo(param.getTeams(), TeamParamDTO.class));
		return JSONResult.ok();
	}

	@ApiOperation(value = "查看创新项目信息", notes = "查看创新项目信息", produces = "text/plain")
	@PreAuthorize("hasRole('hall-invest-query')")
	@GetMapping("/v1/invest/{id}")
	public JSONResult<InvestDetailsResult> getInvest(@PathVariable Long id) {
		Invest invest = investService.accessObject(id);
		InvestDetailsResult investResult = convertTo(invest, InvestDetailsResult.class);
		investResult.setAttachments(JSON.parseArray(invest.getAttachment(), Attachments.class));
		investResult.setDetailImagesUris(investService.detailImagesUrisHandle(invest.getDetailImagesUri()));
		investResult.setIndustryTitle(investService.industryMap().get(investResult.getIndustry()));
		investResult.setInvestStateTitle(investService.investStateMap().get(investResult.getInvestState()));
		investResult.setArea(areaService.accessObject(investResult.getAreaId()).getCityName());
		investResult.setCity(areaService.accessObject(investResult.getCityId()).getCityName());
		investResult.setProvince(areaService.accessObject(investResult.getProvinceId()).getCityName());
		List<Team> teams = teamService.findTeamByInvestId(investResult.getId());
		investResult.setTeams(convertListTo(teams, TeamResult.class));
		return JSONResult.ok(investResult);
	}


	@ApiOperation(value = "创新项目上架", notes = "创新项目上架", produces = "text/plain")
	@PreAuthorize("hasRole('hall-invest-upper-edit-v1')")
	@PostMapping("/v1/invest/upper/{id}")
	@AOLog
	public JSONResult investUpperV1(@PathVariable Long id) {
		investService.investUpperShelf(id);
		return JSONResult.ok();
	}

	@ApiOperation(value = "创新项目下架", notes = "创新项目下架", produces = "text/plain")
	@PreAuthorize("hasRole('hall-invest-lower-edit-v1')")
	@PostMapping("/v1/invest/lower/{id}")
	@AOLog
	public JSONResult investLowerV1(@PathVariable Long id) {
		investService.investLowerShelf(id);
		return JSONResult.ok();
	}
	@ApiOperation(value = "创新项目首页推荐", notes = "创新项目首页推荐", produces = "text/plain")
	@PreAuthorize("hasRole('hall-invest-index-edit-v1')")
	@PostMapping("/v1/invest/index/yes/{id}")
	@AOLog
	public JSONResult investIndexYesV1(@PathVariable Long id) {
		investService.investIndexYes(id);
		return JSONResult.ok();
	}

	@ApiOperation(value = "创新项目取消推荐", notes = "创新项目取消推荐", produces = "text/plain")
	@PreAuthorize("hasRole('hall-invest-index-edit-v1')")
	@PostMapping("/v1/invest/index/no/{id}")
	@AOLog
	public JSONResult investIndexNoV1(@PathVariable Long id) {
		investService.investIndexNo(id);
		return JSONResult.ok();
	}

	@ApiOperation(value = "创新项目审核", notes = "创新项目审核", produces = "text/plain")
	@PreAuthorize("hasRole('hall-invest-verify-edit-v1')")
	@PostMapping("/v1/invest/verify/{id}")
	@AOLog
	public JSONResult investVerifyV1(@PathVariable Long id,@Valid @RequestBody InvestVerifyParam param) {
		investService.investVerify(id, param.getVerify(), param.getVerifyRemark());
		return JSONResult.ok();
	}

	@ApiOperation(value = "创新项目公开申请列表", notes = "创新项目公开申请列表", produces = "text/plain")
	@GetMapping("/v1/invest/apply/page")
	@PreAuthorize("hasRole('hall-invest-apply-query')")
	@PageLayout()
	public JSONResult<Page<InvestApplyResult>> investApplyListV1(PageParam pageParam, InvestApplyQueryParam param) {
		if(null != param.getAccount()){
			param.setProposer(memberService.findMemberIdByPhone(param.getAccount()));
		}
		param.setVerify(SystemConst.VERIFY_AWAIT);
		Page<InvestApplyResult> page = jpaPageConvertToPage(investApplyService.page(pageParam, param), pageParam, InvestApplyResult.class);
		for (InvestApplyResult result : page.getList()) {
			result.setAccount(memberService.accessObject(result.getProposer()).getPhone());
		}
		return JSONResult.ok(page);
	}

	@ApiOperation(value = "创新项目公开", notes = "创新项目公开", produces = "text/plain")
	@PreAuthorize("hasRole('hall-invest-apply-open-edit-v1')")
	@PostMapping("/v1/invest/apply/open")
	@AOLog
	public JSONResult investApplyOpenV1(@Valid @RequestBody InvestApplyParam param) {
		investApplyService.openInvestApply(Arrays.asList(param.getId()), SystemConst.VERIFY_ADOPT, SystemConst.AUDITOR_ADMIN);
		return JSONResult.ok();
	}

}