package com.hwrj.cloud.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.hwrj.cloud.admin.dao.UmsMemberOriginDao;
import com.hwrj.cloud.admin.dao.UmsMemberOriginProductDao;
import com.hwrj.cloud.admin.dto.UmsMemberOriginParam;
import com.hwrj.cloud.admin.dto.param.MemberWebPageParam;
import com.hwrj.cloud.admin.dto.param.SelectVo;
import com.hwrj.cloud.admin.excelEntity.UmsMemberOriginExcel;
import com.hwrj.cloud.admin.mapper.UmsCompanyInfoMapper;
import com.hwrj.cloud.admin.mapper.UmsMemberOriginMapper;
import com.hwrj.cloud.admin.model.UmsCompanyInfo;
import com.hwrj.cloud.admin.model.UmsCompanyInfoExample;
import com.hwrj.cloud.admin.model.UmsMemberOrigin;
import com.hwrj.cloud.admin.model.UmsMemberOriginProduct;
import com.hwrj.cloud.admin.service.UmsMemberOriginProductService;
import com.hwrj.cloud.admin.service.UmsMemberOriginService;
import com.hwrj.cloud.admin.util.CurrUserUtil;
import com.hwrj.cloud.common.exception.GlobalException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @className:
 * @description:
 * @author: lym
 * @date: 2020/9/5 11:23
 */
@Service
public class UmsMemberOriginServiceImpl implements UmsMemberOriginService {
    @Resource
    private UmsMemberOriginMapper umsMemberOriginMapper;
    @Resource
    private UmsMemberOriginProductDao umsMemberOriginProductDao;
    @Resource
    private UmsMemberOriginDao umsMemberOriginDao;

    @Resource
    private UmsCompanyInfoMapper umsCompanyInfoMapper;
    @Autowired
    private UmsMemberOriginProductService umsMemberOriginProductService;

    @Override
    //@Transactional
    public int batchSave(List<UmsMemberOriginExcel> list) {
        UmsMemberOrigin origin = null;
        List<UmsMemberOriginProduct> originProductList = new ArrayList<>();
        int saveNum = 0;
        for (UmsMemberOriginExcel excel:list){
            origin = new UmsMemberOrigin();
            BeanUtils.copyProperties(excel,origin);
            //检验是否唯一
            int i = umsMemberOriginDao.isExist(origin);
//            if (i > 0) continue; //已存在
            List<UmsCompanyInfo> umsCompanyInfos = companyInfoList(excel.getCompName());
            if (umsCompanyInfos != null && umsCompanyInfos.size()>0){
                origin.setCompId(umsCompanyInfos.get(0).getId());
            }
            i = umsMemberOriginMapper.insertSelective(origin); //添加生产地信息
            if (i > 0){
                saveNum ++;
                getOriginProductList(excel,origin.getId(),originProductList);
            }
        }
        if (originProductList != null && originProductList.size() > 0)
            umsMemberOriginProductDao.batchSave(originProductList);
        return saveNum;
    }

    /**
     * 产地产出物
     * lym
     * @param excel
     * @param originProductList
     */
    private void getOriginProductList(UmsMemberOriginExcel excel,long originId,List<UmsMemberOriginProduct> originProductList){
            if (!StringUtils.isEmpty(excel.getProductName())){ //产出物不为空
                List<String> productNames = new ArrayList<>(),plantAreas = new ArrayList<>(),
                        outputNums = new ArrayList<>(),outputValues = new ArrayList<>();
                UmsMemberOriginProduct originProduct = null;
                String productName = excel.getProductName();
                String plantArea = excel.getPlantArea(); //产出物种植面积（亩）
                String outputNum = excel.getOutputNum(); //产出物总产量（吨）
                String outputValue = excel.getOutputValue(); //产出物亩产值（万元）
                if (productName.contains("；")){ //多产出物
                    productNames = Arrays.asList(productName.split("；"));
                    //产出物不为空，种植面积这些才有价值
                    if (plantArea.contains("；")){
                        plantAreas = Arrays.asList(plantArea.split("；"));
                    }

                    if (outputNum.contains("；")){
                        outputNums = Arrays.asList(outputNum.split("；"));
                    }

                    if (outputValue.contains("；")){
                        outputValues = Arrays.asList(outputValue.split("；"));
                    }

                    for (int i = 0;i < productNames.size();i++){ //产出物
                        originProduct = new UmsMemberOriginProduct();
                        originProduct.setFkOriginId(originId);
                        originProduct.setProductName(productNames.get(i));
                        if (plantAreas != null && plantAreas.size() > i)
                            originProduct.setPlantArea(plantAreas.get(i));
                        if (outputNums != null && outputNums.size() > i)
                            originProduct.setOutputNum(outputNums.get(i));
                        if (outputValues != null && outputValues.size() > i)
                            originProduct.setOutputValue(outputValues.get(i));
                        originProduct.setState(0);
                        originProduct.setCreateId(CurrUserUtil.getUserId());
                        originProductList.add(originProduct);
                    }
                }else {
                    originProduct = new UmsMemberOriginProduct();
                    originProduct.setFkOriginId(originId);
                    originProduct.setProductName(productName);
                    originProduct.setPlantArea(plantArea);
                    originProduct.setOutputNum(outputNum);
                    originProduct.setOutputValue(outputValue);
                    originProduct.setState(0);
                    originProduct.setCreateId(1);
                    originProductList.add(originProduct);
                }
            }
    }

    @Override
    public List<UmsMemberOriginParam> list(MemberWebPageParam memberWebPageParam) {
        //判断是不是供应商不是获取全部或者特定的供应商数据
        Long compId = CurrUserUtil.getCompIdInfo();
        if(StringUtils.isEmpty(compId)){
            memberWebPageParam.setCompId(memberWebPageParam.getCompId());
        }else{
            memberWebPageParam.setCompId(compId);
        }
        PageHelper.startPage(memberWebPageParam.getPageNo(), memberWebPageParam.getPageSize());
        List<UmsMemberOriginParam> list = umsMemberOriginDao.pageList(memberWebPageParam);
        return list;
    }

    @Override
    public List<UmsMemberOriginParam> list(UmsMemberOriginParam origin) {
        List<UmsMemberOriginParam> list = umsMemberOriginDao.list(origin);
        return list;
    }

    public List<UmsCompanyInfo> companyInfoList(String companyName){
        if (StringUtils.isEmpty(companyName)){
            return null;
        }
        UmsCompanyInfoExample example = new UmsCompanyInfoExample();
        UmsCompanyInfoExample.Criteria criteria = example.createCriteria();
        criteria.andCompNameEqualTo(companyName);
        example.setOrderByClause("create_time desc");
        List<UmsCompanyInfo> umsCompanyInfos = umsCompanyInfoMapper.selectByExample(example);
        return umsCompanyInfos;
    }

    @Override
    public int save(UmsMemberOriginParam origin) {
        UmsMemberOrigin umsMemberOrigin = new UmsMemberOrigin();
        List<UmsMemberOriginProduct> originProductList = origin.getProductlist();
        BeanUtils.copyProperties(origin,umsMemberOrigin);
        //检验是否唯一
        int i = umsMemberOriginDao.isExist(umsMemberOrigin);
        if (i > 0) {
            throw new GlobalException(1,"生产地已存在!");
        }

        umsMemberOrigin.setCreateTime(new Date());
        i = umsMemberOriginMapper.insertSelective(umsMemberOrigin); //添加生产地信息
        if (i > 0 && originProductList != null && originProductList.size() > 0) { //添加产地产出物信息
            umsMemberOriginProductService.saveOrUpdate(originProductList,umsMemberOrigin.getId());
        }

        return i;
    }

    @Override
    @Transactional
    public int update(UmsMemberOriginParam origin) {
        UmsMemberOrigin umsMemberOrigin = new UmsMemberOrigin();
        List<UmsMemberOriginProduct> originProductList = origin.getProductlist();
        BeanUtils.copyProperties(origin,umsMemberOrigin);
        //检验是否唯一
        int i = umsMemberOriginDao.isExist(umsMemberOrigin);
        if (i > 0) {
            throw new GlobalException(1,"生产地已存在!");
        }

        umsMemberOrigin.setUpdateTime(new Date());
        i = umsMemberOriginMapper.updateByPrimaryKeySelective(umsMemberOrigin); //修改生产地信息
        if (i > 0 && originProductList != null && originProductList.size() > 0) { //添加或修改产地产出物信息
            umsMemberOriginProductService.saveOrUpdate(originProductList,umsMemberOrigin.getId());
        }

        return i;
    }

    @Override
    public UmsMemberOriginParam findById(long id) {
        return umsMemberOriginDao.findById(id);
    }

    @Override
    public int delete(long id) {
        long i = umsMemberOriginDao.deleteOneDataCheck(id);
        if(i>0){
            throw new GlobalException("该生产地以绑定商品！无法删除");
        }
        UmsMemberOrigin origin = new UmsMemberOrigin();
        origin.setId(id);
        origin.setState(2);
        return umsMemberOriginMapper.updateByPrimaryKeySelective(origin);
    }

    @Override
    public List<SelectVo> listSelect(long compId) {
        return umsMemberOriginDao.listSelect(compId);
    }

}
