package com.softwarebr.nunu.web.admin;

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.layout.ViewLayout;
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.google.common.collect.Lists;
import com.softwarebr.nunu.domain.VerifyPageTotal;
import com.softwarebr.nunu.dto.go.PolicyLabelParamDTO;
import com.softwarebr.nunu.dto.go.PolicyParamDTO;
import com.softwarebr.nunu.entity.go.Policy;
import com.softwarebr.nunu.entity.go.PolicyApply;
import com.softwarebr.nunu.entity.go.PolicyLabel;
import com.softwarebr.nunu.entity.user.Member;
import com.softwarebr.nunu.globals.SystemConst;
import com.softwarebr.nunu.json.admin.go.*;
import com.softwarebr.nunu.service.go.LabelService;
import com.softwarebr.nunu.service.go.PolicyApplyService;
import com.softwarebr.nunu.service.go.PolicyLabelService;
import com.softwarebr.nunu.service.go.PolicyService;
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.util.List;

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

/**
 * 政策管理
 *
 * @author lilin
 * @date 2020-02-19 14:03:47
 */

@RestController
@Api(tags = "政策管理")
@AdminMenu(menuName = "政策管理", icon = Icons.TABLE)
@RequestMapping("/admin/access")
public class AdminPolicyController {

    @Autowired
    private PolicyService policyService;

    @Autowired
    private PolicyLabelService policyLabelService;

    @Autowired
    private LabelService labelService;

    @Autowired
    private PolicyApplyService policyApplyService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private AreaService areaService;

    @ApiOperation(value = "政策管理", notes = "政策管理", produces = "text/plain")
    @GetMapping("/v1/policy/page")
    @AdminMenu(menuName = "政策管理", order = 1, url = "PolicyManagement")
    @PreAuthorize("hasRole('go-policy-query')")
    @PageLayout(
            options = {
                    @CmsOption(name = "新增政策", uriMappingMethod = "policyCreateV1")
            },
            columnOptions = {
                    @CmsOption(name = "查看", uriMappingMethod = "getPolicyDetailV1"),
                    @CmsOption(condition = "{status}==0", name = "上架", uriMappingMethod = "policyUpperV1"),
                    @CmsOption(condition = "{status}==1", name = "下架", uriMappingMethod = "policyLowerV1"),
                    @CmsOption(condition = "{indexType}==0", name = "推荐至首页", uriMappingMethod = "policyIndexYesV1"),
                    @CmsOption(condition = "{indexType}==1", name = "取消推荐", uriMappingMethod = "policyIndexNoV1"),
                    @CmsOption(name = "编辑", uriMappingMethod = "policyEditV1"),
                    @CmsOption(name = "删除", uriMappingMethod = "policyDelV1", alert = "确定删除该记录吗?")
            }
    )
    public JSONResult<Page<PolicyResult>> policyListV1(PageParam pageParam, PolicyQueryParam param) {
        param.setMarker(SystemConst.MARKER_STATUS_NO);
        param.setApplyStatus(Policy.APPLY_STATUS_DISPLAY);
        param.setVerify(SystemConst.VERIFY_ADOPT);
        Page<PolicyResult> page = jpaPageConvertToPage(policyService.page(pageParam, param), pageParam, PolicyResult.class);
        return JSONResult.ok(page);
    }

    @ApiOperation(value = "政策上架", notes = "政策上架", produces = "text/plain")
    @PreAuthorize("hasRole('go-policy-upper-edit-v1')")
    @PostMapping("/v1/policy/upper/{id}")
    @AOLog
    public JSONResult policyUpperV1(@PathVariable Long id) {
        policyService.policyUpperShelf(id);
        return JSONResult.ok();
    }

    @ApiOperation(value = "政策下架", notes = "政策下架", produces = "text/plain")
    @PreAuthorize("hasRole('go-policy-lowerp-edit-v1')")
    @PostMapping("/v1/policy/lower/{id}")
    @AOLog
    public JSONResult policyLowerV1(@PathVariable Long id) {
        policyService.policyLowerShelf(id);
        return JSONResult.ok();
    }

    @ApiOperation(value = "首页推荐", notes = "首页推荐", produces = "text/plain")
    @PreAuthorize("hasRole('go-policy-index-edit-v1')")
    @PostMapping("/v1/policy/index/yes/{id}")
    @AOLog
    public JSONResult policyIndexYesV1(@PathVariable Long id) {
        policyService.policyIndexYes(id);
        return JSONResult.ok();
    }

    @ApiOperation(value = "取消推荐", notes = "取消推荐", produces = "text/plain")
    @PreAuthorize("hasRole('go-policy-index-edit-v1')")
    @PostMapping("/v1/policy/index/no/{id}")
    @AOLog
    public JSONResult policyIndexNoV1(@PathVariable Long id) {
        policyService.policyIndexNo(id);
        return JSONResult.ok();
    }

    @ApiOperation(value = "修改政策信息", notes = "修改政策信息", produces = "text/plain")
    @PostMapping("/v1/policy/{id}")
    @PreAuthorize("hasRole('go-policy-edit-v1')")
    @AOLog
    @EditAlertLayout(
            paddingMappingMethod = "getPolicyDetailV1"
    )
    public JSONResult policyEditV1(@PathVariable Long id, @Valid @RequestBody PolicyParam param) {
        policyService.updatePolicy(id, convertTo(param, PolicyParamDTO.class), convertListTo(param.getLabelParams(), PolicyLabelParamDTO.class));
        return JSONResult.ok();
    }

    @ApiOperation(value = "添加政策信息", notes = "添加政策信息", produces = "text/plain")
    @PutMapping("/v1/policy/add")
    @PreAuthorize("hasRole('go-policy-create-v1')")
    @AOLog
    @EditLayout
    public JSONResult policyCreateV1(@Valid @RequestBody PolicyParam param) {
        PolicyParamDTO policyParamDTO = convertTo(param, PolicyParamDTO.class);
        policyParamDTO.setApplyStatus(Policy.APPLY_STATUS_DISPLAY);
        policyService.savePolicy(policyParamDTO, convertListTo(param.getLabelParams(), PolicyLabelParamDTO.class));
        return JSONResult.ok();
    }

    @ApiOperation(value = "删除政策信息", notes = "删除政策信息", produces = "text/plain")
    @DeleteMapping("/v1/policy/{id}")
    @PreAuthorize("hasRole('go-policy-del-v1')")
    @AOLog
    public JSONResult policyDelV1(@PathVariable Long id) {
        policyService.removePolicyById(id);
        return JSONResult.ok();
    }

    @ApiOperation(value = "查看政策信息", notes = "查看政策信息", produces = "text/plain")
    @PreAuthorize("hasRole('go-policy-detail-query')")
    @GetMapping("/v1/policy/detail/{id}")
    @ViewLayout(paddingMappingMethod = "getPolicyDetailV1")
    public JSONResult<PolicyDetailResult> getPolicyDetailV1(@PathVariable Long id) {
        PolicyDetailResult policy = convertTo(policyService.accessObject(id), PolicyDetailResult.class);
        List<PolicyLabel> policyLabel = policyLabelService.getPolicyLabel(policy.getId());
        List<PolicyLabelResult> labelResults = Lists.newArrayList();
        for (PolicyLabel label : policyLabel) {
            labelResults.add(PolicyLabelResult.builder().
                    childName(labelService.accessObject(label.getChildId()).getLabelName()).
                    parentName(labelService.accessObject(label.getParentId()).getLabelName()).
                    childLevelId(label.getChildId()).
                    parentLevelId(label.getParentId()).build());
        }
        policy.setLabelResults(labelResults);
        if (null != policy.getAreaId()) {
            policy.setArea(areaService.accessObject(policy.getAreaId()).getCityName());
        }
        if (null != policy.getCityId()) {
            policy.setCity(areaService.accessObject(policy.getCityId()).getCityName());
        }
        if (null != policy.getProvinceId()) {
            policy.setProvince(areaService.accessObject(policy.getProvinceId()).getCityName());
        }
        return JSONResult.ok(policy);
    }

    @ApiOperation(value = "政策审核管理", notes = "政策审核管理", produces = "text/plain")
    @GetMapping("/v1/policy/verify/page")
    @AdminMenu(menuName = "政策审核管理", order = 2, url = "administer")
    @PreAuthorize("hasRole('go-policy-verify-query')")
    @PageLayout(
            columnOptions = {
                    @CmsOption(name = "查看", uriMappingMethod = "getPolicyDetailV1"),
                    @CmsOption(name = "审核", uriMappingMethod = "verifyPolicyV1")
            }
    )
    public JSONResult<Page<PolicyVerifyResult>> policyVerifyListV1(PageParam pageParam, PolicyVerifyQueryParam param) {
        param.setMarker(SystemConst.MARKER_STATUS_NO);
        param.setApplyStatus(Policy.APPLY_STATUS_DISPLAY);
        param.setSourceType(Policy.SOURCE_TYPE_REPTILE);
        Page<PolicyVerifyResult> page = jpaPageConvertToPage(policyService.page(pageParam, param), pageParam, PolicyVerifyResult.class);
        return JSONResult.ok(page);
    }

    @ApiOperation(value = "政策审核状态数据统计", notes = "政策审核状态数据统计", produces = "text/plain")
    @PreAuthorize("hasRole('go-policy-verify-query')")
    @GetMapping("/v1/policy/verify/count")
    public JSONResult<VerifyPageTotal> getPolicyVerifyCount(PolicyVerifyQueryParam param) {
        VerifyPageTotal verifyPageResult = new VerifyPageTotal();
        param.setMarker(SystemConst.MARKER_STATUS_NO);
        param.setApplyStatus(Policy.APPLY_STATUS_DISPLAY);
        param.setSourceType(Policy.SOURCE_TYPE_REPTILE);
        verifyPageResult.setTotalCount(policyService.count(param));
        param.setVerify(SystemConst.VERIFY_AWAIT);
        verifyPageResult.setVerifyAwaitCount(policyService.count(param));
        param.setVerify(SystemConst.VERIFY_ADOPT);
        verifyPageResult.setVerifyAdoptCount(policyService.count(param));
        param.setVerify(SystemConst.VERIFY_REJECT);
        verifyPageResult.setVerifyRejectCount(policyService.count(param));
        return JSONResult.ok(verifyPageResult);
    }

    @ApiOperation(value = "政策审核", notes = "政策审核", produces = "text/plain")
    @PreAuthorize("hasRole('go-policy-verify-edit-v1')")
    @PostMapping("/v1/policy/verify/{id}")
    @EditAlertLayout(
            paddingMappingMethod = "getPolicyDetailV1"
    )
    @AOLog
    public JSONResult verifyPolicyV1(@PathVariable Long id, @Valid @RequestBody PolicyVerifyParam param) {
        policyService.updatePolicyVerify(id, param.getVerify(), param.getRemark());
        PolicyParamDTO policyParamDTO = convertTo(param, PolicyParamDTO.class);
        policyService.updatePolicy(id, policyParamDTO, convertListTo(param.getLabelParams(), PolicyLabelParamDTO.class));
        return JSONResult.ok();
    }


    @ApiOperation(value = "政策申报管理", notes = "政策申报管理", produces = "text/plain")
    @GetMapping("/v1/policy/apply/page")
    @AdminMenu(menuName = "政策申报管理", order = 3, url = "declare")
    @PreAuthorize("hasRole('go-policy-apply-query')")
    @PageLayout(
            options = {
                    @CmsOption(name = "新增政策", uriMappingMethod = "policyApplyCreateV1")
            },
            columnOptions = {
                    @CmsOption(name = "查看", uriMappingMethod = "getPolicyDetailV1"),
                    @CmsOption(condition = "{status}==0", name = "上架", uriMappingMethod = "policyApplyUpperV1"),
                    @CmsOption(condition = "{status}==1", name = "下架", uriMappingMethod = "policyApplyLowerV1"),
                    @CmsOption(name = "编辑", uriMappingMethod = "policyApplyEditV1"),
                    @CmsOption(name = "删除", uriMappingMethod = "policyDelV1", alert = "确定删除该记录吗?")
            }
    )
    public JSONResult<Page<PolicyResult>> policyApplyListV1(PageParam pageParam, PolicyQueryParam param) {
        param.setMarker(SystemConst.MARKER_STATUS_NO);
        param.setApplyStatus(Policy.APPLY_STATUS_YES);
        param.setVerify(SystemConst.VERIFY_ADOPT);
        Page<PolicyResult> page = jpaPageConvertToPage(policyService.page(pageParam, param), pageParam, PolicyResult.class);
        return JSONResult.ok(page);
    }

    @ApiOperation(value = "政策申报上架", notes = "政策申报上架", produces = "text/plain")
    @PreAuthorize("hasRole('go-policy-apply-upper-edit-v1')")
    @PostMapping("/v1/policy/apply/upper/{id}")
    @AOLog
    public JSONResult policyApplyUpperV1(@PathVariable Long id) {
        policyService.policyUpperShelf(id);
        return JSONResult.ok();
    }

    @ApiOperation(value = "政策申报下架", notes = "政策申报下架", produces = "text/plain")
    @PreAuthorize("hasRole('go-policy-apply-lower-edit-v1')")
    @PostMapping("/v1/policy/apply/lower/{id}")
    @AOLog
    public JSONResult policyApplyLowerV1(@PathVariable Long id) {
        policyService.policyLowerShelf(id);
        return JSONResult.ok();
    }

    @ApiOperation(value = "修改政策申报信息", notes = "修改政策申报信息", produces = "text/plain")
    @PostMapping("/v1/policy/apply/{id}")
    @PreAuthorize("hasRole('go-policy-apply-edit-v1')")
    @AOLog
    @EditAlertLayout(
            paddingMappingMethod = "getPolicyDetailV1"
    )
    public JSONResult policyApplyEditV1(@PathVariable Long id, @Valid @RequestBody PolicyParam param) {
        policyService.updatePolicy(id, convertTo(param, PolicyParamDTO.class), convertListTo(param.getLabelParams(), PolicyLabelParamDTO.class));
        return JSONResult.ok();
    }

    @ApiOperation(value = "添加政策申报信息", notes = "添加政策申报信息", produces = "text/plain")
    @PutMapping("/v1/policy/apply/add")
    @PreAuthorize("hasRole('go-policy-apply-create-v1')")
    @AOLog
    @EditLayout
    public JSONResult policyApplyCreateV1(@Valid @RequestBody PolicyParam param) {
        PolicyParamDTO policyParamDTO = convertTo(param, PolicyParamDTO.class);
        policyParamDTO.setApplyStatus(Policy.APPLY_STATUS_YES);
        policyService.savePolicy(policyParamDTO, convertListTo(param.getLabelParams(), PolicyLabelParamDTO.class));
        return JSONResult.ok();
    }


    @ApiOperation(value = "政策申报留言审核管理", notes = "政策申报留言审核管理", produces = "text/plain")
    @GetMapping("/v1/policy/apply/verify/page")
    @AdminMenu(menuName = "政策留言申报审核管理", order = 4, url = "PMmessage")
    @PreAuthorize("hasRole('go-policy-apply-verify-query')")
    @PageLayout(
            columnOptions = {
                    @CmsOption(name = "查看政策", uriMappingMethod = "getPolicyDetailV1"),
                    @CmsOption(name = "受理", uriMappingMethod = "policyApplyVerifyV1"),
                    @CmsOption(name = "服务完成", uriMappingMethod = "policyApplyVerifySuccessV1")
            }
    )
    public JSONResult<Page<PolicyApplyResult>> policyApplyVerifyListV1(PageParam pageParam, PolicyApplyQueryParam param) {
        if (null != param.getAccount()) {
            param.setMemberId(memberService.findMemberIdByPhone(param.getAccount()));
        }
        Page<PolicyApplyResult> page = jpaPageConvertToPage(policyApplyService.page(pageParam, param), pageParam, PolicyApplyResult.class);
        for (PolicyApplyResult applyResult : page.getList()) {
            applyResult.setPolicyName(policyService.accessObject(applyResult.getPolicyId()).getTitle());
            Member member = memberService.accessObject(applyResult.getMemberId());
            applyResult.setAccount(member.getPhone());
            applyResult.setNickName(member.getNickname());
        }
        return JSONResult.ok(page);

    }

    @ApiOperation(value = "政策申报留言审核状态数据统计", notes = "政策申报留言审核状态数据统计", produces = "text/plain")
    @PreAuthorize("hasRole('go-policy-apply-verify-query')")
    @GetMapping("/v1/policy/apply/verify/count")
    public JSONResult<VerifyPageTotal> getInvestOrgCount(PolicyApplyQueryParam param) {
        VerifyPageTotal verifyPageResult = new VerifyPageTotal();
        if (null != param.getAccount()) {
            param.setMemberId(memberService.findMemberIdByPhone(param.getAccount()));
        }
        verifyPageResult.setTotalCount(policyApplyService.count(param));
        param.setStatus(PolicyApply.STATUS_WAIT_ACCEPTANCE);
        verifyPageResult.setWaitAcceptCount(policyApplyService.count(param));
        param.setStatus(PolicyApply.STATUS_IN_ACCEPTANCE);
        verifyPageResult.setAcceptanceCount(policyApplyService.count(param));
        param.setStatus(PolicyApply.STATUS_SERVICE_SUCCESS);
        verifyPageResult.setSuccessCount(policyApplyService.count(param));
        return JSONResult.ok(verifyPageResult);
    }

    @ApiOperation(value = "受理政策", notes = "受理政策", produces = "text/plain")
    @PreAuthorize("hasRole('go-policy-apply-verify-edit-v1')")
    @PostMapping("/v1/policy/apply/verify/{id}")
    @AOLog
    public JSONResult policyApplyVerifyV1(@PathVariable Long id, @RequestBody PolicyApplyParam param) {
        policyApplyService.policyApplyVerifyAwait(id, param.getRemark());
        return JSONResult.ok();
    }


    @ApiOperation(value = "服务完成", notes = "服务完成", produces = "text/plain")
    @PreAuthorize("hasRole('go-policy-apply-verify-success-edit-v1')")
    @PostMapping("/v1/policy/apply/verify/success/{id}")
    @AOLog
    public JSONResult policyApplyVerifySuccessV1(@PathVariable Long id, @RequestBody PolicyApplyParam param) {
        policyApplyService.policyApplyVerifySuccess(id, param.getRemark());
        return JSONResult.ok();
    }

}
