package com.slodon.b2b2c.controller.member.seller.admin;

import com.slodon.b2b2c.aop.OperationLogger;
import com.slodon.b2b2c.aop.VendorLogger;
import com.slodon.b2b2c.core.constant.MemberConst;
import com.slodon.b2b2c.core.constant.MemberIntegralLogConst;
import com.slodon.b2b2c.core.constant.VendorConst;
import com.slodon.b2b2c.core.controller.BaseController;
import com.slodon.b2b2c.core.response.JsonResult;
import com.slodon.b2b2c.core.response.PageVO;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.core.response.SldResponse;
import com.slodon.b2b2c.core.util.*;
import com.slodon.b2b2c.enums.WebSiteConstant;
import com.slodon.b2b2c.member.dto.MemberAddDTO;
import com.slodon.b2b2c.member.dto.MemberIntegralLogUpdateDTO;
import com.slodon.b2b2c.member.dto.MemberUpdateDTO;
import com.slodon.b2b2c.member.dto.MemberUpdatePwdDTO;
import com.slodon.b2b2c.member.example.MemberExample;
import com.slodon.b2b2c.member.pojo.Member;
import com.slodon.b2b2c.model.member.MemberIntegralLogModel;
import com.slodon.b2b2c.model.member.MemberModel;
import com.slodon.b2b2c.model.msg.MemberSettingModel;
import com.slodon.b2b2c.model.seller.StoreApplyModel;
import com.slodon.b2b2c.model.seller.StoreNameModel;
import com.slodon.b2b2c.model.seller.VendorModel;
import com.slodon.b2b2c.model.seller.VendorRolesModel;
import com.slodon.b2b2c.seller.example.StoreApplyExample;
import com.slodon.b2b2c.seller.example.StoreNameExample;
import com.slodon.b2b2c.seller.example.VendorExample;
import com.slodon.b2b2c.seller.pojo.StoreApply;
import com.slodon.b2b2c.seller.pojo.StoreName;
import com.slodon.b2b2c.seller.pojo.Vendor;
import com.slodon.b2b2c.seller.pojo.VendorRoles;
import com.slodon.b2b2c.system.pojo.Admin;
import com.slodon.b2b2c.vo.member.MemberDetailVO;
import com.slodon.b2b2c.vo.member.MemberVO;
import com.slodon.b2b2c.vo.seller.StoreVendorVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author slodon
 */
@Api(tags = "admin-商家列表")
@RestController
@RequestMapping("v3/member/admin/vendor")
public class VendorController extends BaseController {

    @Resource
    private VendorModel vendorModel;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private VendorRolesModel vendorRolesModel;
    @Resource
    private RedisTemplate<String, Object> objectRedisTemplate;
    @Resource
    private StoreApplyModel storeApplyModel;
    @Resource
    private StoreNameModel storeNameModel;

    /**
     * 商家列表
     * @param request
     * @param vendorName
     * @param vendorMobile
     * @param state
     * @param startTime
     * @param endTime
     * @return
     */
    @ApiOperation("商家列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "webSite", value = "站点", paramType = "query"),
            @ApiImplicitParam(name = "memberName", value = "会员名称", paramType = "query"),
            @ApiImplicitParam(name = "memberMobile", value = "mobile", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "会员状态：0-禁用，1-启用", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("list")
    public JsonResult<PageVO<StoreVendorVO>> getList(HttpServletRequest request,
                                                     @RequestParam(value = "webSite", required = false) String webSite,
                                                     @RequestParam(value = "vendorName", required = false) String vendorName,
                                                     @RequestParam(value = "vendorMobile", required = false) String vendorMobile,
                                                     @RequestParam(value = "state", required = false) Integer state,
                                                     @RequestParam(value = "startTime", required = false) Date startTime,
                                                     @RequestParam(value = "endTime", required = false) Date endTime) {
        //分页设置
        PagerInfo pager = WebUtil.handlerPagerInfo(request);

        //根据条件查询集合
        VendorExample example = new VendorExample();
        example.setVendorNameLike(vendorName);
        example.setVendorMobileLike(vendorMobile);
        example.setIsAllowLogin(state);
        example.setIsAllowLoginNotEquals(VendorConst.LOGOUT_ALLOW_LOGIN);
        example.setRegisterTimeAfter(startTime);
        example.setRegisterTimeBefore(endTime);
        List<Vendor> list = vendorModel.getVendorList(example, pager);
        List<StoreVendorVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (Vendor vendor : list) {
                String storeName = "";
                StoreApplyExample storeApplyExample = new StoreApplyExample();
                storeApplyExample.setStoreId(vendor.getStoreId());
                List<StoreApply> storeApplyList = storeApplyModel.getStoreApplyList(storeApplyExample, null);
                if (!CollectionUtils.isEmpty(storeApplyList)){
                    storeName = storeApplyList.get(0).getStoreName();
                }
                if(WebSiteConstant.MEMBER_DISTRIBUTOR.equals(webSite)){
                    StoreNameExample storeNameExample = new StoreNameExample();
                    storeNameExample.setStoreId(vendor.getStoreId());
                    storeNameExample.setWebSite(webSite);
                    List<StoreName> storeNameList = storeNameModel.getStoreNameList(storeNameExample, null);
                    if (!CollectionUtils.isEmpty(storeNameList)){
                        storeName = storeNameList.get(0).getStoreName();
                    }
                }
                StoreVendorVO vo = new StoreVendorVO(vendor,storeName);
                //获取权限组名称
//                VendorRoles vendorRoles = vendorRolesModel.getVendorRolesByRolesId(vendor.getRolesId());
//                vo.setRolesName(vendorRoles.getRolesName());
                vos.add(vo);
            }
        }
        return SldResponse.success(new PageVO<>(vos, pager));
    }

    /**
     * 商家账号冻结/解冻
     * @param request
     * @param vendorId
     * @param isFreeze
     * @return
     */
    @OperationLogger(option = "商家账号冻结/解冻")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "vendorId", value = "操作员id", required = true),
            @ApiImplicitParam(name = "isFreeze", value = "冻结/解冻[true==冻结,false==解冻]", required = true)
    })
    @PostMapping("isFreeze")
    public JsonResult<Object> freeze(HttpServletRequest request, Long vendorId, Boolean isFreeze) {
        Vendor vendorDb = vendorModel.getVendorByVendorId(vendorId);
        AssertUtil.notNull(vendorDb, "店铺管理员账号不存在");
        AssertUtil.isTrue("1".equals(vendorDb.getIsStoreAdmin()), "店铺管理员账号不可更改");

        Vendor vendorNew = new Vendor();
        vendorNew.setVendorId(vendorId);
        if (isFreeze) {
            AssertUtil.isTrue(vendorDb.getIsAllowLogin() == VendorConst.NOT_ALLOW_LOGIN, "该账号已被冻结");

            vendorNew.setIsAllowLogin(VendorConst.NOT_ALLOW_LOGIN);
            vendorModel.updateVendor(vendorNew);

            //删除操作员的资源权限
            objectRedisTemplate.delete("seller-" + vendorId);
            return SldResponse.success("冻结成功");
        } else {
            AssertUtil.isTrue(vendorDb.getIsAllowLogin() == VendorConst.IS_ALLOW_LOGIN, "该账号非冻结状态");

            vendorNew.setIsAllowLogin(VendorConst.IS_ALLOW_LOGIN);
            vendorModel.updateVendor(vendorNew);
            return SldResponse.success("解冻成功");
        }
    }

    /**
     * 商家账号密码重置
     * @param request
     * @param vendorId
     * @param loginPwd
     * @param confirmPwd
     * @return
     */
    @OperationLogger(option = "商家账号密码重置")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "vendorId", value = "商户id", required = true),
            @ApiImplicitParam(name = "newPassword", value = "新密码", required = true),
            @ApiImplicitParam(name = "newPasswordCfm", value = "确认新密码", required = true)
    })
    @PostMapping("resetPassword")
    public JsonResult<Object> resetPassword(HttpServletRequest request, Long vendorId, String loginPwd, String confirmPwd) {
        AssertUtil.isTrue(!loginPwd.equals(confirmPwd), "密码输入不一致,请重试!");

        Vendor vendorDb = vendorModel.getVendorByVendorId(vendorId);
        AssertUtil.notNull(vendorDb, "店铺管理员账号不存在");

        String newPassword = Md5.getMd5String(confirmPwd);
        AssertUtil.isTrue(vendorDb.getVendorPassword().equals(newPassword), "新密码不能与上次密码一致!");

        Vendor vendorNew = new Vendor();
        vendorNew.setVendorId(vendorId);
        vendorNew.setVendorPassword(Md5.getMd5String(confirmPwd));
        vendorModel.updateVendor(vendorNew);
        return SldResponse.success("重置成功");
    }
}
