package cn.com.countrygarden.bi.main.service.marketing.impl;

import cn.com.countrygarden.bi.main.dao.common.CommMapper;
import cn.com.countrygarden.bi.main.dao.marketing.CommOperationHistoryMapper;
import cn.com.countrygarden.bi.main.dao.marketing.ProposalMapper;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.common.Comm;
import cn.com.countrygarden.bi.main.model.common.CommConstant;
import cn.com.countrygarden.bi.main.model.marketing.CommOperationHistory;
import cn.com.countrygarden.bi.main.model.marketing.Proposal;
import cn.com.countrygarden.bi.main.model.marketing.ProposalMonthData;
import cn.com.countrygarden.bi.main.service.common.CommService;
import cn.com.countrygarden.bi.main.service.common.CooperationTypeService;
import cn.com.countrygarden.bi.main.service.common.ProjectNatureService;
import cn.com.countrygarden.bi.main.service.common.ProjectTypeService;
import cn.com.countrygarden.bi.main.service.marketing.ProposalService;
import cn.com.countrygarden.bi.main.service.marketing.model.ProposalData;
import cn.com.countrygarden.bi.main.service.marketing.model.StatisticsProposal;
import cn.com.countrygarden.bi.main.util.DateUtil;
import cn.com.countrygarden.bi.main.util.NumberUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by chenweijiang on 2017/9/21.
 */
@Service
@Transactional(readOnly = true)
public class ProposalServiceImpl implements ProposalService{

    @Autowired
    private CooperationTypeService cooperationTypeService;

    @Autowired
    private ProjectNatureService projectNatureService;

    @Autowired
    private ProjectTypeService projectTypeService;

    @Autowired
    private CommService commService;

    @Autowired
    private CommMapper commMapper;

    @Autowired
    private CommOperationHistoryMapper commOperationHistoryMapper;

    @Autowired
    private ProposalMapper proposalMapper;

    @Transactional(readOnly = false)
    @Override
    public void parseUploadFile(List<ProposalData> dataList, String userCode) {

        if(dataList.size()==0){
            return;
        }

        //verify data
        Map<String,Object> projectTypeMap = projectTypeService.projectTypeCache();
        Map<String,Object> projectNatureMap = projectNatureService.projectNatureCache();
        Map<String,Object> cooperationTypeMap = cooperationTypeService.cooperationTypeCache();
        Map<String,Object> organNameMap = commService.findOrganNameMapCache();
        List<String> projectNums = new ArrayList<String>();
        //检证：项目类型、项目性质、合作类型、接管区域
        for(ProposalData data: dataList){
            projectNums.add(data.getProjectNum());
//            String projectType = (String) projectTypeMap.get(data.getProjectType());
//            if(projectType == null){
//                throw new ServiceException("数据不正确, '"+data.getProjectType()+"'非系统可识别项目类型");
//            }
//            data.setProjectType(projectType);

//            String projectNature = (String) projectNatureMap.get(data.getProjectNature());
//            if(projectNature == null){
//                throw new ServiceException("数据不正确, '"+data.getProjectNature()+"'非系统可识别项目性质");
//            }
//            data.setProjectNature(projectNature);
//
//            String cooperationType = (String) cooperationTypeMap.get(data.getCorpType());
//            if(cooperationType == null){
//                throw new ServiceException("数据不正确, '"+data.getCorpType()+"'非系统可识别合作类型");
//            }
//            data.setCorpType(cooperationType);
//            if(!StringUtils.isEmpty(data.getOrgan())){
//                String organCode = (String) organNameMap.get(data.getOrgan());
//                if(organCode==null){
//                    throw new ServiceException("数据不正确, '"+data.getOrgan()+"'非系统可区域，请填入ERP系统现有区域");
//                }
//                data.setOrganId(organCode);
//            }
        }

       // List<Comm> dbList = commMapper.searchByCommNums(projectNums);
//        if(dbList.size()!= dataList.size()){
//            throw new ServiceException("数据不正确, 导出数据中有项目未在系统创建,请先到系统中创建并导出项目编号");
//        }
 //   List<Comm> updateList = new ArrayList<Comm>();
        List<Proposal> newData = new ArrayList<Proposal>();
//        List<CommOperationHistory> historyList = new ArrayList<CommOperationHistory>();
        Map<String,Comm> commMap = new HashMap<String,Comm>();
//        for(Comm comm :dbList){
//            commMap.put(comm.getCommNum(),comm);
//        }
        Date current = new Date();
        for(ProposalData data: dataList){
//            Comm comm = commMap.get(data.getProjectNum());
//            comm.setName(data.getProjectName());
//            comm.setOrganId(data.getOrganId());
////            comm.setProjectType(data.getProjectType());
////            comm.setCorpType(data.getCorpType());
////            comm.setProjectNature(data.getProjectNature());
//            comm.setProjectType(1);
//            comm.setCorpType(1);
//            comm.setProjectNature(1);
//            if(!StringUtils.isEmpty(data.getProposalDate())){
//                comm.setProposalDate(DateUtil.parseDate(data.getProposalDate()));
//            }
//            comm.setStatus(data.getStatus());
//            comm.setGmtModified(current);
//            comm.setModifiedBy(userCode);
            String area = data.getArear();
            BigDecimal areaDc = new BigDecimal(area);
//            areaDc = NumberUtil.fromTenOfThousand(areaDc);
           // comm.setArea(areaDc);
  //          updateList.add(comm);

            Proposal proposal = new Proposal();
            proposal.setCommId(0);
            proposal.setProposalDate(DateUtil.parseDate(data.getProposalDate()));
            proposal.setIsDelete((byte)0);
            proposal.setMemo(data.getRemark());
            proposal.setGmtCreate(current);
            proposal.setCreateBy(userCode);
            proposal.setGmtModified(current);
            proposal.setModifiedBy(userCode);
            proposal.setResult(data.getStatus());
            newData.add(proposal);

//            CommOperationHistory history = new CommOperationHistory();
//            history.setCommId(comm.getId());
//            history.setComment(data.getRemark());
//            String operationName = "";
//            switch (comm.getStatus()){
//                case CommConstant.CommStatus.candidate:
//                    operationName = CommConstant.OperationName.candidate;
//                    break;
//                case CommConstant.CommStatus.passed:
//                    operationName = CommConstant.OperationName.passed;
//                    break;
//                case CommConstant.CommStatus.suspend:
//                    operationName = CommConstant.OperationName.suspend;
//                    break;
//
//            }
//            history.setGmtCreate(current);
//            history.setCreateBy(userCode);
//            history.setName(operationName);
//            historyList.add(history);
        }

     //   commOperationHistoryMapper.insertList(historyList);
        proposalMapper.insertList(newData);
//        for(Comm comm:updateList){
//            commMapper.updateByPrimaryKey(comm);
//        }

    }

    /**
     * 上会趋势
     *
     * @return
     */
    public List<ProposalMonthData> tendency() {
        return proposalMapper.tendency(new HashMap<String, Object>() {{
            put("afterDate", DateUtil.getFirstDayOfThisYear());
        }});
    }

    public List<StatisticsProposal> statisticsProposal(){
        List<StatisticsProposal> result = new ArrayList<StatisticsProposal>();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.MILLISECOND,0);
        int month = calendar.get(Calendar.MONTH);
        for(int i=0;i<=month;i++){
            calendar.set(Calendar.MONTH,i);
            int firstDate = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
            int lastDate = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            calendar.set(Calendar.DAY_OF_MONTH,firstDate);
            Date startDate = calendar.getTime();
            calendar.set(Calendar.DAY_OF_MONTH,lastDate);
            Date endDate = calendar.getTime();
            Map<String,Object> query = new HashMap<String,Object>();
            query.put("startDate",startDate);
            query.put("endDate",endDate);
            List<Proposal> dataList = proposalMapper.selectByMonth(query);
            StatisticsProposal statistics = new StatisticsProposal();
            result.add(statistics);
            statistics.setX(i+1+"月");
            Integer commId = null;
            int total = 0;
            int pass = 0;
            int pending=0;
            int shelve = 0;
            for(Proposal proposal :dataList){
            	total++;
            if(proposal.getResult().equals("通过")) {
            	pass++;
            }else if(proposal.getResult().equals("待定")) {
            	pending++;
            }else {
            	shelve++;
            }
           }
      //      int total = statistics.getPass()+statistics.getShelve()+statistics.getPending();
            statistics.setY(total);
            statistics.setPass(pass);
            statistics.setPending(pending);
            statistics.setShelve(shelve);
        }
        return result;
    }


}
