package com.iotechn.unimall.admin.api.sys;


import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.admin.utils.DateUtils;
import com.iotechn.unimall.core.exception.AdminServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.domain.CollectionPaymentDO;
import com.iotechn.unimall.data.dto.CollectionPaymentDTO;
import com.iotechn.unimall.data.dto.CollectionPaymentTiDTO;
import com.iotechn.unimall.data.mapper.CollectionPaymentMapper;
import com.iotechn.unimall.data.model.Page;
import com.iotechn.unimall.data.util.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.RowBounds;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
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.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.util.StringUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Generate Code By Unimall
 */
@Service
@Slf4j
public class CollectionPaymentServiceImpl implements CollectionPaymentService {

    @Autowired
    private CollectionPaymentMapper collectionPaymentMapper;
    @Value("C://file//crew/")
    private String localPath;

    @Override
    public boolean delete(Long id) throws ServiceException {
        return collectionPaymentMapper.deleteById(id) > 0;
    }

    @Override
    public Page<CollectionPaymentDO> list(CollectionPaymentDTO selectDTO, Integer page, Integer limit) throws ServiceException {


        Wrapper<CollectionPaymentDO> wrapper = new EntityWrapper<CollectionPaymentDO>();
        if (!StringUtils.isEmpty(selectDTO.getBusinessType())) {
            wrapper.eq("business_type", selectDTO.getBusinessType());
        }
        if (!StringUtils.isEmpty(selectDTO.getStatus())) {
            wrapper.eq("status", selectDTO.getStatus());
        }
        if (!StringUtils.isEmpty(selectDTO.getPayNo())) {
            wrapper.like("pay_no", selectDTO.getPayNo());
        }
        if (!StringUtils.isEmpty(selectDTO.getReceivingWithdrawingPeople())) {
            wrapper.like("receiving_withdrawing_people", selectDTO.getReceivingWithdrawingPeople());
        }
        if (!StringUtils.isEmpty(selectDTO.getReceivingWithdrawingRegion())) {
            wrapper.like("receiving_withdrawing_region", selectDTO.getReceivingWithdrawingRegion());
        }
        if (StringUtil.isNotEmpty(selectDTO.getStartDate())) {
            wrapper.and("DATE_FORMAT(receipt_payment_date,'%Y%m%d') >= DATE_FORMAT('" + selectDTO.getStartDate() + "','%Y%m%d')");
        }
        if (StringUtil.isNotEmpty(selectDTO.getEndDate())) {
            wrapper.and("DATE_FORMAT(receipt_payment_date,'%Y%m%d') <= DATE_FORMAT('" + selectDTO.getEndDate() + "','%Y%m%d')");

        }
        wrapper.orderBy("receipt_payment_date",false);

        List<CollectionPaymentDO> list = collectionPaymentMapper.selectPage(new RowBounds((page - 1) * limit, limit), wrapper);
//        for (int i=0;i<list.size();i++){
//            list.get(i).setReceiptPaymentDate(DateUtil.);
//        }
        Integer count = collectionPaymentMapper.selectCount(wrapper);
        return new Page<CollectionPaymentDO>(list, page, limit, count);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CollectionPaymentDO create(CollectionPaymentDTO insertDTO) throws ServiceException {
        Date now = new Date();
        CollectionPaymentDO insertDO = new CollectionPaymentDO();
        BeanUtils.copyProperties(insertDTO, insertDO);
        insertDO.setGmtUpdate(now);
        insertDO.setGmtCreate(now);
        insertDO.setStatus(0);
        insertDO.setPayNo(getlinkNo());
        if (collectionPaymentMapper.insert(insertDO) > 0) {
            return insertDO;
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }


    public String getlinkNo() {
        String linkNo = "";
        // 用字符数组的方式随机
        String model = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        char[] m = model.toCharArray();
        for (int j = 0; j < 6; j++) {
            char c = m[(int) (Math.random() * 36)];
            // 保证六位随机数之间没有重复的
            if (linkNo.contains(String.valueOf(c))) {
                j--;
                continue;
            }
            linkNo = linkNo + c;
        }
        return linkNo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createAll(List<CollectionPaymentDTO> collectionPaymentDTOS) throws ServiceException {
        Date now = new Date();
//        List<CollectionPaymentDTO> collectionPaymentDTOS = insertDTO.getCollectionPaymentDTOList();
        collectionPaymentDTOS = JSON.parseArray(JSONObject.toJSONString(collectionPaymentDTOS), CollectionPaymentDTO.class);
        if (!CollectionUtils.isEmpty(collectionPaymentDTOS)) {
            for (int i = 0; i < collectionPaymentDTOS.size(); i++) {
                CollectionPaymentDO insertDO = new CollectionPaymentDO();
                CollectionPaymentDTO dto = collectionPaymentDTOS.get(i);
                BeanUtils.copyProperties(dto, insertDO);
                insertDO.setGmtUpdate(now);
                insertDO.setGmtCreate(now);
                insertDO.setStatus(0);
                collectionPaymentMapper.insert(insertDO);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String edit(CollectionPaymentDTO editDTO) throws ServiceException {
        Date now = new Date();
        CollectionPaymentDO updateDO = new CollectionPaymentDO();
        BeanUtils.copyProperties(editDTO, updateDO);
        updateDO.setGmtUpdate(now);
        if("1".equals(editDTO.getFlag())){
            updateDO.setStatus(1);
        }

        if (collectionPaymentMapper.updateById(updateDO) > 0) {
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }


    @Override
    public List<CollectionPaymentDTO> listReport(CollectionPaymentDTO selectDTO) throws ServiceException {
        // 收款
        Wrapper<CollectionPaymentDO> wrapper = new EntityWrapper<CollectionPaymentDO>();
        wrapper.eq("business_type", "1");
        wrapper.eq("status", 0);
        if (selectDTO != null && !StringUtils.isEmpty(selectDTO.getReceivingWithdrawingRegion())) {
            wrapper.eq("receiving_withdrawing_region", selectDTO.getReceivingWithdrawingRegion());
        }
        List<CollectionPaymentDO> list = collectionPaymentMapper.selectList(wrapper);
        // 提款
        Wrapper<CollectionPaymentDO> wrapper1 = new EntityWrapper<CollectionPaymentDO>();
        wrapper1.eq("business_type", "2");
        wrapper1.eq("status", 0);
        if (selectDTO != null && !StringUtils.isEmpty(selectDTO.getReceivingWithdrawingRegion())) {
            wrapper1.eq("receiving_withdrawing_region", selectDTO.getReceivingWithdrawingRegion());
        }
        List<CollectionPaymentDO> list1 = collectionPaymentMapper.selectList(wrapper1);
        double shouMoneyrmb = 0d;
        double fuMoneyrmb = 0d;
        double shouMoneyo = 0d;
        double fuMoneyo = 0d;
        // shou
        if (!CollectionUtils.isEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                shouMoneyrmb = shouMoneyrmb + list.get(i).getDeductionRmb();
                shouMoneyo = shouMoneyo + list.get(i).getDeductionEuro();
            }

        }
        // ti
        if (!CollectionUtils.isEmpty(list1)) {
            for (int i = 0; i < list1.size(); i++) {
                fuMoneyrmb = fuMoneyrmb + list1.get(i).getDeductionRmb();
                fuMoneyo = fuMoneyo + list1.get(i).getDeductionEuro();
            }
        }
        List<CollectionPaymentDTO> collectionPaymentDTOS = new ArrayList<>();
        CollectionPaymentDTO collectionPaymentDTO = new CollectionPaymentDTO();
        collectionPaymentDTO.setType("shou");
        collectionPaymentDTO.setDeductionEurotj(shouMoneyo);
        collectionPaymentDTO.setDeductionRmbtj(shouMoneyrmb);
        collectionPaymentDTOS.add(collectionPaymentDTO);

        CollectionPaymentDTO collectionPaymentDTO1 = new CollectionPaymentDTO();
        collectionPaymentDTO1.setType("ti");
        collectionPaymentDTO1.setDeductionEurotj(fuMoneyo);
        collectionPaymentDTO1.setDeductionRmbtj(fuMoneyrmb);
        collectionPaymentDTOS.add(collectionPaymentDTO1);

        CollectionPaymentDTO collectionPaymentDTO2 = new CollectionPaymentDTO();
        collectionPaymentDTO2.setType("jing");
        collectionPaymentDTO2.setDeductionEurotj(shouMoneyo-fuMoneyo);
        collectionPaymentDTO2.setDeductionRmbtj(shouMoneyrmb-fuMoneyrmb);
        collectionPaymentDTOS.add(collectionPaymentDTO2);
        return collectionPaymentDTOS;
    }

    /********************************************************************************导出********************************************/

    @Override
    public String export(CollectionPaymentDTO collectionPaymentDTO, HttpServletResponse response) throws Exception {

        if (collectionPaymentDTO.getCollectionPaymentDTOList() != null && "1".equals(collectionPaymentDTO.getCollectionPaymentDTOList().get(0).getBusinessType())) {
            ExcelUtil<CollectionPaymentDTO> util = new ExcelUtil<CollectionPaymentDTO>(CollectionPaymentDTO.class);
            return util.exportExcel(collectionPaymentDTO.getCollectionPaymentDTOList(), "收款记录");
        } else if (collectionPaymentDTO.getCollectionPaymentTiDTOList() != null && "2".equals(collectionPaymentDTO.getCollectionPaymentTiDTOList().get(0).getBusinessType())) {
            ExcelUtil<CollectionPaymentTiDTO> util = new ExcelUtil<CollectionPaymentTiDTO>(CollectionPaymentTiDTO.class);
            return util.exportExcel(collectionPaymentDTO.getCollectionPaymentTiDTOList(), "提款记录");
        } else {
            return "ng";
        }

    }


    /**
     * 下载
     *
     * @param path
     * @param response
     */
    private void download(String path, HttpServletResponse response, Workbook wb) {

        try {

            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String fileName = file.getName();
            // 给文件名编码
            fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");

            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

            // 定义byte输出流
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            // 写导出文件
            wb.write(out);

            // 取得模板文件中的数据
            byte[] result = out.toByteArray();

            // 设置输出数据类型
            response.setContentType("application/vnd.ms-excel");
            // 设置输出数据长度
            response.setContentLength(result.length);

            // 设置文件名称
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            // 将文件流输出到画面
            response.getOutputStream().write(result);

            out.flush();
            out.close();

        } catch (IOException ex) {
            log.debug(ex.getMessage());
        }

    }

}
