package org.springblade.customer.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springblade.audit.entity.AuditComplaintDetail;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.api.R;
import org.springblade.customer.dto.LlAllin1Cs10010DTO;
import org.springblade.customer.dto.LlAllin1CsPrmDTO;
import org.springblade.customer.entity.CustomerLiallinRecord;
import org.springblade.customer.entity.LlAllin1Cs10010;
import org.springblade.customer.entity.LlAllin1CsPrm;
import org.springblade.customer.enums.LlAllinEnum;
import org.springblade.customer.listener.LlAllin1Cs10010Listener;
import org.springblade.customer.listener.LlAllin1CsPrmListener;
import org.springblade.customer.service.ICustomerLiallinRecordService;
import org.springblade.customer.service.ILlAllin1Cs10010Service;
import org.springblade.customer.service.ILlAllin1CsPrmService;
import org.springblade.system.client.UserClient;
import org.springblade.system.client.model.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 流量一点看全-PRM投诉 前端控制器
 * </p>
 *
 * @author zbc
 * @since 2023-02-08
 */
@RestController
@Api(value = "投诉管理", tags = "投诉管理")
@RequestMapping("/llAllin1CsPrm")
@Slf4j
public class LlAllin1CsPrmController {


    @Autowired
    private ILlAllin1Cs10010Service llAllin1Cs10010Service;

    @Autowired
    private ILlAllin1CsPrmService llAllin1CsPrmService;

    @Autowired
    private ICustomerLiallinRecordService customerLiallinRecordService;

    @Autowired
    private UserClient userClient;

    @Value("${blade.file.uploadPath}")
    private String picDir;



    @GetMapping("/page")
    @ApiOperation(value = "分页")
    public R page(String excelCode, Query query) {
        IPage<CustomerLiallinRecord> page = Condition.getPage(query);
        IPage<CustomerLiallinRecord> res = customerLiallinRecordService.page(page,new LambdaQueryWrapper<CustomerLiallinRecord>()
            .eq(CustomerLiallinRecord::getCategoryCode,excelCode)
        );
        return R.data(res);
    }


    @PostMapping("/import")
    @ApiOperation(value = "报表导入", notes = "报表导入")
    public R entrance(@RequestParam(required = true, name = "file") MultipartFile file,
                      @RequestParam(required = true, name = "excelCode") String excelCode
    ) {
        if (file == null) {
            return R.fail("导入文件不能为空");
        }
        if (StringUtils.isBlank(excelCode)) {
            return R.fail("excelCode不能为空");
        }
        //prm 投诉
        if (LlAllinEnum.PRM.getCode().equals(excelCode)) {
            return prmImport(file, excelCode);
        }
        //10010 投诉
        if (LlAllinEnum.I00I0.getCode().equals(excelCode)) {
            return I00I0Import(file, excelCode);
        }
        return R.fail("excelCode 参数异常");
    }


    private R prmImport(MultipartFile file, String excelCode) {
        Long userId = SecureUtil.getUserId();
        String oFileName = file.getOriginalFilename();
        String fileSuffix = oFileName.substring(oFileName.lastIndexOf("."));
        if (
                !".xls".equalsIgnoreCase(fileSuffix) &&
                        !".xlsx".equalsIgnoreCase(fileSuffix)
        ) {
            return R.fail("只能上传xlsx/xls类型的文件");
        }
        String tempFileName = UUID.randomUUID().toString() + fileSuffix;
        File f = new File(picDir + tempFileName);
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), f);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String path = "uploads/" + tempFileName;

        UserModel user = userClient.getById(userId);
        LlAllin1CsPrmListener easyExcelListener = new LlAllin1CsPrmListener();
        List<LlAllin1CsPrmDTO> excelList = easyExcelListener.list;
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, LlAllin1CsPrmDTO.class, easyExcelListener).sheet().doRead();
            log.info("prm投诉读取数据条数" + excelList.size());
            List<LlAllin1CsPrm> voList = new ArrayList<LlAllin1CsPrm>();
            if (excelList != null && !excelList.isEmpty()) {
                for (LlAllin1CsPrmDTO obj : excelList) {
                    try {
                        LlAllin1CsPrm bean = new LlAllin1CsPrm();
                        BeanUtils.copyProperties(obj, bean);
                        //受理时间处理
                        if (StringUtils.isNotBlank(obj.getFinishTime())) {
                            String regEx = "[\n`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。， ·、？]";
                            String replace = "";
                            String trim = obj.getFinishTime().replaceAll(regEx, replace).trim();
                            String month = trim.replaceAll("\\-", "");
                            bean.setThemonth(Integer.valueOf(month.substring(0,6)));
                        }
                        voList.add(bean);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.info("obj = {}",obj);
                    }
                }
            }
            log.info("prm投诉填装数据条数" + voList.size());
            //清除同月份旧数据
            Integer month = voList.get(0).getThemonth();
            boolean rem = llAllin1CsPrmService.remove(new LambdaQueryWrapper<LlAllin1CsPrm>()
                    .eq(LlAllin1CsPrm::getThemonth,month)
            );
            log.info("prm投诉 删除同月份旧数据 执行结果 {}",rem);
            List<LlAllin1CsPrm> finalVoList = voList;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean fct = llAllin1CsPrmService.saveBatch(finalVoList);
                    log.info("prm投诉 投诉数据导入结果 === {}",fct);
                    if(fct){
                        CustomerLiallinRecord entity = new CustomerLiallinRecord();
                        entity.setCategoryCode(excelCode);
                        entity.setReportName(file.getOriginalFilename());
                        entity.setCreateUser(user.getName());
                        entity.setReportUrl(path);
                        entity.setCreateTime(new Date());
                        boolean save = customerLiallinRecordService.save(entity);
                        log.info("导入记录保存完成 === {}",save);
                    }
                }
            }).start();
            return R.success("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("导入失败");
        }

    }


    private R I00I0Import(MultipartFile file, String excelCode) {
        Long userId = SecureUtil.getUserId();
        String oFileName = file.getOriginalFilename();
        String fileSuffix = oFileName.substring(oFileName.lastIndexOf("."));
        if (
                !".xls".equalsIgnoreCase(fileSuffix) &&
                        !".xlsx".equalsIgnoreCase(fileSuffix)
        ) {
            return R.fail("只能上传xlsx/xls类型的文件");
        }
        String tempFileName = UUID.randomUUID().toString() + fileSuffix;
        File f = new File(picDir + tempFileName);
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), f);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String path = "uploads/" + tempFileName;

        UserModel user = userClient.getById(userId);
        LlAllin1Cs10010Listener easyExcelListener = new LlAllin1Cs10010Listener();
        List<LlAllin1Cs10010DTO> excelList = easyExcelListener.list;
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, LlAllin1Cs10010DTO.class, easyExcelListener).sheet().doRead();
            log.info("读取数据条数" + excelList.size());
            List<LlAllin1Cs10010> voList = new ArrayList<LlAllin1Cs10010>();
            if (excelList != null && !excelList.isEmpty()) {
                for (LlAllin1Cs10010DTO obj : excelList) {
                    try {
                        LlAllin1Cs10010 bean = new LlAllin1Cs10010();
                        BeanUtils.copyProperties(obj, bean);
                        //受理时间处理
                        if (StringUtils.isNotBlank(obj.getTheday())) {
                            bean.setThemonth(Integer.valueOf(obj.getTheday().substring(0,6)));
                        }
                        voList.add(bean);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.info("obj = {}",obj);
                    }
                }
            }
            log.info("填装数据条数" + voList.size());
            //清除同月份旧数据
            Integer month = voList.get(0).getThemonth();
            boolean rem = llAllin1Cs10010Service.remove(new LambdaQueryWrapper<LlAllin1Cs10010>()
                .eq(LlAllin1Cs10010::getThemonth,month)
            );
            log.info("10010投诉 删除同月份旧数据 执行结果 {}",rem);
            List<LlAllin1Cs10010> finalVoList = voList;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean fct = llAllin1Cs10010Service.saveBatch(finalVoList);
                    log.info("10010 投诉数据导入结果 === {}",fct);
                    if(fct){
                        CustomerLiallinRecord entity = new CustomerLiallinRecord();
                        entity.setCategoryCode(excelCode);
                        entity.setReportName(file.getOriginalFilename());
                        entity.setCreateUser(user.getName());
                        entity.setReportUrl(path);
                        entity.setCreateTime(new Date());
                        boolean save = customerLiallinRecordService.save(entity);
                        log.info("导入记录保存完成 === {}",save);
                    }
                }
            }).start();
            return R.success("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("导入失败");
        }
    }
}

