package cn.com.countrygarden.bi.main.controller.marketing.app;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.model.MarketingCharge;
import cn.com.countrygarden.bi.main.model.MarketingContract;
import cn.com.countrygarden.bi.main.model.MarketingProposal;
import cn.com.countrygarden.bi.main.model.MarketingQuota;
import cn.com.countrygarden.bi.main.service.MarketingChargeService;
import cn.com.countrygarden.bi.main.service.MarketingContractService;
import cn.com.countrygarden.bi.main.service.MarketingProposalService;
import cn.com.countrygarden.bi.main.service.MarketingQuotaService;
import cn.com.countrygarden.bi.main.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller("marketingAppContractController")
@RequestMapping("/api/biapp/marketing/contract")
public class ContractController {

    @Autowired
    private MarketingContractService contractService;
    @Autowired
    private MarketingProposalService proposalService;
    @Autowired
    private MarketingQuotaService quotaService;
    @Autowired
    private MarketingChargeService chargeService;

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");


    /**
     * 首页实时数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/realtime", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result realtime() {
        Map<String, Object> response = new HashMap<>();

        MarketingContract thisYearContract = contractService.sumThisYear();
        MarketingContract lastContract = contractService.findLastContract();
        MarketingQuota thisYearQuota = quotaService.sumThisYear();
        response.put("area", thisYearContract.getContractArea()); //当前签约面积
        response.put("quota", thisYearQuota.getContractArea()); //当前签约面积目标
        response.put("lastUpdateAt", DateUtil.simpleFormat(lastContract.getContractDate())); //最后签约日期

        Map<String, Object> lastWeek = new HashMap<>();
        MarketingContract lastWeekContract = contractService.sumLastWeek(1);
        MarketingContract last2rdWeekContract = contractService.sumLastWeek(2);
        MarketingProposal lastWeekProposal = proposalService.sumLastWeek(1);
        MarketingProposal last2rdProposal = proposalService.sumLastWeek(2);

        int last1stComms = Math.max(lastWeekContract.getComms(), 0);
        BigDecimal last1stArea = lastWeekContract.getContractArea();
        if (last1stArea == null) {
            last1stArea = BigDecimal.ZERO;
        }
        lastWeek.put("area", last1stArea); //上周签约面积
        lastWeek.put("contractComm", last1stComms); //上周签约项目数


        //签约项目数环比上上周增幅
        Integer last2rdComms = last2rdWeekContract.getComms();
        float contractCommIncrease = 0f;
        if (last1stComms > 0
                && last2rdComms != null && last2rdComms > 0) {
            contractCommIncrease = (last1stComms - last2rdComms) / last2rdComms * 100;
        }
        lastWeek.put("contractCommIncrease", contractCommIncrease);

        BigDecimal last2rdArea = last2rdWeekContract.getContractArea();
        float areaIncrease = 0f;
        if (last2rdArea != null && last2rdArea.compareTo(BigDecimal.ZERO) > 0) {
            BigDecimal areaSubtract = last1stArea.subtract(last2rdArea);
            if (areaSubtract != null && areaSubtract.compareTo(BigDecimal.ZERO) > 0) {
                areaIncrease = areaSubtract.divide(last2rdArea).floatValue();
            }
        }
        lastWeek.put("areaIncrease", areaIncrease); //上周签约面积增幅

        int proposalComms = Math.max(0, lastWeekProposal.getComms());
        int proposalComms2rd = Math.max(0, last2rdProposal.getComms());
        float proposalCommIncrease = 0f;
        if (proposalComms > 0 && proposalComms2rd > 0) {
            proposalCommIncrease = (proposalComms - proposalComms2rd) / proposalComms2rd * 100;
        }
        lastWeek.put("proposalComm", proposalComms); //上会项目数
        lastWeek.put("proposalCommIncrease", proposalCommIncrease); //上会项目数环比上上周增幅

        response.put("lastWeek", lastWeek);

        return Response.response(response);
    }

    /**
     * 签约趋势
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/tendency", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result tendency() {
        List<Map<String, Object>> response = new ArrayList<>();
        List<MarketingContract> contracts = contractService.tendency();

        for (MarketingContract contract : contracts) {
            Map<String, Object> item = new HashMap<>();
            item.put("y", contract.getContractArea());
            item.put("x", Integer.valueOf(contract.getContractMonth()) + "月");
            response.add(item);
        }

        return Response.response(response);
    }

    /**
     * 签约Top5
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/ranking/top", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result rankingTop(@RequestParam(value = "limit", defaultValue = "5") int limit) {
        List<Map<String, Object>> response = new ArrayList<>();
        List<MarketingContract> contracts = contractService.rankingByOrgan(0, 0, limit);

        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        numberFormat.setMaximumFractionDigits(2);
        for (MarketingContract contract : contracts) {
            Map<String, Object> item = new HashMap<>();
            item.put("area", contract.getContractArea());
            item.put("quota", contract.getQuotaContractArea());
            item.put("rate", numberFormat.format(contract.getContractRate()));
            item.put("organ", contract.getOrganName());
            response.add(item);
        }

        return Response.response(response);
    }

    /**
     * 签约Top5
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/ranking", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result ranking(@RequestParam(value = "season", defaultValue = "0") int season,
                          @RequestParam(value = "skip", defaultValue = "0") int offset,
                          @RequestParam(value = "limit", defaultValue = "10") int limit,
                          @RequestParam(value = "retrieveProject", defaultValue = "1") int retrieveProject) {
        Map<String, Object> response = new HashMap<>();
        //今年内目标签约面积
        MarketingQuota quota = quotaService.sumThisYear();
        response.put("targetContractedAreaInThisYear", quota.getContractArea());
        //今年内实际签约面积
        MarketingContract contractThisYear = contractService.sumThisYear();
        response.put("actualContractedAreaInThisYear", contractThisYear.getContractArea());

        List<Map<String, Object>> rankings = new ArrayList<>();
        List<MarketingContract> contracts = contractService.rankingByOrgan(season, offset, limit);
        int sort = offset + 1;
        for (MarketingContract contract : contracts) {
            Map<String, Object> item = new HashMap<String, Object>() {{
                put("organName", contract.getOrganName());//区域名
            }};
            BigDecimal actualContractedArea = contract.getContractArea();
            BigDecimal targetContractedArea = contract.getQuotaContractArea();
            item.put("actualContractedArea", actualContractedArea == null ? 0 : actualContractedArea.floatValue());
            item.put("targetContractedArea", targetContractedArea == null ? 0 : targetContractedArea.floatValue());
            item.put("sort", sort);
            sort += 1;

            // projectList
            if (retrieveProject == 1) {
                item.put("projectList", retrieveOrganProject(contract.getOrganId(), season));
            } else {
                item.put("projectList", new ArrayList<>());
            }

            rankings.add(item);
        }
        response.put("contractRankingList", rankings);

        return Response.response(response);
    }

    private List<Map<String, Object>> retrieveOrganProject(int organId, int season) {
        List<Map<String, Object>> projectList = new ArrayList<>();
        List<MarketingContract> contracts = contractService.listProjectByOrgan(organId, season);
        for (MarketingContract contract : contracts) {
            Map<String, Object> item = new HashMap<String, Object>() {{
                put("id", contract.getId());
                put("commName", contract.getCommName()); //项目名
                put("corpType", contract.getCorpType()); //合作类型
                put("projectType", contract.getProjectType()); //项目类型
                put("contractArea", contract.getContractArea()); //面积
                put("contractDate", dateFormat.format(contract.getContractDate())); //签约日期
            }};
            projectList.add(item);
        }

        return projectList;
    }

    /**
     * 数据汇总
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/summary", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result summary() {
        Map<String, Object> response = new HashMap<>();

        MarketingContract contract = contractService.sumThisYear();
        MarketingCharge charge = chargeService.sumThisYear();
        List<MarketingContract> contractsByCorpType = contractService.sumThisYearByCorpType();
        List<MarketingContract> contractsByProjectType = contractService.sumThisYearByProjectType();

        response.put("contractOrgans", contract.getOrgans()); // 签约区域数
        response.put("contractComms", contract.getComms()); // 签约项目数
        response.put("contractArea", contract.getContractArea()); // 签约面积
        response.put("chargeArea", charge.getChargeArea()); // 收费面积
        response.put("chargeComms", charge.getComms()); // 收费项目数

        List<Map<String, Object>> corpTypes = new ArrayList<>();
        for (MarketingContract corpType : contractsByCorpType) {
            Map<String, Object> item = new HashMap<>();
            item.put("area", corpType.getContractArea());
            item.put("corpType", corpType.getCorpType());
            corpTypes.add(item);
        }
        response.put("corpType", corpTypes);

        List<Map<String, Object>> projectTypes = new ArrayList<>();
        for (MarketingContract projectType : contractsByProjectType) {
            Map<String, Object> item = new HashMap<>();
            item.put("area", projectType.getContractArea());
            item.put("projectType", projectType.getProjectType());
            projectTypes.add(item);
        }
        response.put("projectType", projectTypes);

        return Response.response(response);
    }


    /**
     * 合同列表
     *
     * @param datetimeFilter 时间过滤器。0 全部；1 本月；2 本年；3 往年
     * @param search         搜索关键词。模糊搜索区域、项目
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/search", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result search(@RequestParam(value = "datetime_filter", defaultValue = "0") String datetimeFilter,
                         @RequestParam(value = "search", defaultValue = "") String search,
                         @RequestParam(value = "skip", defaultValue = "0") int skip,
                         @RequestParam(value = "limit", defaultValue = "10") int limit) {
        return Response.response();
//        return Response.response(service.search(datetimeFilter, search, skip, limit));

    }
}
