package com.liquidnet.client.admin.web.controller.zhengzai.kylin;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liquidnet.client.admin.common.annotation.Log;
import com.liquidnet.client.admin.common.core.controller.BaseController;
import com.liquidnet.client.admin.common.core.domain.AjaxResult;
import com.liquidnet.client.admin.common.core.domain.entity.SysUser;
import com.liquidnet.client.admin.common.core.page.TableDataInfo;
import com.liquidnet.client.admin.common.enums.BannersTargetType;
import com.liquidnet.client.admin.common.enums.BusinessType;
import com.liquidnet.client.admin.common.utils.ShiroUtils;
import com.liquidnet.client.admin.zhengzai.adam.service.impl.AdamIdCodeService;
import com.liquidnet.client.admin.zhengzai.kylin.service.IToolService;
import com.liquidnet.commons.lang.constant.LnsRegex;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.base.ErrorMapping;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.kylin.dao.OrderTicketsListDao;
import com.liquidnet.service.kylin.dao.PerformanceSponsorDao;
import com.liquidnet.service.kylin.dto.param.admin.EntitiesEditParam;
import com.liquidnet.service.kylin.dto.param.admin.OrderListReq;
import com.liquidnet.service.kylin.dto.vo.admin.OrderDetailsAdminVo;
import com.liquidnet.service.kylin.entity.KylinOrderTicketEntities;
import com.liquidnet.service.kylin.entity.KylinOrderTicketEntitiesEditLog;
import com.liquidnet.service.kylin.mapper.KylinOrderTicketEntitiesEditLogMapper;
import com.liquidnet.service.kylin.mapper.KylinOrderTicketEntitiesMapper;
import com.liquidnet.service.kylin.service.admin.IKylinOrderTicketsAdminService;
import com.liquidnet.service.kylin.service.admin.IKylinPerformancesAdminService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 订单Controller
 *
 * @author anjiabin
 * @date 2021-05-24
 */
@Controller
@RequestMapping("/kylin/order")
public class KylinOrderTicketsController extends BaseController {
    private String prefix = "zhengzai/kylin/order";

    @Value("${liquidnet.client.admin.platformUrl}")
    private String platformUrl;

    @Value("${liquidnet.aliyun.oss.imgUrl}")
    private String imgUrl;

    @Autowired
    private IKylinOrderTicketsAdminService iKylinOrderTicketsAdminService;

    @Autowired
    private IKylinPerformancesAdminService kylinPerformancesService;

    @Autowired
    private IToolService toolService;

    @Autowired
    private AdamIdCodeService adamIdCodeService;

    @Autowired
    private KylinOrderTicketEntitiesMapper kylinOrderTicketEntitiesMapper;

    @Autowired
    private KylinOrderTicketEntitiesEditLogMapper kylinOrderTicketEntitiesEditLogMapper;

    @RequiresPermissions("kylin:order:orderlist:view")
    @GetMapping("/orderList")
    public String tickets() {
        return prefix + "/orderList/orderList";
    }

    @GetMapping("/enterEditList/{id}")
    @RequiresPermissions("kylin:order:orderlist:view")
    public String enterEditList(@PathVariable("id") String id, ModelMap mmap) {
        mmap.put("id", id);
        return prefix + "/orderList/enterEditList";
    }

    @Log(title = "观演人信息修改记录列表", businessType = BusinessType.LIST)
    @RequiresPermissions("kylin:order:orderlist:view")
    @PostMapping("/enterEditList/{id}")
    @ResponseBody
    public TableDataInfo enterEditListPost(@PathVariable("id") String id) {
        List<KylinOrderTicketEntitiesEditLog> editLogs = kylinOrderTicketEntitiesEditLogMapper.selectList(
                Wrappers.lambdaQuery(KylinOrderTicketEntitiesEditLog.class)
                        .eq(KylinOrderTicketEntitiesEditLog::getOrderTicketEntitiesId, id)
        );
        for (KylinOrderTicketEntitiesEditLog editLog : editLogs) {
            String result = Arrays.stream(editLog.getImages().split(","))
                    .map(url -> imgUrl + url)
                    .collect(Collectors.joining(","));
            editLog.setImages(result);
        }
        return getDataTable(editLogs);
    }

    @GetMapping("/enterEdit/{id}")
    @RequiresPermissions("kylin:order:orderlist:view")
    public String enterEdit(@PathVariable("id") String id, ModelMap mmap) {
        mmap.put("id", id);
        mmap.put("platformUrl", platformUrl);
        List<Object> bannersTargetType = BannersTargetType.getResultType();
        mmap.put("BannersTargetType", bannersTargetType);
        KylinOrderTicketEntities kylinOrderTicketEntities = kylinOrderTicketEntitiesMapper.selectOne(
                Wrappers.lambdaQuery(KylinOrderTicketEntities.class)
                        .eq(KylinOrderTicketEntities::getOrderTicketEntitiesId, id)
        );
        mmap.put("entitie", kylinOrderTicketEntities);
        return prefix + "/orderList/enterEdit";
    }

    @PostMapping("/enterEdit")
    @RequiresPermissions("kylin:order:orderlist:view")
    @Log(title = "修改观演人信息", businessType = BusinessType.UPDATE)
    @ResponseBody
    public AjaxResult enterEditPost(EntitiesEditParam param) {
        String orderTicketEntitiesId = param.getOrderTicketEntitiesId();
        KylinOrderTicketEntities entities = kylinOrderTicketEntitiesMapper.selectOne(
                Wrappers.lambdaQuery(KylinOrderTicketEntities.class)
                        .eq(KylinOrderTicketEntities::getOrderTicketEntitiesId, orderTicketEntitiesId)
        );
        String enterName = param.getEnterName();
        String enterMobile = entities.getEnterMobile();
        String enterIdCode = param.getEnterIdCode();
        Integer enterType = param.getEnterType();
        String orderId = entities.getOrderId();
        // 验证
        switch (param.getEnterType()) {
            case 1:
                if (!Pattern.matches(LnsRegex.Valid.CN_HANZI, enterName)) {
                    return error("观演人姓名只能为中文");
                }
                if (!Pattern.matches(LnsRegex.Valid.CN_ID_CARD_REF, enterIdCode)) {
                    return error("身份证号码不合规");
                }
                try {
                    adamIdCodeService.identityHandler1(enterName, enterIdCode);
                } catch (Exception e) {
                    return error(e.getMessage());
                }
                break;
            case 2:
                if (!Pattern.matches(LnsRegex.Valid.CN_ID_CARD_HM, enterIdCode)) {
                    return error("港澳居民来往内地通行证号码不合规");
                }
                break;
            case 3:
                if (!Pattern.matches(LnsRegex.Valid.CN_ID_CARD_TW, enterIdCode)) {
                    return error("台湾居民来往大陆通行证号码不合规");
                }
                break;
            case 4:
                if (Pattern.matches(LnsRegex.Valid.CN_ID_CARD_PP, enterIdCode)) {
                    return error("不支持中国大陆护照");
                }
                if (!Pattern.matches(LnsRegex.Valid.CN_ID_CARD_PP_NON, enterIdCode)) {
                    return error("护照号码不合规");
                }
                break;
            case 5:
                if (!Pattern.matches(LnsRegex.Valid.CN_ID_CARD_MO, enterIdCode)) {
                    return error("军官证号不合规");
                }
                break;
            default:
                return error("证件类型不正确");
        }
        // 修改
        toolService.supplementEnter(orderTicketEntitiesId, enterName, enterMobile, enterIdCode, enterType, orderId);
        // 记录
        KylinOrderTicketEntitiesEditLog editLog = KylinOrderTicketEntitiesEditLog.getNew();
        editLog.setEntitiesEditLogId(IDGenerator.nextSnowId());
        editLog.setOrderTicketEntitiesId(orderTicketEntitiesId);
        editLog.setEnterType(enterType);
        editLog.setEnterIdCode(enterIdCode);
        editLog.setEnterName(enterName);
        editLog.setRemark(param.getRemark());
        editLog.setImages(param.getImages());

        SysUser sysUser = ShiroUtils.getSysUser();
        editLog.setSysUserId(sysUser.getUserId());
        editLog.setSysUserName(sysUser.getUserName());

        editLog.setEnterNameOld(entities.getEnterName());
        editLog.setEnterTypeOld(entities.getEnterType());
        editLog.setEnterIdCodeOld(entities.getEnterIdCode());

        kylinOrderTicketEntitiesEditLogMapper.insert(editLog);

        return success();
    }

    /**
     * 查询订单列表
     */
    @Log(title = "演出订单", businessType = BusinessType.LIST)
    @RequiresPermissions("kylin:order:orderlist:list")
    @PostMapping("/orderList/list")
    @ResponseBody
    public TableDataInfo list(OrderListReq orderListReq) {
        startPage();
        List<OrderTicketsListDao> list = iKylinOrderTicketsAdminService.orderList(orderListReq);
        return getDataTable(list);
    }

    /**
     * 订单详情
     */
    @Log(title = "演出订单", businessType = BusinessType.DETAIL)
    @RequiresPermissions("kylin:order:orderlist:detail")
    @GetMapping("/orderList/detail/{orderId}")
    public String addPerformance(@PathVariable("orderId") String orderId, ModelMap mmap) {
        OrderDetailsAdminVo orderDetailsVo = iKylinOrderTicketsAdminService.orderDetails(orderId);
        mmap.put("orderDetailsVo", orderDetailsVo);
        return prefix + "/orderList/details";
    }

    /**
     * 获取第三方列表
     */
    @Log(title = "演出订单-三方", businessType = BusinessType.LIST)
    @GetMapping("/orderList/getSponsorList")
    @ResponseBody
    public AjaxResult getSponsorList() {
        List<PerformanceSponsorDao> performanceSponsorList = kylinPerformancesService.getPerformanceSponsorList(null);
        AjaxResult ajax = new AjaxResult();

        ajax.put("code", 200);
        ajax.put("value", performanceSponsorList);
        return ajax;
    }

    /**
     * 获取第三方列表
     */
    @Log(title = "演出订单-初始化转赠 [只支持 transferStatus = 5]]", businessType = BusinessType.LIST)
    @PostMapping("/orderList/initTransfer")
    @ResponseBody
    public AjaxResult initTransfer(@RequestParam("orderId") String orderId) {
        String result = iKylinOrderTicketsAdminService.initTransfer(orderId);
        return this.success(result);
    }
}
