package com.liquidnet.service.platform.controller.A_fskfsfs;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liquidnet.common.cache.redis.util.RedisDataSourceUtil;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.kylin.constant.KylinRedisConst;
import com.liquidnet.service.kylin.dto.param.platformFskfsfs.FskfsfsAddressExcelVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinOrderTicketVo;
import com.liquidnet.service.kylin.dto.vo.returns.KylinOrderRefundsVo;
import com.liquidnet.service.kylin.entity.KylinOrderRefunds;
import com.liquidnet.service.kylin.entity.KylinOrderTickets;
import com.liquidnet.service.kylin.mapper.KylinOrderRefundsMapper;
import com.liquidnet.service.kylin.mapper.KylinOrderTicketsMapper;
import com.mysql.cj.jdbc.result.ResultSetImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

/**
 * 临时数据处理
 *
 * @author jiangxiulong
 */
@Api(tags = "临时数据处理")
@RestController
@RequestMapping("fskfsfs")
@Slf4j
public class JxlDataKylinOrderController {

    @Value("${spring.datasource.url}")
    private String SQL_URL;
    @Value("${spring.datasource.username}")
    private String SQL_USER;
    @Value("${spring.datasource.password}")
    private String SQL_PWD;

    @Autowired
    private KylinOrderRefundsMapper kylinOrderRefundsMapper;
    @Autowired
    private KylinOrderTicketsMapper kylinOrderTicketsMapper;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisDataSourceUtil redisDataSourceUtil;

    @GetMapping("KO001")
    @ApiOperation("某演出快递票批量申请未退快递费bug临时数据处理")
    @ApiImplicitParams({
            @ApiImplicitParam(type = "query", dataType = "String", name = "performancesId", value = "演出id", required = true),
    })
    public ResponseDto KO001(
            @RequestParam("performancesId") String performancesId
    ) {
        try {
            String sql = "select aa.created_at, aa.order_tickets_id, aa.price, bb.price_actual,bb.number,count(1) as ssrefund_number, bb.price_express as b_price_express, aa.price_express, type, aa.order_refunds_id, bb.order_code\n" +
                    "from kylin_order_refunds as aa\n" +
                    "         join kylin_order_tickets as bb on aa.order_tickets_id = bb.order_tickets_id\n" +
                    "where bb.performance_title = '2024武汉草莓音乐节'\n" +
                    "  and bb.get_ticket_type = 'express'\n" +
                    "  and aa.price_express != bb.price_express\n" +
                    "  and aa.status = 0\n" +
                    "group by bb.order_code, bb.number\n" +
                    "HAVING\n" +
                    "        COUNT(1) = bb.number;";

            Connection connection = DriverManager.getConnection(SQL_URL, SQL_USER, SQL_PWD);
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSetImpl row = (ResultSetImpl) preparedStatement.executeQuery();
            while (row.next()) {
                String order_tickets_id = row.getString("order_tickets_id");
                String order_refunds_id = row.getString("order_refunds_id");
                BigDecimal b_price_express = row.getBigDecimal("b_price_express");

                // mysql
                KylinOrderRefunds aNew = KylinOrderRefunds.getNew();
                aNew.setPriceExpress(b_price_express);
                kylinOrderRefundsMapper.update(aNew,
                        Wrappers.lambdaUpdate(KylinOrderRefunds.class)
                                .eq(KylinOrderRefunds::getOrderRefundsId, order_refunds_id)
                );
                // mongodb
                mongoTemplate.getCollection(KylinOrderRefundsVo.class.getSimpleName()).updateOne(
                        Query.query(Criteria.where("orderRefundsId").is(order_refunds_id)).getQueryObject(),
                        new Document("$set", new Document("priceExpress", b_price_express))
                );
                // redis
                redisDataSourceUtil.getRedisKylinUtil().del(KylinRedisConst.ORDER_REFUND_BY_ORDER_ID + order_tickets_id);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseDto.success();
    }

    @PostMapping("KO002")
    @ApiOperation("修改快递票订单收货地址")
    @ApiImplicitParams({
            @ApiImplicitParam(type = "form", dataType = "File", name = "file", value = "文件", required = true)
    })
    public ResponseDto KO002(
            @RequestParam MultipartFile file
    ) {
        try {
            EasyExcel.read("/Users/jiangxiulong/Desktop" + File.separator + file.getOriginalFilename(), FskfsfsAddressExcelVo.class, new PageReadListener<FskfsfsAddressExcelVo>(dataList -> {
                for (FskfsfsAddressExcelVo demoData : dataList) {
                    String orderCode = demoData.getOrderCode();
                    String userName = demoData.getUserName();
                    String phone = demoData.getPhone();
                    String address = demoData.getAddress();
                    log.info("orderCode:{}，userName:{}，phone:{}，address:{}，", orderCode, userName, phone, address);

                    if (null == orderCode) {
                        continue;
                    }
                    // 获取订单 id
                    KylinOrderTickets kylinOrderTickets = kylinOrderTicketsMapper.selectOne(
                            Wrappers.lambdaQuery(KylinOrderTickets.class)
                                    .eq(KylinOrderTickets::getOrderCode, orderCode)
                    );
                    String orderTicketsId = kylinOrderTickets.getOrderTicketsId();
                    if (null == userName || userName.isEmpty()) {
                        userName = kylinOrderTickets.getExpressContacts();
                    }
                    if (null == phone || phone.isEmpty()) {
                        phone = kylinOrderTickets.getExpressPhone();
                    }
                    if (null == address || address.isEmpty()) {
                        address = kylinOrderTickets.getExpressAddress();
                    }

                    // mysql
                    KylinOrderTickets aNew = KylinOrderTickets.getNew();
                    aNew.setExpressContacts(userName);
                    aNew.setExpressPhone(phone);
                    aNew.setExpressAddress(address);
                    kylinOrderTicketsMapper.update(aNew,
                            Wrappers.lambdaUpdate(KylinOrderTickets.class)
                                    .eq(KylinOrderTickets::getOrderTicketsId, orderTicketsId)
                    );

                    // mongodb
                    mongoTemplate.getCollection(KylinOrderTicketVo.class.getSimpleName()).updateOne(
                            Query.query(Criteria.where("orderTicketsId").is(orderTicketsId)).getQueryObject(),
                            new Document("$set", new Document("expressContacts", userName)
                                    .append("expressAddress", address)
                                    .append("expressPhone", phone)
                            )
                    );

                    //redis
                    redisDataSourceUtil.getRedisKylinUtil().del(KylinRedisConst.ORDER + orderTicketsId);
                }
            })).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseDto.success();
    }

}
