package com.ywt.mg.web.controllers;


import com.ywt.mg.core.MGRight;
import com.ywt.mg.core.exceptions.AppMessageException;
import com.ywt.mg.core.utils.Checker;
import com.ywt.mg.core.utils.StringHelper;
import com.ywt.mg.core.utils.serializers.JsonSerializer;
import com.ywt.mg.domain.models.ConstantDef;
import com.ywt.mg.params.mealOrder.MealOrderListRequest;
import com.ywt.mg.services.AuthService;
import com.ywt.mg.services.DownloadRecordService;
import com.ywt.mg.services.IdGenerator;
import com.ywt.mg.services.MealOrderService;
import com.ywt.mg.web.BaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

@RequestMapping({"/mealOrder"})
@RestController("/mealOrder")
@MGRight
public class MealOrderController {

    private final Logger logger = LoggerFactory.getLogger(MealOrderController.class);


    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private DownloadRecordService downloadRecordService;

    @Autowired
    private MealOrderService mealOrderService;

    @Autowired
    private AuthService authService;


    @RequestMapping({"/downloadMealOrderList"})
    public BaseResponse downloadMealOrderList(@RequestBody MealOrderListRequest request) {
//        int currentAdminId = Checker.getIntegerValue(authService.getCurrentAdminId());
//        request.setCurrentAdminId(currentAdminId);
        // 插入记录
//        int hospital = 0;
//        if(request.getHosp() > 0){
//            hospital = authService.getCurrentHospitalId();
//            request.setHospitalId(hospital);
//        }
        int downloadRecordId = idGenerator.genDownloadRecordId();
        String name = "订餐订单";
        String fileName = "订餐订单";
        String excelSuffixFormat = ConstantDef.EXCEL_SUFFIX_FORMAT;
        String paramUrl = "/mealOrder/downloadMealOrderList";
        String paramJson = JsonSerializer.toJson(request);
        downloadRecordService.getOrInsertDownloadRecord(downloadRecordId, name, fileName + excelSuffixFormat, paramUrl, paramJson);
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    String shopIds = "0";
                    if (!Checker.isNone(request.getShopIds())) {
                        shopIds = URLDecoder.decode(request.getShopIds(), "UTF-8");
                    }
                    request.setShopIds(shopIds);
                    Boolean bIsStaff = getIsStaffParamCompat(request.getIsStaff());
                    request.setbIsStaff(bIsStaff);
                    mealOrderService.downloadMealOrderListNew(downloadRecordId, fileName, request);
                } catch (AppMessageException e) {
                    logger.error("MealOrderController#downloadMealOrderList(orderNo={} , name={} , mobile={} , type={} , " +
                                    "status={} , payStatus={} , payTimeStart={} , payTimeEnd={} , httpServletResponse={} ):\n {}",
                            e.getMessage(), e);
                } catch (Exception e) {
                    logger.error("MealOrderController#downloadMealOrderList(orderNo={} , name={} , mobile={} , type={} , " +
                                    "status={} , payStatus={} , payTimeStart={} , payTimeEnd={} , httpServletResponse={} ):\n {}",
                            request.getOrderNo(), name, request.getMobile(), request.getType(), request.getStatus(), request.getPayStatus(), request.getPayTimeStart(),
                            request.getPayTimeEnd(), e.getMessage(), e);
                }
            }
        };
        t.start();
        return new BaseResponse().succeed("后台下载中...");
    }


    private Boolean getIsStaffParamCompat(String isStaff) throws AppMessageException {
        if (StringHelper.isNullOrEmpty(isStaff)) return null;
        try {
            int integer = Integer.parseInt(isStaff);
            return integer == 1;
        } catch (NumberFormatException e) {
            throw new AppMessageException(String.format("参数有误：%s", isStaff));
        }
    }

    @RequestMapping({"/downloadMealOrderBillList"})
    public BaseResponse downloadMealOrderBillList(@RequestBody MealOrderListRequest request) {
//        int currentAdminId = Checker.getIntegerValue(authService.getCurrentAdminId());
//        request.setCurrentAdminId(currentAdminId);

        int downloadRecordId = idGenerator.genDownloadRecordId();
        String name = "订餐订单对账数据";
        String fileName = "订餐订单对账数据";
        String excelSuffixFormat = ConstantDef.EXCEL_SUFFIX_FORMAT;
        String paramUrl = "/mealOrder/downloadMealOrderBillList";
        String paramJson = JsonSerializer.toJson(request);
        downloadRecordService.getOrInsertDownloadRecord(downloadRecordId, name, fileName + excelSuffixFormat, paramUrl, paramJson);
        Thread t = new Thread() {
            @Override
            public void run() {
                int adminId = 0;
//                String shopIds = "";
//                if (request.getHospitalId() > 0) {
//                    adminId = authService.getCurrentAdminId();
//                    shopIds = mgAdminService.getNutrimealShopIdsByAdminId(adminId);
//                }
                try {


                    String shopIds = "0";
                    if (!Checker.isNone(request.getShopIds())) {
                        shopIds = URLDecoder.decode(request.getShopIds(), "UTF-8");
                    }
                    request.setShopIds(shopIds);
                    mealOrderService.downloadMealOrderBillList(downloadRecordId, fileName, request);
                } catch (Exception e) {
                    logger.error("MealOrderController#downloadMealOrderList(orderNo={} , name={} , mobile={} , type={} , " +
                                    "status={} , payStatus={} , payTimeStart={} , payTimeEnd={} , httpServletResponse={} ):\n {}",
                            request.getOrderNo(), name, request.getMobile(), request.getType(), request.getStatus(), request.getPayStatus(), request.getPayTimeStart(),
                            request.getPayTimeEnd(), e.getMessage(), e);
                    e.printStackTrace();
                }

            }
        };
        t.start();
        return new BaseResponse().succeed("后台下载中...");
    }


}
