package com.liangjian.dataplatform.member.service.impl;

import com.liangjian.dataplatform.member.dao.tertiary.ProductRepository;
import com.liangjian.dataplatform.member.dao.tertiary.ProductUsageRepository;
import com.liangjian.dataplatform.member.entity.po.secondary.FiltersData;
import com.liangjian.dataplatform.member.entity.po.secondary.FiltersUtils;
import com.liangjian.dataplatform.member.jobUtil.EsUtils;
import com.liangjian.dataplatform.member.service.IMrugTakeInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MrugTakeInfoService implements IMrugTakeInfoService {

    @Autowired
    private ProductUsageRepository productUsageRepository;
    @Autowired
    private ProductRepository productRepository;

//    @PersistenceContext
    @Autowired
    @Qualifier("entityManagerTertiary")
    private EntityManager entityManager;

    @Override
    public Map<String, Object> getProductUsageList(FiltersData data) {

        Map<String, Object> ret = new HashMap<String, Object>();

        try {
            if(null != data){
                List<FiltersUtils> filters = data.getFilters();
                for (int i = 0; i <filters.size() ; i++) {
                    FiltersUtils filtersUtils = filters.get(i);
                    String str = filtersUtils.getField();
                    if(str.equals("ProductName")){
                        filtersUtils.setField("p.ProductName");
                    }else if(str.equals("CommonTitle")){
                        filtersUtils.setField("p.CommonTitle");
                    }else if(str.equals("UsageMethod")){
                        filtersUtils.setField("u.UsageMethod");
                    }else if(str.equals("UsageFrequencyUnit")){
                        filtersUtils.setField("u.UsageFrequencyUnit");
                    }else if(str.equals("UsageFrequencyStr")){
                        filtersUtils.setField("u.UsageFrequencyStr");
                    }else if(str.equals("UsagePerUseCount")){
                        filtersUtils.setField("u.UsagePerUseCount");
                    }else if(str.equals("Manufacturer")){
                        filtersUtils.setField("p.Manufacturer");
                    }else if(str.equals("Introduction")){
                        filtersUtils.setField("p.Introduction");
                    }else if(str.equals("UsagePerUseUnit")){
                        filtersUtils.setField("u.UsagePerUseUnit");
                    }
                }

                String filterString = EsUtils.getFilterString(filters);
                int pageIndex = data.getPageIndex();
                int pageSize = data.getPageSize();

                if(pageSize <= 0){
                    pageSize = 15;
                }

                if(pageIndex == 1){
                    pageIndex = 0;
                }else if(pageIndex > 0){
                    pageIndex = ((pageIndex - 1) * pageSize);
                    pageSize = pageIndex + pageSize;
                    pageIndex++;

                }

                String sql = "select * \n \n" +
                        "from ( ";
                StringBuilder sqlTemp = new StringBuilder("select row_number() over(order by id asc) as rownumber, u.ID,p.ProductName productName,p.CommonTitle commonTitle," +
                        "u.UsageMethod usageMethod,u.UsageFrequencyUnit usageFrequencyUnit,u.UsageFrequencyStr usageFrequencyStr,u.UsagePerUseCount usagePerUseCount," +
                        " p.Manufacturer manufacturer,p.Introduction introduction, u.UsagePerUseUnit usagePerUseUnit,p.ProductCode \n" +
                        "from dbo.ProductUsage AS u INNER JOIN dbo.Product AS p \n" +
                        "on u.ProductCode = p.ProductCode ").append(filterString);
                StringBuilder sqlCount = new StringBuilder("select count(1) totalCount \n" +
                        "from dbo.ProductUsage AS u INNER JOIN dbo.Product AS p \n" +
                        "on u.ProductCode = p.ProductCode ").append(filterString);

                sql = sql + sqlTemp.toString() + " ) a where a.rownumber  BETWEEN "+pageIndex+" AND "+ pageSize;

                Query dataQuery = entityManager.createNativeQuery(sql);
                List<Object[]> resultList = dataQuery.getResultList();



                Object totalCount = 0;
                List<Map<String, Object>> retList = new ArrayList<>();
                if(resultList != null && resultList.size() > 0){
                    for (int i = 0; i <resultList.size() ; i++) {
                        Map<String, Object> map = new HashMap<>();
                        Object[] objects = resultList.get(i);
                        map.put("ID",objects[1]);
                        map.put("ProductName",objects[2]);
                        map.put("CommonTitle",objects[3]);
                        map.put("UsageMethod",objects[4]);
                        map.put("UsageFrequencyUnit",objects[5]);
                        map.put("UsageFrequencyStr",objects[6]);
                        map.put("UsagePerUseCount",objects[7]);
                        map.put("Manufacturer",objects[8]);
                        map.put("Introduction",objects[9]);
                        map.put("UsagePerUseUnit",objects[10]);
                        map.put("ProductCode",objects[11]);
                        retList.add(map);
                    }
                    Query countQuery = entityManager.createNativeQuery(sqlCount.toString());
                    List<Object[]> countList = countQuery.getResultList();
                    totalCount = countList.get(0);
                }
                ret.put("items",retList);
                ret.put("totalCount",totalCount);

            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }

    @Override
    public Map<String, Object> updateTakeInfo(Map<String, Object> data) {

        Map<String, Object> ret = new HashMap<>();
        ret.put("success",false);
        try {
            if(data != null && !data.isEmpty()){

                String productName  = (String) data.get("ProductName");
                String commonTitle = (String) data.get("CommonTitle");
                String manufacturer = (String) data.get("Manufacturer");
                String introduction = (String) data.get("Introduction");
                int productCode = Integer.parseInt(data.get("ProductCode").toString());

                int num = productRepository.updateByProductCode(productName, commonTitle, manufacturer, introduction,productCode);

                String usageMethod = (String) data.get("UsageMethod");
                String usageFrequencyUnit = (String) data.get("UsageFrequencyUnit");
                String usageFrequencyStr = (String) data.get("UsageFrequencyStr");
                String usagePerUseCount = (String) data.get("UsagePerUseCount");
                String isagePerUseUnit = (String) data.get("UsagePerUseUnit");


                num += productUsageRepository.updateByProductCode(usageMethod, usageFrequencyUnit, usageFrequencyStr, usagePerUseCount, isagePerUseUnit, productCode);

                ret.put("success",true);
                ret.put("rows",num);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }
}
