package com.tourism.webadmin.app.wechat.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.page.PageMethod;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.tourism.common.core.annotation.DisableDataFilter;
import com.tourism.common.core.annotation.MyRequestBody;
import com.tourism.common.core.constant.ErrorCodeEnum;
import com.tourism.common.core.object.MyPageData;
import com.tourism.common.core.object.MyRelationParam;
import com.tourism.common.core.object.ResponseResult;
import com.tourism.common.core.object.TokenData;
import com.tourism.common.core.util.MyCommonUtil;
import com.tourism.common.core.util.MyModelUtil;
import com.tourism.common.core.util.MyPageUtil;
import com.tourism.common.log.annotation.OperationLog;
import com.tourism.common.log.model.constant.SysOperationLogType;
import com.tourism.webadmin.app.wechat.dto.DeliveryDefaultAddressDto;
import com.tourism.webadmin.back.dao.DeliveryAddressMapper;
import com.tourism.webadmin.back.dto.DeliveryAddressDto;
import com.tourism.webadmin.back.dto.DeliveryAddressWebDto;
import com.tourism.webadmin.back.model.DeliveryAddress;
import com.tourism.webadmin.back.service.DeliveryAddressService;
import com.tourism.webadmin.back.vo.DeliveryAddressVo;
import com.tourism.common.additional.config.ApplicationConfig;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "外卖地址管理管理接口")
@Slf4j
@RestController
@RequestMapping("/wechat/delivery/address")
public class WechatDeliveryAddressController {
    @Autowired
    private ApplicationConfig appConfig;
    @Autowired
    private DeliveryAddressService deliveryAddressService;
    @Autowired
    private DeliveryAddressMapper deliveryAddressMapper;

    /**
     * 新增外卖地址管理数据。
     *
     * @param deliveryAddressDto 新增对象。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {"deliveryAddressDto.id"})
//    @SaCheckPermission("deliveryAddress.add")
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<String> add(@RequestBody DeliveryAddressDto deliveryAddressDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(deliveryAddressDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        DeliveryAddress deliveryAddress = MyModelUtil.copyTo(deliveryAddressDto, DeliveryAddress.class);
        deliveryAddress = deliveryAddressService.saveNew(deliveryAddress);
        return ResponseResult.success(deliveryAddress.getId());
    }

    /**
     * 更新外卖地址管理数据。
     *
     * @param deliveryAddressDto 更新对象。
     * @return 应答结果对象。
     */
//    @SaCheckPermission("deliveryAddress.update")
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/update")
    @DisableDataFilter
    public ResponseResult<Void> update(@RequestBody DeliveryAddressDto deliveryAddressDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(deliveryAddressDto, true);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        DeliveryAddress deliveryAddress = MyModelUtil.copyTo(deliveryAddressDto, DeliveryAddress.class);
        DeliveryAddress originalDeliveryAddress = deliveryAddressService.getById(deliveryAddress.getId());
        if (originalDeliveryAddress == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [数据] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        if (!deliveryAddressService.update(deliveryAddress, originalDeliveryAddress)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.success();
    }

    /**
     * 删除外卖地址管理数据。
     *
     * @param id 删除对象主键Id。
     * @return 应答结果对象。
     */
//    @SaCheckPermission("deliveryAddress.delete")
    @OperationLog(type = SysOperationLogType.DELETE)
    @PostMapping("/delete")
    @DisableDataFilter
    public ResponseResult<Void> delete(@MyRequestBody String id) {
        if (MyCommonUtil.existBlankArgument(id)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        return this.doDelete(id);
    }

    /**
     * 批量删除外卖地址管理数据。
     *
     * @param idList 待删除对象的主键Id列表。
     * @return 应答结果对象。
     */
//    @SaCheckPermission("deliveryAddress.delete")
    @OperationLog(type = SysOperationLogType.DELETE_BATCH)
    @PostMapping("/deleteBatch")
    @DisableDataFilter
    public ResponseResult<Void> deleteBatch(@MyRequestBody List<String> idList) {
        if (MyCommonUtil.existBlankArgument(idList)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        for (String id : idList) {
            ResponseResult<Void> responseResult = this.doDelete(id);
            if (!responseResult.isSuccess()) {
                return responseResult;
            }
        }
        return ResponseResult.success();
    }

    /**
     * 列出符合过滤条件的外卖地址管理列表。
     *
     * @param deliveryAddressDtoFilter 过滤对象。
     * @return 应答结果对象，包含查询结果集。
     */
//    @SaCheckPermission("deliveryAddress.view")
    @GetMapping("/list")
    public ResponseResult<MyPageData<DeliveryAddressVo>> list(
            @Valid @ModelAttribute DeliveryAddressWebDto deliveryAddressDtoFilter) {
        if (deliveryAddressDtoFilter != null) {
            PageMethod.startPage(deliveryAddressDtoFilter.getPageNum(), deliveryAddressDtoFilter.getPageSize(), true);
        }
        DeliveryAddress deliveryAddressFilter = MyModelUtil.copyTo(deliveryAddressDtoFilter, DeliveryAddress.class);
        Long userId = TokenData.takeFromRequest().getUserId();
        deliveryAddressFilter.setCreateUserId(userId);
//        String orderBy = MyOrderParam.buildOrderBy(orderParam, DeliveryAddress.class);
        List<DeliveryAddress> deliveryAddressList =
                deliveryAddressService.getDeliveryAddressListWithRelation(deliveryAddressFilter, "create_time");
//        deliveryAddressService.maskFieldDataList(deliveryAddressList, null);
        return ResponseResult.success(MyPageUtil.makeResponseData(deliveryAddressList, DeliveryAddressVo.class));
    }

    /**
     * 查看指定外卖地址管理对象详情。
     *
     * @param id 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
//    @SaCheckPermission("deliveryAddress.view")
    @GetMapping("/view")
    public ResponseResult<DeliveryAddressVo> view(@RequestParam String id) {
        DeliveryAddress deliveryAddress = deliveryAddressService.getByIdWithRelation(id, MyRelationParam.full());
        if (deliveryAddress == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        deliveryAddressService.maskFieldData(deliveryAddress, null);
        DeliveryAddressVo deliveryAddressVo = MyModelUtil.copyTo(deliveryAddress, DeliveryAddressVo.class);
        return ResponseResult.success(deliveryAddressVo);
    }

    private ResponseResult<Void> doDelete(String id) {
        String errorMessage;
        // 验证关联Id的数据合法性
        DeliveryAddress originalDeliveryAddress = deliveryAddressService.getById(id);
        if (originalDeliveryAddress == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [对象] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        if (!deliveryAddressService.remove(id)) {
            errorMessage = "数据操作失败，删除的对象不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        return ResponseResult.success();
    }

    /**
     * 更新默认地址。
     *
     * @param deliveryDefaultAddressDto 更新对象。
     * @return 应答结果对象。
     */
//    @SaCheckPermission("deliveryAddress.update")
    @OperationLog(type = SysOperationLogType.UPDATE)
    @SaIgnore
    @PostMapping("/updateIsDefaultAddress")
    @DisableDataFilter
    public ResponseResult<Void> updateIsDefaultAddress(@RequestBody DeliveryDefaultAddressDto deliveryDefaultAddressDto) {

        TokenData tokenData = TokenData.takeFromRequest();

        //id地址是否存在
        DeliveryAddress address = deliveryAddressService.getById(deliveryDefaultAddressDto.getId());
        if (address==null) return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);

        if (deliveryDefaultAddressDto.getIsDefault()==1){//是默认地址

           //将所有为默认地址的地址改为不默认
            LambdaUpdateWrapper<DeliveryAddress> updateWrapper = new LambdaUpdateWrapper<DeliveryAddress>()
                    .eq(DeliveryAddress::getIsDefault, 1)
                    .eq(DeliveryAddress::getDataState, 1)
                    .eq(DeliveryAddress::getCreateUserId, tokenData.getUserId())
                    .set(DeliveryAddress::getIsDefault, 2);
            deliveryAddressMapper.update(null, updateWrapper);
            }
        //将传入id地址状态改为传入地址状态
        address.setIsDefault(deliveryDefaultAddressDto.getIsDefault());
        deliveryAddressService.updateById(address);

        return ResponseResult.success();
    }
}
