package com.xxfc.platform.vehicle.biz;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.StringToolsUtil;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.vehicle.entity.BranchCompanyStockRight;
import com.xxfc.platform.vehicle.mapper.*;
import com.xxfc.platform.vehicle.pojo.BranchCompanyStockSearchVo;
import com.xxfc.platform.vehicle.pojo.dto.BranchCompanyStockRightDTO;
import com.xxfc.platform.vehicle.pojo.dto.BranchCompanyStockRightFindDTO;
import com.xxfc.platform.vehicle.pojo.vo.BranchCompanyStockInfoRightVo;
import com.xxfc.platform.vehicle.pojo.vo.BranchCompanyStockRightForWeChatOfficeVO;
import com.xxfc.platform.vehicle.util.excel.ExcelImport;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class BranchCompanyStockRightBiz extends BaseBiz<BranchCompanyStockRightMapper, BranchCompanyStockRight> {


    @Autowired
    BranchCompanyBiz branchCompanyBiz;

    @Autowired
    BranchCompanyStockApplyInfoBiz branchCompanyStockApplyInfoBiz;


    @Value("${branchCompanyPic.stock}")
    private String companyPic;

    //获取股权列表
    public PageInfo<BranchCompanyStockInfoRightVo> search(BranchCompanyStockSearchVo searchVo) {
        PageHelper.startPage(searchVo.getPage(), searchVo.getLimit());
        return new PageInfo<>(mapper.search(searchVo));
    }

    //更新股权
    public ObjectRestResponse updStockInfo(BranchCompanyStockInfoRightVo stockInfoVo) {
        if (stockInfoVo == null || stockInfoVo.getCompanyId() == null || stockInfoVo.getCompanyId() == 0) {

        }
        Integer id = stockInfoVo.getId();
        if (!checkInfo(id, stockInfoVo.getCompanyId())) {
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "分公司已存在");
        }
        BranchCompanyStockRight stockInfo = new BranchCompanyStockRight();
        BeanUtils.copyProperties(stockInfoVo, stockInfo);
        if (stockInfo.getBalance() == null) {
            stockInfo.setBalance(stockInfo.getTotal());
        }
        if (stockInfoVo.getState() == null) {
            stockInfo.setStockState(0);
        }
        if (id == null || id == 0) {
            mapper.insertSelective(stockInfo);
        } else {
            mapper.updateByPrimaryKeySelective(stockInfo);
        }
        return ObjectRestResponse.succ();
    }

    //检查是否存在分公司
    public boolean checkInfo(Integer id, Integer companyId) {
        Example example = new Example(BranchCompanyStockRight.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("companyId", companyId);
        if (id != null && id > 0) {
            criteria.andNotEqualTo("id", id);
        }
        List<BranchCompanyStockRight> list = mapper.selectByExample(example);
        if (list.size() > 0)
            return false;
        return true;
    }


    //获取股权信息
    public BranchCompanyStockInfoRightVo getInfoById(Integer id) {
        return mapper.selectInfoById(id);
    }


    /**
     * 获取所有的股权单价
     *
     * @return
     */
    public List<Integer> getAllPrice() {
        return mapper.selectAllPrice();
    }


    //更新股份
    public int updateBalance(Integer companyId, Integer balance, Integer lastBalance) {
        return mapper.updateBalance(companyId, balance, lastBalance);
    }

    //删除股权
    public void delete(Integer id) {
        BranchCompanyStockRight stockRight = new BranchCompanyStockRight();
        stockRight.setId(id);
        stockRight.setIsDel(1);
        mapper.updateByPrimaryKeySelective(stockRight);
    }

    //导入
    public ObjectRestResponse<String> importExcel(MultipartFile multipartfile, HttpServletRequest request) {
        try {
            List<String[]> readExcel = ExcelImport.getExcelData(multipartfile);
            if (readExcel.size() < 4) {
                return ObjectRestResponse.createFailedResult(ResultCode.NULL_CODE, "导入不能没数据！！！");
            }
            List<BranchCompanyStockRight> list = new ArrayList<>();
            for (int i = 3; i < readExcel.size(); i++) {
                BranchCompanyStockRight stockInfoVo = new BranchCompanyStockRight();
                String[] str = readExcel.get(i);
                String companyName = str[2];
                Integer companyId = mapper.getCompanyInfo(companyName);
                if (companyId == null || companyId == 0) {
                    return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "第" + (i + 1) + "行的" + companyName + "不匹配");
                }
                String str3 = str[3];
                if (StringUtils.isBlank(str3)) {
                    return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "第" + (i + 1) + "行的股价不能为空");
                }
                if (str3.contains("万港币/股")) {
                    str3 = str3.replace("万港币/股", "");
                } else {
                    str3 = str3.replace("万/股", "");
                }
                if (!StringToolsUtil.isBigDecimal(str3) || !StringToolsUtil.isNumer(str[4]) || !StringToolsUtil.isNumer(str[5])) {
                    return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "第" + (i + 1) + "行的数据格式不对");
                }
                BigDecimal price = new BigDecimal(str3);
                price = price.multiply(new BigDecimal("10000"));
                Integer balance = Integer.parseInt(str[4]);
                Integer total = Integer.parseInt(str[5]) + balance;
                stockInfoVo.setPrice(price);
                stockInfoVo.setBalance(balance);
                stockInfoVo.setTotal(total);
                stockInfoVo.setStockState(2);
                list.add(stockInfoVo);
            }
            mapper.addCompamyList(list);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "网络异常！");
        }
        return ObjectRestResponse.succ();
    }


    public PageDataVO<BranchCompanyStockRightForWeChatOfficeVO> findWithPageByPriceOrCode(BranchCompanyStockRightFindDTO branchCompanyStockRightFindDTO) {
         PageDataVO<BranchCompanyStockRightForWeChatOfficeVO> dataPage = new PageDataVO<>();
        PageDataVO<BranchCompanyStockRightDTO> pageDataVO = PageDataVO.pageInfo(branchCompanyStockRightFindDTO.getPage(), branchCompanyStockRightFindDTO.getLimit(),
                () -> mapper.findWithPageByPriceOrCode(branchCompanyStockRightFindDTO.getPrice(), branchCompanyStockRightFindDTO.getAddrProvince(), branchCompanyStockRightFindDTO.getAddrCity()));

        List<BranchCompanyStockRightDTO> data = pageDataVO.getData();
        if (CollectionUtils.isEmpty(data)){
            return dataPage;
        }

        List<BranchCompanyStockRightForWeChatOfficeVO> stockRights = new ArrayList<>();
        BranchCompanyStockRightForWeChatOfficeVO branchCompanyStockRightForWeChatOfficeVO;
        for (BranchCompanyStockRightDTO branchCompanyStockRight : data) {
            branchCompanyStockRightForWeChatOfficeVO= new BranchCompanyStockRightForWeChatOfficeVO();
            BeanUtils.copyProperties(branchCompanyStockRight,branchCompanyStockRightForWeChatOfficeVO);
            stockRights.add(branchCompanyStockRightForWeChatOfficeVO);
        }
        dataPage.setTotalCount(pageDataVO.getTotalCount());
        dataPage.setTotalPage(pageDataVO.getTotalPage());
        dataPage.setPageNum(pageDataVO.getPageNum());
        dataPage.setPageSize(pageDataVO.getPageSize());
        dataPage.setData(stockRights);
        return dataPage;
    }

    public BranchCompanyStockRight selectByCompanyId(Integer companyId) {
        BranchCompanyStockRight branchCompanyStockRight = new BranchCompanyStockRight();
        branchCompanyStockRight.setCompanyBaseId(companyId);
        branchCompanyStockRight.setIsDel(0);
        BranchCompanyStockRight result = mapper.selectOne(branchCompanyStockRight);
        return result;
    }
}
