package thyyxxk.webserver.service.outpatient.wxmall;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import thyyxxk.webserver.controller.outpatient.wxmall.dto.PackageCreation;
import thyyxxk.webserver.controller.outpatient.wxmall.dto.PackageInquiry;
import thyyxxk.webserver.dao.his.outpatient.WxmallPackageDao;
import thyyxxk.webserver.entity.outpatient.wxmall.PackageState;
import thyyxxk.webserver.entity.outpatient.wxmall.Type;
import thyyxxk.webserver.entity.outpatient.wxmall.WxmallPackage;
import thyyxxk.webserver.entity.outpatient.wxmall.WxmallPackageItem;
import thyyxxk.webserver.service.hutoolcache.UserCache;
import thyyxxk.webserver.utils.SnowFlakeId;
import thyyxxk.webserver.utils.StringUtil;
import thyyxxk.webserver.utils.TokenUtil;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class WxmallPackageService {
    private final WxmallPackageDao dao;
    private final UserCache userCache;

    @Autowired
    public WxmallPackageService(WxmallPackageDao dao, UserCache userCache) {
        this.dao = dao;
        this.userCache = userCache;
    }

    public List<WxmallPackage> getPackagesByCondition(PackageInquiry inquiry) {
        PackageState state = inquiry.getState();
        if (null == state) {
            inquiry.setStatement("");
        } else {
            inquiry.setStatement(" and state='" + state + "'");
        }
        return dao.getPackagesByCondition(inquiry);
    }

    public BigDecimal getOriginPrice(Type type, String code) {
        String table = type == Type.JY ? "jy_item_charge" : "jc_item_charge";
        return dao.getOriginPrice(table, code);
    }

    @Transactional(rollbackFor = Exception.class)
    public WxmallPackage createNewPackage(PackageCreation creation) {

        WxmallPackage mainPackage = JSON.parseObject(creation.getMainPackageJson(), WxmallPackage.class);
        List<WxmallPackageItem> list = JSON.parseArray(creation.getPackageItemListJson(), WxmallPackageItem.class);

        String packageId = mainPackage.getId();
        if (StringUtil.isBlank(packageId)) {
            packageId = SnowFlakeId.instance().nextId();
        } else {
            dao.deletePackage(packageId);
        }
        String thumbPath = mainPackage.getThumbPath();
        if (creation.getFile() != null) {
            creation.setFileName(packageId);
            thumbPath = saveThumbImageToDisk(creation);
        }

        String userCode = TokenUtil.getInstance().getTokenUserId();
        String userName = userCache.getEmployeeName(userCode);
        mainPackage.setId(packageId);
        mainPackage.setThumbPath(thumbPath);
        mainPackage.setCreateStaffCode(userCode);
        mainPackage.setCreateStaffName(userName);
        mainPackage.setCreateTime(new Date());
        mainPackage.setState(PackageState.ACTIVATED);

        BigDecimal originalCost = BigDecimal.ZERO;
        BigDecimal discountCost = BigDecimal.ZERO;
        for (WxmallPackageItem item : list) {
            item.setPackageId(packageId);
            item.setCostAmt(item.getDiscountPrice()
                    .multiply(new BigDecimal(item.getQuantity())));
            originalCost = originalCost.add(item.getOriginPrice()
                    .multiply(new BigDecimal(item.getQuantity())));
            discountCost = discountCost.add(item.getDiscountPrice()
                    .multiply(new BigDecimal(item.getQuantity())));
        }
        mainPackage.setOriginPrice(originalCost);
        mainPackage.setDiscountPrice(discountCost);

        dao.insertNewPackage(mainPackage);
        dao.insertPackageItem(list);

        return mainPackage;
    }

    private String saveThumbImageToDisk(PackageCreation creation) {
        if (null == creation.getFile() || creation.getFile().isEmpty()) {
            return null;
        }

        try {
            String url = "https://staticweb.hnthyy.cn/htmlToImage/saveImg/saveThumbImageToDisk";
            ByteArrayResource fileResource = new ByteArrayResource(creation.getFile().getBytes()) {
                @Override
                public String getFilename() {
                    return creation.getFile().getOriginalFilename();
                }
            };

            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", fileResource);
            body.add("fileName", creation.getFileName());

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(body, headers);
            RestTemplate template = new RestTemplate();
            ResponseEntity<String> res = template.exchange(url, HttpMethod.POST, request, String.class);
            return res.getBody();
        } catch (IOException e) {
            log.error("文件读取失败", e);
            return null;
        } catch (RestClientException e) {
            log.error("API调用失败", e);
            return null;
        }
    }

    public String updatePackageState(WxmallPackage pkg) {
        dao.updatePackageState(pkg);
        return "操作成功";
    }

    public WxmallPackage getPackageDetail(String packageId) {
        WxmallPackage pkg = dao.getPackageById(packageId);
        if (null == pkg) {
            return null;
        }
        List<WxmallPackageItem> items = dao.getPackageItems(packageId);
        pkg.setItems(items);
        return pkg;
    }
}
