package com.steerinfo.baseinfo.meterbasecussupcar.controller;

import com.alibaba.fastjson.JSONObject;
import com.steerinfo.baseinfo.meterbaseoperationlog.mapper.MeterBaseOperationLogMapper;
import com.steerinfo.baseinfo.meterbaseoperationlog.model.MeterBaseOperationLog;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.framework.utils.collection.ListUtils;
import com.steerinfo.baseinfo.meterbasecussupcar.model.MeterBaseCusSupCar;
import com.steerinfo.baseinfo.meterbasecussupcar.service.IMeterBaseCusSupCarService;
import com.steerinfo.meterwork.except.MarkerMetException;
import com.steerinfo.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * MeterBaseCusSupCar RESTful接口：
 *
 * @author generator
 * @version 1.0-SNAPSHORT 2020-06-15 11:47
 * 类描述
 * 修订历史：
 * 日期：2020-06-15
 * 作者：generator
 * 参考：
 * 描述：MeterBaseCusSupCar RESTful接口
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 * @see null
 */
@RestController
@RequestMapping("/${api.version}/meterbasecussupcars")
@Api(value = "/${api.version}/meterbasecussupcars", tags = "客商车辆维护 - MeterBaseCusSupCarController")
public class MeterBaseCusSupCarController extends BaseRESTfulController {

    @Value("${sso.url}")
    String ssoUrl;

    @Value("${sso.appuser}")
    String ssoAppUser;

    @Value("${sso.password}")
    String ssoPassword;

    @Autowired
    IMeterBaseCusSupCarService meterBaseCusSupCarService;

    @Autowired
    private MeterBaseOperationLogMapper meterBaseOperationLogMapper;

    @ApiOperation(value = "获取列表", notes = "分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("meterbasecussupcar:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas, Integer pageNum, Integer pageSize) {
        try {
            PageList<MeterBaseCusSupCar> list = meterBaseCusSupCarService.queryForPage(parmas, pageNum, pageSize);
            return success(list);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new MarkerMetException(500, "操作异常！！");
        }
    }

    @ApiOperation(value = "获取列表", notes = "分页模糊查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("meterbasecussupcar:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas, Integer pageNum, Integer pageSize) {
        try {
            PageList<MeterBaseCusSupCar> list = meterBaseCusSupCarService.queryLikeForPage(parmas, pageNum, pageSize);
            return success(list);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new MarkerMetException(500, "操作异常！！");
        }
    }

    @ApiOperation(value = "创建", notes = "根据MeterBaseCusSupCar对象创建")
    @ApiImplicitParam(name = "meterBaseCusSupCar", value = "详细实体meterBaseCusSupCar", required = true, dataType = "MeterBaseCusSupCar")
    //@RequiresPermissions("meterbasecussupcar:create")
    @Transactional
    @PostMapping(value = "/")
    public RESTfulResult add(@RequestBody MeterBaseCusSupCar model) {
        try {
            String msg = meterBaseCusSupCarService.checkandadd(model);
            if (StringUtils.isNotEmpty(msg)) {
                return failed(null, msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }

        return success();
    }

    @ApiOperation(value = "获取详细信息", notes = "根据url的id来获取详细信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("meterbasecussupcar:view")
    @GetMapping(value = "/{id}")
    public RESTfulResult get(@PathVariable String id) {
        try {
            MeterBaseCusSupCar meterBaseCusSupCar = meterBaseCusSupCarService.getById(id);
            return success(meterBaseCusSupCar);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new MarkerMetException(500, "操作异常！！");
        }
    }

    @ApiOperation(value = "更新详细信息", notes = "根据url的id来指定更新对象，并根据传过来的meterBaseCusSupCar信息来更新详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
            @ApiImplicitParam(name = "meterBaseCusSupCar", value = "详细实体meterBaseCusSupCar", required = true, dataType = "MeterBaseCusSupCar")
    })
    //@RequiresPermissions("meterbasecussupcar:update")
    @Transactional
    @PutMapping(value = "/{id}", produces = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody MeterBaseCusSupCar model) {
        try {
            String msg = meterBaseCusSupCarService.checkandupdate(id, model);
            if (StringUtils.isNotEmpty(msg)) {
                return failed(null, msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }

        return success();
    }

    @ApiOperation(value = "删除", notes = "根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("meterbasecussupcar:delete")
    @PutMapping(value = "/")//String
    public RESTfulResult delete(@RequestBody List<MeterBaseCusSupCar> models) {
        try {
            List<String> list = new ArrayList<String>();
            for (MeterBaseCusSupCar model : models) {
                String id = model.getId();
                list.add(id);
            }
            List<String> ids = ListUtils.convertList(list);
            meterBaseCusSupCarService.delete(ids);

            for (MeterBaseCusSupCar model : models) {
                MeterBaseOperationLog operationLog = new MeterBaseOperationLog();
                String id = PublicMethod.IdCreate(2);
                operationLog.setId(id);
                operationLog.setOperationPage("微信小程序-车辆维护"); //操作界面-页面名称
                operationLog.setOperationFunction("车辆维护-删除车号");//操作界面-功能名称
                operationLog.setOperationId(model.getId());//操作界面-数据主键
                operationLog.setOperationCarnNo(model.getCusSupCarNo());//操作界面-车号
                operationLog.setCreateManNo(model.getCustomerSupplierNo());
                operationLog.setCreateManName(model.getCustomerSupplierName());
                operationLog.setCreateTime(new Date());
                meterBaseOperationLogMapper.insertSelective(operationLog);
            }
            return success();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new MarkerMetException(500, "操作异常！！");
        }
    }

    @ApiOperation(value = "服役", notes = "根据传过来的MeterBaseCusSupCar集合信息来更新详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MeterBaseCusSupCar", value = "详细实体MeterBaseCusSupCar", required = true, dataType = "MeterBaseCusSupCar")
    })
    @Transactional
    @PostMapping(value = "/Recovery")
    public RESTfulResult Recovery(@RequestBody List<MeterBaseCusSupCar> models) {
        try {
            String msg = meterBaseCusSupCarService.Recovery(models);
            if (StringUtils.isNotEmpty(msg)) {
                return failed(null, msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }
        return success();
    }

    @ApiOperation(value = "停役", notes = "根据传过来的MeterBaseCusSupCar集合信息来更新详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MeterBaseCusSupCar", value = "详细实体MeterBaseCusSupCar", required = true, dataType = "MeterBaseCusSupCar")
    })
    @Transactional
    @PostMapping(value = "/abolish")
    public RESTfulResult abolish(@RequestBody List<MeterBaseCusSupCar> models) {
        try {
            String msg = meterBaseCusSupCarService.abolish(models);
            if (StringUtils.isNotEmpty(msg)) {
                return failed(null, msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }
        return success();
    }

    @ApiOperation(value = "app自助注册", notes = "app自助注册")
    @Transactional
    @PostMapping(value = "/appregister")
    public RESTfulResult appregister(@RequestBody HashMap params) {
        try {
            String msg = "";
            // sso注册
            SSOUtil ssoUtil = new SSOUtil();
            //msg = ssoUtil.ssoRegister(params);
            msg = "";

            // sso注册成功时，增加车辆表
            if (StringUtils.isNotEmpty(msg) && !msg.equals("账号已被注册")) {
                return failed(null, msg);
            }
            else {
                // 拆分司机list，新增客商车辆表
                List<MeterBaseCusSupCar> driverList = JSONObject.parseArray(params.get("driverList").toString(), MeterBaseCusSupCar.class);
                // 循环新增车辆
                for (MeterBaseCusSupCar car: driverList) {
                    // 检查车辆 + 司机是否存在
                    HashMap query = new HashMap();
                    query.put("cusSupCarNo", params.get("cusSupCarNo").toString());
                    query.put("telNum", car.getTelNum());
                    query.put("validFlag", "0");

                    List<MeterBaseCusSupCar> list = meterBaseCusSupCarService.query(query);
                    if(list.size() == 0){
                        // 将车辆类型，载重信息加入实体
                        car.setCusSupCarNo(params.get("cusSupCarNo").toString());

                        car.setCarTypeNo(params.get("carTypeNo").toString());
                        car.setCarTypeName(params.get("carTypeName").toString());
                        car.setCarCarrierWeight(new BigDecimal(params.get("carCarrierWeight").toString()));

                        car.setCreateManNo("admin");
                        car.setCreateManName("admins");
                        car.setCreateTime(new Date());

                        msg = meterBaseCusSupCarService.checkandadd(car);
                    }

                    if(StringUtils.isNotEmpty(msg)){
                        break;
                    }
                }
            }

            if (StringUtils.isNotEmpty(msg)) {
                return failed(null, msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }
        return success();
    }

    @ApiOperation(value = "app登录", notes = "app登录")
    @Transactional
    @PostMapping(value = "/applogin")
    public RESTfulResult applogin(@RequestBody HashMap params) {

        String msg = "";
        Object ssodata = "";

        try {
            if(params.get("cusSupCarNo") == null || StringUtils.isEmpty(params.get("cusSupCarNo").toString())) {
                msg = "车号不能为空！！";
            }
            else if(params.get("telNum") == null || StringUtils.isEmpty(params.get("telNum").toString())) {
                msg = "手机号不能为空！！";
            }
            else {
                // 状态（0：服役；1:停役;2:删除）
                params.put("validFlag", "0");

                // 判断车号，司机手机号是否存在
                List<MeterBaseCusSupCar> list = meterBaseCusSupCarService.query(params);
                if(list.size() >= 1){
//                    // sso登录
//                    // 密码加密
//                    String shaPass = SHAUtil.shaEncode(params.get("password").toString());
//
//                    Map<String, String> loginMap = new HashMap<>();
//                    loginMap.put("loginName", params.get("cusSupCarNo").toString());
//                    loginMap.put("password", shaPass);
//
//                    String ssomsg1 = HttpsRequest.sendPost(ssoUrl + "/auth/login", loginMap);
//                    // ssomsg1转JSONObject
//                    JSONObject jsonObject1 = JSONObject.parseObject(ssomsg1);
//                    //如果成功，读取accessToken
//                    String accessToken = "";
//                    if(jsonObject1.get("code").toString().equals("0")) {
//                        // 返回sso返回的data
//                        ssodata = jsonObject1.get("data");
//                    }
//                    else{
//                        msg = jsonObject1.get("message").toString();
//                    }

                    SSOUtil ssoUtil = new SSOUtil();
                    HashMap map = ssoUtil.ssoLogin(params, "");

                    if(map.get("code").toString().equals("0")){
                        ssodata = map.get("data").toString();
                    }
                    else {
                        msg = map.get("msg").toString();
                    }

                }
                else {
                    msg = "没有此车号或手机号";
                }
            }

            if (StringUtils.isNotEmpty(msg)) {
                return failed(null, msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }

        return success(ssodata);
    }

    @ApiOperation(value = "app修改密码", notes = "app修改密码")
    @Transactional
    @PostMapping(value = "/appchangepwd")
    public RESTfulResult appchangepwd(@RequestBody HashMap params) {

        String msg = "";

        try {
            if(params.get("cusSupCarNo") == null || StringUtils.isEmpty(params.get("cusSupCarNo").toString())) {
                msg = "车号不能为空！！";
            }
            else if(params.get("telNum") == null || StringUtils.isEmpty(params.get("telNum").toString())) {
                msg = "手机号不能为空！！";
            }
            else {
                // 状态（0：服役；1:停役;2:删除）
                params.put("validFlag", "0");

                // 判断车号，司机手机号是否存在
                List<MeterBaseCusSupCar> list = meterBaseCusSupCarService.query(params);
                if(list.size() >= 1){
                    // SSO修改密码
                    SSOUtil ssoUtil = new SSOUtil();
                    HashMap map = ssoUtil.ssoChangePwd(params);

                    if(map.get("code").toString().equals("0")){
                    }
                    else {
                        msg = map.get("msg").toString();
                    }
                }
                else {
                    msg = "没有此车号或手机号";
                }
            }

            if (StringUtils.isNotEmpty(msg)) {
                return failed(null, msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }

        return success();
    }

    @ApiOperation(value = "PC新增车辆", notes = "PC新增车辆")
    @Transactional
    @PostMapping(value = "/addcar")
    public RESTfulResult addcar(@RequestBody HashMap params) {
        try {
            String msg = "";

            // 检查车辆是否存在
            HashMap query = new HashMap();
            query.put("cusSupCarNo", params.get("cusSupCarNo").toString());
            query.put("validFlag", "0");

            List<MeterBaseCusSupCar> list = meterBaseCusSupCarService.query(query);
            if(list.size() == 0){
                // sso注册
                SSOUtil ssoUtil = new SSOUtil();
                //msg = ssoUtil.ssoRegister(params);
                msg = "";

                // sso注册成功时，增加车辆表
                if (StringUtils.isNotEmpty(msg) && !msg.equals("账号已被注册")) {
                    return failed(null, msg);
                }
                else {
                    MeterBaseCusSupCar car = new MeterBaseCusSupCar();
                    // 将车辆类型，载重信息加入实体
                    car.setCusSupCarNo(params.get("cusSupCarNo").toString());

                    car.setCarTypeNo(params.get("carTypeNo").toString());
                    car.setCarTypeName(params.get("carTypeName").toString());
                    if(params.get("carCarrierWeight") != null){
                        car.setCarCarrierWeight(new BigDecimal(params.get("carCarrierWeight").toString()));
                    }

                    car.setCreateManNo("admin");
                    car.setCreateManName("admins");
                    car.setCreateTime(new Date());

                    msg = meterBaseCusSupCarService.checkandadd(car);
                }
            }
            else {
                msg = "车辆已存在";
            }

            if (StringUtils.isNotEmpty(msg)) {
                return failed(null, msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }
        return success();
    }

    @ApiOperation(value = "PC新增司机", notes = "PC新增司机")
    @Transactional
    @PostMapping(value = "/adddriver")
    public RESTfulResult adddriver(@RequestBody HashMap params) {
        try {
            String msg = "";

            // 拆分司机list，新增客商车辆表
            List<MeterBaseCusSupCar> driverList = JSONObject.parseArray(params.get("driverList").toString(), MeterBaseCusSupCar.class);
            // 循环新增车辆
            for (MeterBaseCusSupCar car: driverList) {
                // 检查是否存在没有司机的车辆(有车号，但是没有司机姓名和联系电话)
                HashMap query = new HashMap();
                query.put("cusSupCarNo", params.get("cusSupCarNo").toString());
                query.put("driverName", "");
                query.put("telNum", "");
                query.put("validFlag", "0");

                List<MeterBaseCusSupCar> list = meterBaseCusSupCarService.query(query);
                // 新增一条车辆记录
                if(list.size() == 0){
                    // 新增司机时，如果不存在没有司机的车辆，这个车号必然存在至少一条有司机的记录
                    // 读取这条记录
                    query.remove("driverName");
                    query.remove("telNum");
                    List<MeterBaseCusSupCar> listHasDriver = meterBaseCusSupCarService.query(query);
                    if (listHasDriver.size() >=1){
                        // 将车辆类型，载重信息加入实体
                        MeterBaseCusSupCar tempCar = listHasDriver.get(0);

                        tempCar.setDriverName(params.get("driverName").toString());
                        tempCar.setTelNum(params.get("telNum").toString());

                        tempCar.setCreateManNo("admin");
                        tempCar.setCreateManName("admins");
                        tempCar.setCreateTime(new Date());

                        msg = meterBaseCusSupCarService.checkandadd(tempCar);
                    }
                    else {
                        msg = "不存在符合条件的车辆";
                    }

                }
                // 将司机姓名和联系方式附加到没有司机的车辆上
                else {
                    MeterBaseCusSupCar tempCar = list.get(0);
                    tempCar.setDriverName(params.get("driverName").toString());
                    tempCar.setDriverName(params.get("telNum").toString());

                    msg = meterBaseCusSupCarService.checkandupdate(tempCar.getId(), tempCar);
                }

                if(StringUtils.isNotEmpty(msg)){
                    break;
                }
            }

            if (StringUtils.isNotEmpty(msg)) {
                return failed(null, msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }
        return success();
    }

    @ApiOperation(value = "PC移除司机", notes = "PC移除司机")
    @Transactional
    @PostMapping(value = "/removedriver")
    public RESTfulResult removedriver(@RequestBody HashMap params) {
        try {
            String msg = "";

            // 拆分司机list，移除客商车辆表
            List<MeterBaseCusSupCar> driverList = JSONObject.parseArray(params.get("driverList").toString(), MeterBaseCusSupCar.class);
            // 循环新增车辆
            for (MeterBaseCusSupCar car: driverList) {
                // 检查是存在相关记录
                HashMap query = new HashMap();
                query.put("cusSupCarNo", params.get("cusSupCarNo").toString());
                query.put("driverName", params.get("driverName").toString());
                query.put("telNum", params.get("telNum").toString());
                query.put("validFlag", "0");

                List<MeterBaseCusSupCar> list = meterBaseCusSupCarService.query(query);
                // 移除一条车辆记录
                if(list.size() == 1){
                    meterBaseCusSupCarService.delete(list.get(0).getId());
                }
                else {
                    msg = "不存在相关司机信息";
                }

                if(StringUtils.isNotEmpty(msg)){
                    break;
                }
            }

            if (StringUtils.isNotEmpty(msg)) {
                return failed(null, msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(null, "操作异常，请确认！");
        }
        return success();
    }


}
