package com.heyu.api.controller.imageseg;


import com.aliyun.imageseg20191230.models.SegmentHairResponse;
import com.aliyun.imageseg20191230.models.SegmentHairResponseBody;
import com.heyu.api.alibaba.handle.imageseg.ASegmentHairHandle;
import com.heyu.api.alibaba.request.imageseg.ASegmentHairRequest;
import com.heyu.api.controller.BaseController;
import com.heyu.api.data.annotation.CacheResult;
import com.heyu.api.data.annotation.NotIntercept;
import com.heyu.api.data.utils.ApiR;
import com.heyu.api.data.utils.R;
import com.heyu.api.resp.imageseg.SegmentHairResp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/***
 * https://next.api.aliyun.com/api/imageseg/2019-12-30/SegmentHair?tab=DOC&lang=JAVA&RegionId=cn-shanghai&params={%22ImageURL%22:%22http%3A%2F%2Fworkbench-file-transfer.oss-cn-shanghai.aliyuncs.com%2Fuser-files%2F2893a748-900f-4310-9c8e-9d45b011c3ce-SegmentHair1.jpg%3FOSSAccessKeyId%3DLTAI5tRvL6vYdjKSfTFZ156m%26Expires%3D1742401044%26Signature%3DFXSfytFsiXJntSbyz95BuwnzPww%253D%26response-content-disposition%3Dattachment%22}
 *头发分割
 *
 * SegmentHair
 *
 *功能描述
 * 头发分割能力用于识别图像中的人物头像，然后对人物头像区域进行抠图解析，最后输出 PNG 格式的人物头发矩形透明图。
 *
 *
 * 应用场景
 * 假发网络试戴：通过头发分割，截取自拍照的头发后，换成假发图像，就可以直接看到假发试戴效果，省去了网购后佩戴不合适需要退换货的烦恼。
 * 理发店发型尝试：发型师指导客户通过平板电脑或手机拍摄的自己头像，换成各种发型，有更直观的感觉。客户可以选择最喜欢的发型，让发型师为自己打理
 *
 *
 *
 *
 */
@Slf4j
@RestController
@RequestMapping("/hair")
@NotIntercept
public class SegmentHairController extends BaseController {

    @Autowired
    private ASegmentHairHandle segmentHairHandle;


    @RequestMapping("/segment")
    @CacheResult
    public R segment(ASegmentHairRequest request) {

        List<SegmentHairResp> respList = new ArrayList<>();

        ApiR<SegmentHairResponse> aR = segmentHairHandle.handle(request);
        if (aR.isSuccess() && isSuccessStatusCode(aR.getData().getStatusCode())) {
            SegmentHairResponseBody.SegmentHairResponseBodyData responseBodyData = aR.getData().getBody().getData();

            if (CollectionUtils.isNotEmpty(responseBodyData.getElements())) {
                for (SegmentHairResponseBody.SegmentHairResponseBodyDataElements element : responseBodyData.getElements()) {

                    SegmentHairResp resp = new SegmentHairResp();
                    resp.setImageURL(element.getImageURL());
                    resp.setY(element.getY());
                    resp.setX(element.getX());
                    resp.setHeight(element.getHeight());
                    resp.setWidth(element.getWidth());
                    respList.add(resp);
                }
            }

            return R.ok().setData(respList);
        }

        return R.error(aR.getErrorMsg());
    }


}
