package com.heyu.api.controller.vv;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.heyu.api.alibaba.request.vv.AppBuyerAddressRequest;
import com.heyu.api.common.annotation.AppRealyLogin;
import com.heyu.api.common.annotation.Describe;
import com.heyu.api.data.dao.vv.VvBuyerAddressDao;
import com.heyu.api.data.dao.vv.VvBuyerDao;
import com.heyu.api.data.entity.vv.VvBuyerAddressEntity;
import com.heyu.api.data.enums.BuyerAddressEnums;
import com.heyu.api.data.utils.R;
import com.heyu.api.data.utils.StringUtils;
import com.heyu.api.utils.ISelect;
import com.heyu.api.utils.PPageUtils;
import lombok.extern.slf4j.Slf4j;
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.util.List;


@Slf4j
@RestController
@RequestMapping("/app/buyer/address")

public class AppBuyerAddressManagerController {


    @Autowired
    private VvBuyerAddressDao vvBuyerAddressDao;

    @Autowired
    private VvBuyerDao vvBuyerDao;

    /***
     * 列表
     * /app/buyer/address/list
     */
    @Describe("买家地址列表")
    @RequestMapping("/list")
    @AppRealyLogin
    public R list(@RequestBody AppBuyerAddressRequest appBuyerAddressRequest) {
        PPageUtils pageUtils = PPageUtils.startPage(appBuyerAddressRequest.getPageNum(), appBuyerAddressRequest.getPageSize())
                .doSelect(new ISelect() {
                    @Override
                    public List doSelect(IPage page) {
                        return vvBuyerAddressDao.selectAppByCondition(page,
                                appBuyerAddressRequest.getBuyerId(),
                                BuyerAddressEnums.deleted.getStatus()
                        );
                    }
                });


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

    // /app/buyer/address/insertOrUpdate
    @Describe("买家地址插入或修改")
    @RequestMapping("/insertOrUpdate")
    @AppRealyLogin
    public R inserOrUpdate(@RequestBody VvBuyerAddressEntity vvBuyerAddressEntity) {
        // 如果当前状态是默认地址，
        if (BuyerAddressEnums.default_address.getStatus().equals(vvBuyerAddressEntity.getStatus())) {
            vvBuyerAddressDao.updateVvBuyerAddressStatusById(BuyerAddressEnums.common.getStatus(),
                    BuyerAddressEnums.default_address.getStatus(),
                    vvBuyerAddressEntity.getBuyerId());
        }

        if(StringUtils.isEmpty(vvBuyerAddressEntity.getStatus())){
            vvBuyerAddressEntity.setStatus(BuyerAddressEnums.common.getStatus());
        }

        vvBuyerAddressDao.insertOrUpdateVvBuyerAddress(vvBuyerAddressEntity);
        return R.ok();
    }


}
