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

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jeequan.jeepay.agent.ctrl.CommonCtrl;
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.AgentInfo;
import com.jeequan.jeepay.db.entity.MchApplyment;
import com.jeequan.jeepay.db.entity.MchInfo;
import com.jeequan.jeepay.db.entity.MchStore;
import com.jeequan.jeepay.service.impl.AgentInfoService;
import com.jeequan.jeepay.service.impl.MchApplymentService;
import com.jeequan.jeepay.service.impl.MchInfoService;
import com.jeequan.jeepay.service.impl.MchStoreService;
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;

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

    @Autowired private MchStoreService mchStoreService;
    @Autowired private AgentInfoService agentInfoService;
    @Autowired private MchInfoService mchInfoService;
    @Autowired
    private MchApplymentService mchApplymentService;


    /**
     * @date: 2021/12/29 9:53
     * @describe: 门店列表查询
     */
    @GetMapping
    @PreAuthorize("hasAuthority('ENT_MCH_STORE_LIST')")
    public ApiRes list() {
        MchStore mchStore = getObject(MchStore.class);
        //mchStore.setAgentNo(getCurrentAgentNo());
        JSONObject paramJSON = getReqParamJSON();
        // 可查看自己和全部下级服务商
        String currentAgentNo = getCurrentAgentNo();
        List<String> subAgentNoList = agentInfoService.queryAllSubAgentNo(currentAgentNo);
        if (CollectionUtil.isNotEmpty(subAgentNoList)) {
            mchStore.setSubAgentNoList(subAgentNoList);
        }
        IPage<MchStore> mchStoreList = mchStoreService.listByPage(getIPage(true), mchStore, paramJSON);
        return ApiRes.page(mchStoreList);
    }

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

        Assert.hasLength(mchStore.getMchNo(), "用户号[mchNo]不能为空");

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

        AgentInfo agentInfo = agentInfoService.getById(getCurrentAgentNo());

        Assert.hasLength(mchStore.getMchApplyId(), "商户号[mchApplyId]不能为空");

        MchApplyment tbMchApplyment = mchApplymentService.getById(mchStore.getMchApplyId());
        Assert.notNull(tbMchApplyment, "商户不存在");

        //关联商户信息（原进件信息）t_mch_applyment，需要校验商户状态，必须是进件成功的
        if (MchApplyment.STATE_SUCCESS != tbMchApplyment.getState()) {
            return ApiRes.customFail("该商户状态未进件成功！");
        }

        //校验指定商户号下的进件信息
        String applyMchNo = tbMchApplyment.getMchNo();
        String storeMchNo = mchStore.getMchNo();

        if (!applyMchNo.equals(storeMchNo)) {
            return ApiRes.customFail("用户信息与商户信息不匹配！");
        }

        mchStore.setStoreId(SeqKit.genStoreNo());
        mchStore.setAgentNo(agentInfo.getAgentNo());
        mchStore.setTopAgentNo(agentInfoService.queryTopAgentNo(getCurrentAgentNo()));

        mchStore.setIsvNo(agentInfo.getIsvNo());
        // 初始为非默认门店
        mchStore.setDefaultFlag(CS.NO);
        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.getAgentNo().equals(getCurrentAgentNo())) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }

        MchInfo mchInfo = mchInfoService.getById(mchStore.getMchNo());
        mchStore.addExt("mchName", mchInfo.getMchName());

        return ApiRes.ok(mchStore);
    }

    /**
     * @date: 2021/12/29 10:00
     * @describe: 更新门店
     */
    @MethodLog(remark = "更新门店")
    @PutMapping("/{recordId}")
    @PreAuthorize("hasAuthority('ENT_MCH_STORE_EDIT')")
    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.getAgentNo().equals(getCurrentAgentNo())) {
            throw new BizException("无权操作！");
        }

        // 如果修改当前为默认
        if (mchStore.getDefaultFlag() == CS.YES) {
            mchStoreService.updateAllDefaultFlag(dbRecord.getMchNo());
        }else {
            mchStore.setDefaultFlag(null);
        }

        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.getAgentNo().equals(getCurrentAgentNo())) {
            throw new BizException("无权操作！");
        }
        if (mchStore.getDefaultFlag() == CS.YES) {
            throw new BizException("默认门店无法删除！");
        }

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


    /**
     * @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);
    }
}
