package com.jeequan.jeepay.mch.ctrl.store;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.DBApiMapConfig;
import com.jeequan.jeepay.core.utils.SeqKit;
import com.jeequan.jeepay.db.entity.*;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 商户门店管理
 *
 * @date 2021/12/29 9:52
 */
@RestController
@RequestMapping("/api/mchStore")
public class MchStoreController extends CommonCtrl {

    @Autowired
    private MchStoreService mchStoreService;
    @Autowired
    private MchInfoService mchInfoService;
    @Autowired
    private SysUserMchStoreRelaService sysUserMchStoreRelaService;
    @Autowired
    private MchApplymentService mchApplymentService;
    @Autowired
    private MchAppService mchAppService;
    @Autowired
    private MchStoreDeviceService mchStoreDeviceService;
    @Autowired
    private MchQrcodeCardService qrcodeCardService;

    /**
     * @date: 2021/12/29 9:53
     * @describe: 门店列表查询
     */
    @GetMapping
    @PreAuthorize("hasAuthority('ENT_MCH_STORE_LIST')")
    public ApiRes list() {
        MchStore mchStore = getObject(MchStore.class);
        mchStore.setMchNo(getCurrentMchNo());

        // 门店条件
        List<String> storeIdList = getCurrentUser().getStoreIdList();
        if (CollectionUtil.isNotEmpty(storeIdList)) {
            mchStore.setStoreIdList(storeIdList);
        }
        IPage<MchStore> mchStoreList = mchStoreService.listByPage(getIPage(true), mchStore, getReqParamJSON());
        return ApiRes.page(mchStoreList);
    }

    /**
     * @date: 2021/12/29 9:59
     * @describe: 新建门店
     */
    @MethodLog(remark = "新建门店")
    @PostMapping
    @PreAuthorize("hasAuthority('ENT_MCH_STORE_ADD')")
    public ApiRes add() {
        MchInfo mchInfo = mchInfoService.getById(getCurrentMchNo());
        MchStore mchStore = getObject(MchStore.class);
        mchStore.setStoreId(SeqKit.genStoreNo());

        Assert.notNull(mchStore.getAreaCode(), "请选择省市区");

        mchStore.setMchNo(getCurrentMchNo());
        //关联商户信息（原进件信息）t_mch_applyment，需要校验商户状态，必须是进件成功的

        Assert.hasLength(mchStore.getMchApplyId(), "进件id不能为空! ");

        MchApplyment tbMchApplyment = mchApplymentService.getById(mchStore.getMchApplyId());

        if (MchApplyment.STATE_SUCCESS != tbMchApplyment.getState()) {
            return ApiRes.customFail("该商户状态未进件成功！");
        }
        //校验指定商户号下的进件信息
        String applyMchNo = tbMchApplyment.getMchNo();
        String storeMchNo = mchStore.getMchNo();
        if (!Objects.equals(applyMchNo, storeMchNo)) {
            return ApiRes.customFail("商户信息与进件信息不匹配！");
        }
        // 初始为非默认门店
        mchStore.setDefaultFlag(CS.NO);
        mchStore.setAgentNo(mchInfo.getAgentNo());
        mchStore.setTopAgentNo(mchInfo.getTopAgentNo());
//        mchStore.setIsvNo(mchInfo.getIsvNo());
        //门店默认应用为商户绑定的应用
        MchApplyment mchApplymentById = mchApplymentService.getById(mchStore.getMchApplyId());
        mchStore.setBindAppId(mchApplymentById.getAutoConfigMchAppId());
        boolean result = mchStoreService.save(mchStore);
        if (!result) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_CREATE);
        }
        return ApiRes.ok();
    }

    /**
     * @date: 2021/12/29 9:59
     * @describe: 门店详情
     */
    @GetMapping("/{recordId}")
    @PreAuthorize("hasAuthority('ENT_MCH_STORE_VIEW')")
    public ApiRes detail(@PathVariable("recordId") String recordId) {

        MchStore mchStore = mchStoreService.getById(recordId);
        if (mchStore == null || !mchStore.getMchNo().equals(getCurrentMchNo())) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }
        return ApiRes.ok(mchStore);
    }

    /**
     * @author: xiaoyu
     * @date: 2021/12/29 10:00
     * @describe: 更新门店
     */
    @MethodLog(remark = "更新门店")
    @PutMapping("/{recordId}")
    @PreAuthorize("hasAnyAuthority('ENT_MCH_STORE_EDIT', 'ENT_MCH_STORE_APP_DIS')")
    public ApiRes update(@PathVariable("recordId") String recordId) {

        MchStore mchStore = getObject(MchStore.class);
        mchStore.setStoreId(recordId);
        mchStore.setMchNo(null);
        mchStore.setAgentNo(null);
        mchStore.setTopAgentNo(null);
        mchStore.setCreatedAt(null);
        mchStore.setUpdatedAt(null);
        MchStore dbRecord = mchStoreService.getById(recordId);
        if (!dbRecord.getMchNo().equals(getCurrentMchNo())) {
            throw new BizException("无权操作！");
        }

        // 如果修改当前为默认
        if (mchStore.getDefaultFlag() != null && mchStore.getDefaultFlag() == CS.YES) {
            mchStoreService.updateAllDefaultFlag(getCurrentMchNo());
        } else {
            mchStore.setDefaultFlag(null);
        }
        //门店应用为商户绑定的应用
        MchApplyment mchApplymentById = mchApplymentService.getById(mchStore.getMchApplyId());
        mchStore.setBindAppId(mchApplymentById.getAutoConfigMchAppId());
        boolean result = mchStoreService.updateById(mchStore);
        if (!result) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_UPDATE);
        }
        return ApiRes.ok();
    }

    /**
     * @date: 2021/12/29 10:05
     * @describe: 删除门店
     */
    @MethodLog(remark = "删除门店")
    @DeleteMapping("/{recordId}")
    @PreAuthorize("hasAuthority('ENT_MCH_STORE_DELETE')")
    public ApiRes delete(@PathVariable("recordId") String recordId) {
        MchStore mchStore = mchStoreService.getById(recordId);

        if (!mchStore.getMchNo().equals(getCurrentMchNo())) {
            throw new BizException("无权操作！");
        }

        if (mchStore.getDefaultFlag() == CS.YES) {
            throw new BizException("默认门店无法删除！");
        }

        mchStoreService.deleteStore(recordId, false);
        return ApiRes.ok();
    }


    /**
     * @date: 2022/11/30 10:41
     * @describe: 经纬度转换为areacode
     */
    @GetMapping("/location2areacode")
    @PreAuthorize("hasAuthority('ENT_MCH_STORE_MAP')")
    public ApiRes location2areacode() {
        try {
            // 经纬度 逗号分隔
            String location = getValStringRequired("location");

            DBApiMapConfig apiMapConfig = sysConfigService.getDBApiMapConfig();

            String result = HttpUtil.get("https://restapi.amap.com/v3/geocode/regeo?key=" + apiMapConfig.getApiMapWebServiceKey() + "&location=" + location);

            JSONObject resObject = JSONObject.parseObject(result);

            String areacode = resObject.getJSONObject("regeocode").getJSONObject("addressComponent").getString("adcode");

            JSONObject resJSON = new JSONObject();
            resJSON.put("areacode", areacode);
            return ApiRes.ok(resJSON);

        } catch (Exception e) {
            logger.error("经纬度转换为areacode异常", e);
            return ApiRes.ok(new JSONObject());
        }

    }


    /**
     * @date: 2022/2/19 10:41
     * @describe: 获取地图配置参数
     */
    @GetMapping("/mapConfig")
    @PreAuthorize("hasAuthority('ENT_MCH_STORE_MAP')")
    public ApiRes getMapConfig() {
        DBApiMapConfig apiMapConfig = sysConfigService.getDBApiMapConfig();
        return ApiRes.ok(apiMapConfig);
    }

    /**
     * @date: 2021/12/29 9:53
     * @describe: 门店列表查询
     */
    @GetMapping("/bindStoreList")
    @PreAuthorize("hasAuthority('ENT_MCH_STORE_LIST')")
    public ApiRes bindStoreList() {
        JSONObject paramJSON = getReqParamJSON();

        MchStore mchStore = getObject(MchStore.class);
        mchStore.setMchNo(getCurrentMchNo());
        // 门店条件
        List<String> storeIdList = getCurrentUser().getStoreIdList();
        if (CollectionUtil.isNotEmpty(storeIdList)) {
            mchStore.setStoreIdList(storeIdList);
        }


        IPage<MchStore> mchStoreList = mchStoreService.getBindStoreList(getIPage(true), mchStore, paramJSON);

        return ApiRes.page(mchStoreList);
    }


    /**
     * 查询已绑定集合
     */
    @GetMapping("/userStoreRelas")
    @PreAuthorize("hasAuthority('ENT_MCH_STORE_LIST')")
    public ApiRes userStoreRelas() {

        LambdaQueryWrapper<SysUserMchStoreRela> queryWrapper = SysUserMchStoreRela.gw();
        queryWrapper.eq(SysUserMchStoreRela::getSysUserId, getValLongRequired("sysUserId"));

        IPage<SysUserMchStoreRela> pages = sysUserMchStoreRelaService.page(getIPage(true), queryWrapper);
        return ApiRes.page(pages);
    }


}
