package com.dxhy.customs.controller;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dxhy.api.model.config.UserInfo;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigEntity;
import com.dxhy.api.model.custom.TdxCustomsRecord;
import com.dxhy.common.constant.CommonConstants;
import com.dxhy.common.controller.AbstractController;
import com.dxhy.common.util.UserInfoUtil;
import com.dxhy.common.utils.R;
import com.dxhy.customs.dao.BasisSysEnterpriceConfigDao;
import com.dxhy.customs.dao.CustomsRecordDao;
import com.dxhy.customs.dao.CustomsTdxLqDkCustomFpycxxDao;
import com.dxhy.customs.entity.TdxLqDkCustomFpycxx;
import com.dxhy.customs.model.TdxCustomsRecordModelDTO;
import com.dxhy.customs.service.CustomsRecordDkrzService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 缴款书认证
 *
 * @author 陈刚扬
 * @date 2020/8/10
 */
@RestController
@RequestMapping("/customsRecordRzdk")
@Slf4j
public class CustomsRecordRzdkController extends AbstractController {
    @Resource
    private CustomsRecordDkrzService tDxCustomsRecordService;

    @Resource
    private BasisSysEnterpriceConfigDao basisSysEnterpriceConfigDao;

    @Resource
    private CustomsRecordDao customsRecordDao;

    @Resource
    private CustomsTdxLqDkCustomFpycxxDao customsTdxLqDkCustomFpycxxDao;

    /**
     * 抵扣认证 - 缴款书手工认证-列表查询
     *
     * @author 陈刚扬
     * @date 2020/8/10
     * @param page
     *            入参
     * @param dto
     *            入参
     * @return org.springframework.http.ResponseEntity<?>
     */
    @PostMapping("/querySgByPage")
    public ResponseEntity<?> querySgByPage(Page<?> page, @RequestBody TdxCustomsRecordModelDTO dto) {
        try {
            return ResponseEntity
                .ok(R.ok().put("data", tDxCustomsRecordService.querySgByPage(page, dto, this.getUserInfo())));
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            return ResponseEntity.ok(R.error(CommonConstants.MSG_ERR_DEFAULT));
        }
    }

    /**
     * 缴款书调教认证抵扣、不抵扣
     *
     * @author 陈刚扬
     * @date 2020/8/10
     * @param dto
     *            入参
     * @return org.springframework.http.ResponseEntity<?>
     */
    @PostMapping("/approveSg")
    public ResponseEntity<?> approveSg(@RequestBody TdxCustomsRecordModelDTO dto) {
        try {
            String result = tDxCustomsRecordService.approveSg(dto, this.getUserInfo());
            return ResponseEntity.ok(R.ok().put("data", result));
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            return ResponseEntity.ok(R.error(e.getMessage()));
        }
    }

    /**
     * 缴款书认证抵扣excel导入校验
     *
     * @author 陈刚扬
     * @date 2020/8/10
     * @param pramsMap
     *            入参
     * @return org.springframework.http.ResponseEntity<?>
     */
    @PostMapping("/importCert")
    public ResponseEntity<?> importCert(@RequestBody Map<String, Object> pramsMap) {
        try {

            List<String> gfshList = UserInfoUtil.getGfshAll(getUserInfo().getOrg());
            pramsMap.put("dbName", getUserInfo().getDbName());

            pramsMap.put("gfsh", gfshList);
            String datalist = (String)pramsMap.get("datalist");
            if (StringUtils.isNotBlank(datalist)) {
                pramsMap.put("datalist", datalist);
            } else {
                return ResponseEntity.ok(R.error("请上传excel文件!"));
            }

            return ResponseEntity.ok(Objects
                .requireNonNull(R.ok().put("data", tDxCustomsRecordService.importCert(pramsMap, getUserInfo()))));
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            return ResponseEntity.ok(R.error(CommonConstants.MSG_ERR_DEFAULT));
        }
    }

    /**
     * 文件下载
     *
     */
    @RequestMapping("/downLoad")
    @ResponseBody
    public ResponseEntity<?> downLoadFtpFileMould(String fileName, HttpServletResponse response) {
        try {
            File downLoadFile = new File(this.getClass().getResource("/").getPath() + "template/" + fileName);
            // 获取文件的长度
            long fileLength = downLoadFile.length();
            BufferedInputStream bis;
            BufferedOutputStream bos;

            // 设置文件输出类型
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition",
                "attachment; filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
            // 设置输出长度
            response.setHeader("Content-Length", String.valueOf(fileLength));
            // 获取输入流
            bis = new BufferedInputStream(new FileInputStream(downLoadFile));
            // 输出流
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bos.flush();
            // 关闭流
            bis.close();
            bos.close();
            return null;
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            return ResponseEntity.ok(R.error(CommonConstants.MSG_ERR_DEFAULT));
        }
    }

    /**
     * 抵扣认证 - 缴款书设置不抵扣-列表查询
     */
    @PostMapping("/queryBdkByPage")
    public ResponseEntity<?> queryBdkByPage(Page<?> page, @RequestBody TdxCustomsRecordModelDTO dto) {
        try {
            return ResponseEntity
                .ok(R.ok().put("data", tDxCustomsRecordService.queryBdkByPage(page, dto, this.getUserInfo())));
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            return ResponseEntity.ok(R.error(CommonConstants.MSG_ERR_DEFAULT));
        }
    }

    /**
     * 抵扣认证 - 缴款书认证查询-列表查询
     */
    @PostMapping("/queryRzcxByPage")
    public ResponseEntity<?> queryRzcxByPage(Page<?> page, @RequestBody TdxCustomsRecordModelDTO dto) {
        try {
            return ResponseEntity
                .ok(R.ok().put("data", tDxCustomsRecordService.queryRzcxByPage(page, dto, this.getUserInfo())));
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            return ResponseEntity.ok(R.error(CommonConstants.MSG_ERR_DEFAULT));
        }
    }

    /**
     * 抵扣认证 - 缴款书认证查询-撤销抵扣或撤销不抵扣
     */
    @PostMapping("/approveCxrz")
    public ResponseEntity<?> approveCxrz(@RequestBody TdxCustomsRecordModelDTO dto) {
        try {
            UserInfo userInfo = this.getUserInfo();
            String result = tDxCustomsRecordService.approveCxrz(dto, userInfo);

            //此接口ids必传，也可能ids和gfsh都传
            // 撤销认证    ，     异常缴款书认证
            if(StringUtils.isEmpty(dto.getGfsh())){
                log.info("撤销认证按钮");
                for (int i = 0; i < dto.getIds().size(); i++) {
                    //先找到税号，再判断是否乐企
                    TdxCustomsRecord tdxCustomsRecord = customsRecordDao.selectOne(new LambdaQueryWrapper<TdxCustomsRecord>()
                            .select(TdxCustomsRecord::getGfTaxNo)
                            .eq(TdxCustomsRecord::getId, dto.getIds().get(i)));
                    String gfTaxNo = tdxCustomsRecord.getGfTaxNo();
                    //处理异常缴款书逻辑
                    delYcCustomsByids(dto.getIds().get(i),gfTaxNo,result);
                }
            }else{
                log.info("异常缴款书撤销按钮");
                delYcCustoms(dto.getIds(),dto.getGfsh(),result);
            }
            return ResponseEntity.ok(R.ok().put("data", result));
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
            return ResponseEntity.ok(R.error(e.getMessage()));
        }
    }

    /**
    * @Description 通过id删除对应异常信息
    * @param id
    * @param gfTaxNo
    * @param result
    * @Return void
    * @Author wangruwei
    * @Date 2024/11/14 10:19
    **/
    private void delYcCustomsByids(String id,String gfTaxNo, String result) {
        log.info("判断是否乐企税号");
        //判断是否为大企业税号
        SysEnterpriseConfigEntity enterpriseConfigEntity = basisSysEnterpriceConfigDao.selectOne(new LambdaQueryWrapper<SysEnterpriseConfigEntity>()
                .eq(SysEnterpriseConfigEntity::getNsrsbh, gfTaxNo)
                .eq(SysEnterpriseConfigEntity::getJrfs,"1")
        );
        if (enterpriseConfigEntity != null) {
            String resultJsonStr = Base64.decodeStr(result);
            log.info("乐企税号调原有撤销认证不抵扣接口返回:{},解析出:{}",result,resultJsonStr);
            JSONObject jsonObject = JSONObject.parseObject(resultJsonStr);
            //如果是空，撤销成功，删除异常表中对应数据
            if(StringUtils.isEmpty(jsonObject.getString("message"))){
                log.info("海关缴款书撤销抵扣或不抵扣，成功后，删除lqcustomFpycxx表数据");
                TdxCustomsRecord byId = customsRecordDao.selectById(id);
                LambdaQueryWrapper<TdxLqDkCustomFpycxx> fpycxxWrapper = new LambdaQueryWrapper<>();
                fpycxxWrapper.eq(TdxLqDkCustomFpycxx::getJkshm, byId.getCustomsCode());
                customsTdxLqDkCustomFpycxxDao.delete(fpycxxWrapper);
            }

        }
    }

    private void delYcCustoms(List<String> ids,String gfTaxNo, String result) {
        log.info("判断是否乐企税号");
        //判断是否为大企业税号
        SysEnterpriseConfigEntity enterpriseConfigEntity = basisSysEnterpriceConfigDao.selectOne(new LambdaQueryWrapper<SysEnterpriseConfigEntity>()
                .eq(SysEnterpriseConfigEntity::getNsrsbh, gfTaxNo)
                .eq(SysEnterpriseConfigEntity::getJrfs,"1")
        );
        if (enterpriseConfigEntity != null) {
            String resultJsonStr = Base64.decodeStr(result);
            log.info("乐企税号调原有撤销认证不抵扣接口返回:{},解析出:{}",result,resultJsonStr);
            int customCxrzNum=0;
            JSONObject jsonObject = JSONObject.parseObject(resultJsonStr);
            //如果是空，撤销成功，删除异常表中对应数据
            if(StringUtils.isEmpty(jsonObject.getString("message"))){
                log.info("海关缴款书撤销抵扣或不抵扣，成功后，删除lqcustomFpycxx表数据");
                for (String idstr : ids) {
                    TdxCustomsRecord byId = customsRecordDao.selectById(idstr);
                    LambdaQueryWrapper<TdxLqDkCustomFpycxx> fpycxxWrapper = new LambdaQueryWrapper<>();
                    fpycxxWrapper.eq(TdxLqDkCustomFpycxx::getJkshm, byId.getCustomsCode());
                    customsTdxLqDkCustomFpycxxDao.delete(fpycxxWrapper);
                    customCxrzNum++;
                }
                log.info("删除lqcustomFpycxx表数据条数:{}",customCxrzNum);
            }

        }
    }
}
