package com.winsun.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.winsun.auth.core.base.controller.BaseController;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.auth.core.shiro.ShiroUser;
import com.winsun.bean.Order;
import com.winsun.bean.Package;
import com.winsun.bean.YsmUser;
import com.winsun.mapper.OrderMapper;
import com.winsun.mapper.PackageMapper;
import com.winsun.mapper.YsmUserMapper;
import com.winsun.utils.MyBatisPlusUpdateUtils;
import com.winsun.utils.OrderManage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 张宸
 * @Date: 2020年3月11日15:12:46
 */
@Slf4j
@RestController
@RequestMapping("/supervisor")
public class supervisorController extends BaseController {

    private static String REPLACE="new/ciop";

    private static PackageMapper packageMapper;

    private static OrderMapper orderMapper;

    private static YsmUserMapper ysmUserMapper;

    @Autowired
    public supervisorController(PackageMapper packageMapper, OrderMapper orderMapper, YsmUserMapper ysmUserMapper) {
        supervisorController.packageMapper = packageMapper;
        supervisorController.orderMapper = orderMapper;
        supervisorController.ysmUserMapper = ysmUserMapper;
    }

    /**
     * 督导订单详情查询
     *
     * @param orderId
     * @return
     */
    @RequestMapping(value = "selectOrderInfo", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> selectOrderInfo(@RequestParam("orderId") String orderId) {
       /* ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }*/

        if (StringUtils.isNotBlank(orderId)) {
            ResponseData<String> verification = verification(orderId);
            if (!verification.isSuccess()) {
                return ResponseData.error("订单不存在或异常！");
            }
        } else {
            return ResponseData.error("页面已失效，请重新登录！");
        }
        Wrapper<Order> wrapper = new EntityWrapper<>();
        wrapper.eq("id", orderId);
        List<Map<String, Object>> list = orderMapper.selectMaps(wrapper);
        Map<String, Object> map = list.get(0);
        if (map.size() == 0) {
            return ResponseData.error("当前订单不存在！");
        }
        Package aPackage = packageMapper.selectById(Integer.parseInt(map.get("packageId").toString()));
        map.put("packageName", aPackage.getPackageName());
        map.put("advImg", aPackage.getAdvImg());
        //测试用
        if (StringUtils.isBlank(map.get("idCard").toString())) {
            map.put("idCard", "000000000000000000".substring(0, 14) + "****");
        } else {
            if (map.get("idCard").toString().length() == 18) {
                map.put("idCard", map.get("idCard").toString().substring(0, 14) + "****");
            } else {
                map.put("idCard", map.get("idCard").toString().substring(0, 11) + "****");
            }
        }
        map.put("explains", aPackage.getExplains());

        //查询历史状态
        List<Map<String, Object>> orderHis = orderMapper.selectOrderHis(orderId);
        map.put("orderHis", orderHis);
        return ResponseData.success(map);
    }

    /**
     * 督导订单置为异常单
     *
     * @param orderId
     * @return
     */
    @RequestMapping(value = "updateOrderState", method = RequestMethod.POST)
    public ResponseData<String> updateOrderState(@RequestParam("orderId") String orderId) {
        /* ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }*/
        if (StringUtils.isNotBlank(orderId)) {
            ResponseData<String> verification = verification(orderId);
            if (!verification.isSuccess()) {
                return ResponseData.error("订单不存在或异常！");
            }
        } else {
            return ResponseData.error("页面已失效，请重新登录！");
        }
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", orderId);
        Map<String, Object> dataMapping = new HashMap<>();
        dataMapping.put("order_status", "异常单");
        Integer integer = orderMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
        if (integer == 0) {
            return ResponseData.error("置为异常单失败！");
        } else {
            //orderMapper.inserOrderHis(orderId,"已置为异常单",new Date(),user.getName());
            orderMapper.inserOrderHis(orderId, "已置为异常单", new Date(), "测试");
            return ResponseData.success("置为异常单成功！");
        }
    }

    /**
     * 待处理
     *
     * @param orderId
     * @param type    0 是线上 1是线下
     * @return
     */
    @RequestMapping(value = "daichuliUpdate", method = RequestMethod.POST)
    public ResponseData<String> daiChuLiUpdate(@RequestParam("orderId") String orderId, @RequestParam("type") String type) {
        /* ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }*/
        if (StringUtils.isNotBlank(orderId)) {
            ResponseData<String> verification = verification(orderId);
            if (!verification.isSuccess()) {
                return ResponseData.error("订单不存在或异常！");
            }
        } else {
            return ResponseData.error("页面已失效，请重新登录！");
        }
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", orderId);
        Order order = orderMapper.selectById(orderId);
        Map<String, Object> dataMapping = new HashMap<>();
        int xb = order.getXbType();
        if ("0".equals(type)) {
            if (xb == 1) {
                dataMapping.put("order_status", "待配送");
                dataMapping.put("send_type", "快递");
            } else {
                dataMapping.put("order_status", "待选号");
                dataMapping.put("send_type", "快递");
            }
        }
        if ("1".equals(type)) {
            if (xb == 1) {
                dataMapping.put("order_status", "待活体");
                dataMapping.put("send_type", "送货上门");
            } else {
                dataMapping.put("order_status", "待选号");
                dataMapping.put("send_type", "送货上门");
            }
        }
        Integer integer = orderMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
        if (integer == 0) {
            return ResponseData.error("实名提交失败！");
        } else {
            //user.getName()
            orderMapper.inserOrderHis(orderId, "实名提交成功，" + dataMapping.get("order_status"), new Date(), "测试");
            return ResponseData.success("实名提交成功！");
        }
    }

    /**
     * 待选号
     *
     * @param orderId
     * @return
     */
    @RequestMapping(value = "daiXuanHaoUpdate", method = RequestMethod.POST)
    public ResponseData<String> daiXuanHaoUpdate(@RequestParam("orderId") String orderId, @RequestParam("businessNumber") String businessNumber, @RequestParam(value = "iccid", required = false) String iccid) {
        /* ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }*/
        if (StringUtils.isNotBlank(orderId)) {
            ResponseData<String> verification = verification(orderId);
            if (!verification.isSuccess()) {
                return ResponseData.error("订单不存在或异常！");
            }
        } else {
            return ResponseData.error("页面已失效，请重新登录！");
        }
        Order order = orderMapper.selectById(orderId);
        if (StringUtils.isBlank(businessNumber)) {
            return ResponseData.error("请输入办理号码！");
        }
        String s = yZPlaceAnOrder(orderId, businessNumber, iccid);
        Map map = JSON.parseObject(s, Map.class);
        if(s==null){
            return ResponseData.error("选号失败！");
        }
        if(StringUtils.isNotBlank(map.get("msg").toString())){
            orderMapper.inserOrderHis(orderId, "选号提交失败，" + map.get("msg").toString(), new Date(), "测试");
            return ResponseData.error(map.get("msg").toString());
        }
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", orderId);
        Map<String, Object> dataMapping = new HashMap<>();
        dataMapping.put("order_id", map.get("orderNumber").toString());
        if ("快递".equals(order.getSendType())) {
            dataMapping.put("order_status", "审核中");
            dataMapping.put("business_iccid", iccid);
        } else {
            dataMapping.put("order_status", "已完成");
        }
        dataMapping.put("business_number", businessNumber);
        Integer integer = orderMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
        if (integer == 0) {
            return ResponseData.error("选号提交失败！");
        } else {
            //user.getName()
            orderMapper.inserOrderHis(orderId, "选号提交成功，" + dataMapping.get("order_status"), new Date(), "测试");
            return ResponseData.success("选号提交成功！");
        }
    }

    /**
     * 待配送
     *
     * @param orderId
     * @return
     */
    @RequestMapping(value = "daiPeiSongUpdate", method = RequestMethod.POST)
    public ResponseData<String> daiPeiSongUpdate(@RequestParam("orderId") String orderId, @RequestParam("kuaidiOrder") String kuaidiOrder, @RequestParam(value = "expressDelivery") String expressDelivery) {
        /* ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }*/
        if (StringUtils.isNotBlank(orderId)) {
            ResponseData<String> verification = verification(orderId);
            if (!verification.isSuccess()) {
                return ResponseData.error("订单不存在或异常！");
            }
        } else {
            return ResponseData.error("页面已失效，请重新登录！");
        }
        Order order = orderMapper.selectById(orderId);
        if (StringUtils.isBlank(kuaidiOrder)) {
            return ResponseData.error("请输入快递单号！");
        }
        if (StringUtils.isBlank(expressDelivery)) {
            return ResponseData.error("请选择快递公司！");
        }
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", orderId);
        Map<String, Object> dataMapping = new HashMap<>();
        int xbType = order.getXbType();
        if (xbType == 1) {
            dataMapping.put("order_status", "待活体");
        } else {
            dataMapping.put("order_status", "已完成");
        }
        dataMapping.put("company", expressDelivery);
        dataMapping.put("kuaidi_order", kuaidiOrder);
        Integer integer = orderMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
        if (integer == 0) {
            return ResponseData.error("配送方式提交失败！");
        } else {
            //user.getName()
            orderMapper.inserOrderHis(orderId, "提交成功，" + dataMapping.get("order_status"), new Date(), "测试");
            return ResponseData.success("配送方式提交成功！");
        }
    }

    /**
     * 验证订单
     *
     * @param orderId
     * @return
     */
    public ResponseData<String> verification(String orderId) {
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", orderId);
        List list = orderMapper.selectList(wrapper);
        if (list.size() == 1) {
            return ResponseData.success("ok");
        } else if (list.size() == 0) {
            return ResponseData.error("订单不存在！");
        } else {
            return ResponseData.error("订单异常！");
        }
    }

    /**
     * 预制卡下单
     *
     * @param orderId
     * @param businessNumber
     * @param iccid
     * @return
     */
    public String yZPlaceAnOrder(String orderId, String businessNumber, String iccid) {
        Order order = orderMapper.selectById(orderId);
        String s = orderMapper.selectYsmById(order.getHehuorenId());
        YsmUser ysmUser = ysmUserMapper.selectById(s);
        Map<String, Object> map = new HashMap<>();
        map.put("ysmUser", ysmUser.getUserName());
        map.put("userName", order.getCustomerName());// 客户姓名，必填// 联系人，必填
        map.put("linkPhone", order.getContactNumber());// 客户(代办人)电话，必填
        map.put("idCard", order.getIdCard());
        String[] split = order.getSite().split("/");
        map.put("sheng", split[0]);
        map.put("shi", split[1]);
        map.put("xian", split[2]);
        map.put("address", order.getAddress());
        map.put("iccId", iccid);
        map.put("orderPhone", order.getBusinessNumber());
        map.put("orderNum", order.getOrderNumber());
        map.put("imgUrl1", order.getIdCardz().replace(REPLACE,"enclosure"));
        map.put("imgUrl2", order.getIdCardf().replace(REPLACE,"enclosure"));
        map.put("imgUrl3", order.getIdCardzs().replace(REPLACE,"enclosure"));
        map.put("imgUrl4", order.getIdCardzs().replace(REPLACE,"enclosure"));
        map.put("sign", ysmUser.getSign());
        map.put("cardType",order.getKapin());
        try {
            OrderManage orderManage = new OrderManage();
            return orderManage.sendOrder(map);
        } catch (Exception e) {
            log.error("预制卡下单失败", e.getMessage());
        }
        return null;
    }
}
