package com.ywt.mg.web.controllers.pharmacy;


import com.fasterxml.jackson.databind.JsonNode;
import com.ywt.mg.configs.DomainConfigurer;
import com.ywt.mg.core.MGRight;
import com.ywt.mg.core.MGRightTypeDef;
import com.ywt.mg.core.utils.Checker;
import com.ywt.mg.core.utils.RandomUtil;
import com.ywt.mg.core.utils.serializers.JsonSerializer;
import com.ywt.mg.domain.models.ConstantDef;
import com.ywt.mg.params.downloadRecord.DownloadFileRequest;
import com.ywt.mg.params.downloadRecord.QueryDownloadRecordListRequest;
import com.ywt.mg.params.pharamcy.PharamcyDownloadPresRequest;
import com.ywt.mg.params.prescription.QueryPrescriptionListRequest;
import com.ywt.mg.services.AuthService;
import com.ywt.mg.services.DownloadRecordService;
import com.ywt.mg.services.IdGenerator;
import com.ywt.mg.services.PharmacyService;
import com.ywt.mg.web.BaseResponse;
import com.ywt.mg.web.DataResponse;
import com.ywt.mg.web.controllers.hospital.HospNatOrderController;
import io.swagger.annotations.ApiOperation;
import org.eclipse.jetty.util.UrlEncoded;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Base64;
import java.util.Map;

@RestController("/pharmacy")
@RequestMapping({"/pharmacy"})
@MGRight
public class PharmacyController {

    private static Logger logger = LoggerFactory.getLogger(HospNatOrderController.class);

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private DownloadRecordService downloadRecordService;

    @Autowired
    private AuthService authService;

    @Autowired
    private PharmacyService pharmacyService;

    @Autowired
    private DomainConfigurer domainConfigurer;


    @ApiOperation(value = "按条件查询下载记录列表")
    @RequestMapping(value = {"/downloadRecordList"}, method = RequestMethod.POST)
    @MGRight(menuCode = {"/pharmacy/downloadRecordList"}, type = MGRightTypeDef.Menu | MGRightTypeDef.Logined)
    BaseResponse queryDownloadRecordList(@Validated @RequestBody QueryDownloadRecordListRequest request) throws Exception {
        //药房客户端
        request.setHospitalId(-1);
        int adminId = authService.getCurrentAdminId();
        request.setAdminId(adminId);
        return downloadRecordService.queryPharDownloadRecordList(request);
    }

    @MGRight(rightCode = {"/pharmacy/downloadPrescriptionFile"},type = MGRightTypeDef.Menu | MGRightTypeDef.Logined)
    @RequestMapping({"/downloadPrescriptionFile"})
    BaseResponse downloadPrescriptionlist(@RequestBody Map<String, Object> map) {
        DataResponse<Object> dataResponse = new DataResponse<>();
        try {
//            map.put("pharmacyId", userService.getPharmacyId());
//            map.put("adminId", userService.getAdminId());

            String uData = Base64.getEncoder().encodeToString(JsonSerializer.toJson(map).getBytes());
            String randomValue = RandomUtil.getRandomCode(8, 3);
            String url = domainConfigurer.getYwtHttpsMgapiDomain() + "/downloadService/pharmacy/downloadFile?k=" + UrlEncoded.encodeString(uData) + "&randomValue=" + randomValue;
            dataResponse.setData(url);
            return dataResponse.succeed();
        } catch (Exception e) {
            logger.error("/pharmacyPrescription/downloadPrescriptionList:{},{}", JsonSerializer.toJson(map), e.getMessage(), e);
            return dataResponse.failed(BaseResponse.PARAMETER_ERROR, "处理失败");
        }
    }

    private String getStrFromJsonNode(JsonNode node, String def) {
        if (node == null) return def;
        return node.asText(def);
    }


    @ApiOperation(value = "下载文件")
    @RequestMapping(value = {"/downloadFile"})
    @MGRight(menuCode = {"/pharmacy/downloadFile"}, type = MGRightTypeDef.Menu | MGRightTypeDef.Logined)
    public void downloadFile(@RequestParam(value = "k") String k,  HttpServletResponse httpServletResponse) {
        String key = new String(Base64.getDecoder().decode(k));
        JsonNode jsonNode = JsonSerializer.readToNode(key);
        String downloadId = getStrFromJsonNode(jsonNode.get("id"), "0");
        int downId = Integer.parseInt(downloadId);
        DownloadFileRequest request = new DownloadFileRequest();
        request.setDownloadRecordId(downId);
        downloadRecordService.downloadFile(request, httpServletResponse);
    }

    @RequestMapping(value ={"/downloadPrescriptionlist"},  method = RequestMethod.POST)
    public BaseResponse downloadNatOrderList(@RequestBody PharamcyDownloadPresRequest request) {
        int currentAdminId = Checker.getIntegerValue(authService.getCurrentAdminId());
//        request.setCurrentAdminId(currentAdminId);
        // 插入记录
//        int  hospital = authService.getCurrentHospitalId();
//        request.setHospitalId(hospital);
//        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 = "/pharmacy/downloadPrescriptionlist";
        String paramJson = JsonSerializer.toJson(request);
        downloadRecordService.getOrInsertPharDownloadRecord(downloadRecordId, name, fileName + excelSuffixFormat, paramUrl, paramJson);
        Thread t = new Thread() {
            @Override
            public void run() {
               pharmacyService.downloadPharPrescriptionlist(downloadRecordId, fileName, request);
//
            }
        };
        t.start();
        return new BaseResponse().succeed("后台下载中...");
    }

}
