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.annotion.Permission;
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.smsUtils.SendSmsAndMail;
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
     */
    @Permission(menuname = "督导订单详情查询",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("当前订单不存在！");
        }
        if (map.get("packageId") != null) {
            Package aPackage = packageMapper.selectById(Integer.parseInt(map.get("packageId").toString()));
            map.put("packageName", aPackage.getPackageName());
            map.put("advImg", aPackage.getAdvImg());
            map.put("explains", aPackage.getExplains());
        }

        //测试用
        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) + "****");
            }
        }

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

    /**
     * 督导订单置为异常单
     *
     * @param orderId
     * @return
     */
    @Permission(menuname = "督导订单置为异常单",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", "异常单");
        dataMapping.put("success_time", new Date());
        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
     */
    @Permission(menuname = "待处理",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("无数据权限");
        }*/
        ShiroUser shiroUser = getShiroUser();
        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<>();
        String xb = order.getXbType();
        if ("0".equals(type)) {
            if ("1".equals(xb)) {
                dataMapping.put("order_status", "待配送");
                dataMapping.put("send_type", "快递");
            } else {
                dataMapping.put("order_status", "待选号");
                dataMapping.put("send_type", "快递");
            }
        }
        if ("1".equals(type)) {
            if ("1".equals(xb)) {
                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(), shiroUser.getName());
            return ResponseData.success("配送方式修改成功！");
        }
    }

    /**
     * 待选号
     *
     * @param orderId
     * @return
     */
    @Permission(menuname = "待选号",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(map.get("msg") != null && 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("success_time", new Date());
        }
        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
     */
    @Permission(menuname = "待配送",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<>();
        String xbType = order.getXbType();
        if ("1".equals(xbType)) {
            dataMapping.put("order_status", "待活体");
        } else {
            dataMapping.put("order_status", "已完成");
            dataMapping.put("success_time", new Date());
        }
        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()
            log.info("联系号码：" + order.getContactNumber());
            // 发送短信
            SendSmsAndMail.sendSms2(order.getContactNumber(), expressDelivery, kuaidiOrder, "11");
            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());
        map.put("imgUrl2", order.getIdCardf());
        map.put("imgUrl3", order.getIdCardzs());
        map.put("imgUrl4", order.getIdCardzs());
        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;
    }
}
