package com.steerinfo.baseinfo.meterbasetravellingmerchant.controller;

import com.alibaba.fastjson.JSONObject;
import com.steerinfo.baseinfo.meterbasecar.model.MeterBaseCar;
import com.steerinfo.baseinfo.meterbasecussupcar.model.MeterBaseCusSupCar;
import com.steerinfo.baseinfo.meterbasedriver.model.MeterBaseDriver;
import com.steerinfo.baseinfo.meterbasetravellingmerchant.mapper.MeterBaseTravellingMerchantMapper;
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.meterbasetravellingmerchant.model.MeterBaseTravellingMerchant;
import com.steerinfo.baseinfo.meterbasetravellingmerchant.service.IMeterBaseTravellingMerchantService;
import com.steerinfo.util.SSOUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

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

/**
 * MeterBaseTravellingMerchant RESTful接口：
 * @author generator
 * @version 1.0-SNAPSHORT 2022-03-04 04:01
 * 类描述
 * 修订历史：
 * 日期：2022-03-04
 * 作者：generator
 * 参考：
 * 描述：MeterBaseTravellingMerchant RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/meterbasetravellingmerchants")
@Api(value = "/${api.version}/meterbasetravellingmerchants", tags = "客商信息 - MeterBaseTravellingMerchantController")
public class MeterBaseTravellingMerchantController extends BaseRESTfulController {

    @Autowired
    IMeterBaseTravellingMerchantService meterBaseTravellingMerchantService;

    @Autowired
    MeterBaseTravellingMerchantMapper meterBaseTravellingMerchantMapper;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("meterbasetravellingmerchant:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<MeterBaseTravellingMerchant> list = meterBaseTravellingMerchantService.queryForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value="获取列表", notes="分页模糊查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("meterbasetravellingmerchant:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<MeterBaseTravellingMerchant> list = meterBaseTravellingMerchantService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value="获取列表", notes="分页模糊查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("meterbasetravellingmerchant:view")
    @PostMapping(value = "/like/")
    public RESTfulResult listLikePost(@RequestBody HashMap parmas){
        Integer pageNum = parmas.get("pageNum") == null ? 1 : Integer.parseInt(parmas.get("pageNum").toString());
        Integer pageSize =parmas.get("pageSize") == null ? 20 : Integer.parseInt(parmas.get("pageSize").toString());
        PageList<MeterBaseTravellingMerchant> list = meterBaseTravellingMerchantService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据MeterBaseTravellingMerchant对象创建")
    @ApiImplicitParam(name = "meterBaseTravellingMerchant", value = "详细实体meterBaseTravellingMerchant", required = true, dataType = "MeterBaseTravellingMerchant")
    //@RequiresPermissions("meterbasetravellingmerchant:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute MeterBaseTravellingMerchant model){
        MeterBaseTravellingMerchant meterBaseTravellingMerchant = meterBaseTravellingMerchantService.add(model);
        return success(meterBaseTravellingMerchant);
    }

    @ApiOperation(value="获取详细信息", notes="根据url的id来获取详细信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("meterbasetravellingmerchant:view")
    @GetMapping(value = "/{id}")
    public RESTfulResult get(@PathVariable String id){
        MeterBaseTravellingMerchant meterBaseTravellingMerchant = meterBaseTravellingMerchantService.getById(id);
        return success(meterBaseTravellingMerchant);
    }

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的meterBaseTravellingMerchant信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
        @ApiImplicitParam(name = "meterBaseTravellingMerchant", value = "详细实体meterBaseTravellingMerchant", required = true, dataType = "MeterBaseTravellingMerchant")
    })
    //@RequiresPermissions("meterbasetravellingmerchant:update")
    @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody MeterBaseTravellingMerchant model){
        model.setId(id);
        MeterBaseTravellingMerchant meterBaseTravellingMerchant = meterBaseTravellingMerchantService.modify(model);
        return success(meterBaseTravellingMerchant);
    }

    @ApiOperation(value = "客商注册", notes = "客商注册")
    @Transactional
    @PostMapping(value = "/register")
    public RESTfulResult register(@RequestBody HashMap params) {
        try {
            String msg = "";
            params.put("carNo",params.get("travellingMerchantName").toString());
            params.put("password",params.get("travellingMerchantPossword").toString());
            // sso注册
            SSOUtil ssoUtil = new SSOUtil();
            HashMap ssoMap = ssoUtil.ssoRegister(params);

            // sso注册成功时，增加客商表
            if (ssoMap.get("code").equals("1") && !"账号已被注册".equals(ssoMap.get("msg").toString())) {
                return failed(null, ssoMap.get("msg").toString());
            } else {
                // 清除SSO"账号已被注册"
                msg = "";

                // 查询客商是否写入客商表
                HashMap queryCar = new HashMap();
                queryCar.put("travellingMerchantNo", params.get("travellingMerchantName").toString());
                queryCar.put("validFlag", "0");
                List<MeterBaseTravellingMerchant> queryList = meterBaseTravellingMerchantService.query(queryCar);

                // 车辆表已存在时，跳过
                if (queryList.size() == 0) {
                    // 新增车辆
                    MeterBaseTravellingMerchant mebl = new MeterBaseTravellingMerchant();
                    mebl.setTravellingMerchantNo(meterBaseTravellingMerchantMapper.getNewID());
                    mebl.setValidFlag("0");
                    mebl.setTravellingMerchantName(params.get("travellingMerchantName").toString());
                    mebl.setTravellingMerchantPossword(params.get("travellingMerchantPossword").toString());


                    // 将sso id写入车辆表，便于以后删除和重置密码
                    mebl.setSsoId(ssoMap.get("data").toString());

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

                    meterBaseTravellingMerchantMapper.insertSelective(mebl);
                }
            }

            if (com.steerinfo.util.StringUtils.isNotEmpty(msg)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                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("meterbasetravellingmerchant:delete")
    @DeleteMapping(value = "/{id}")//String
    public RESTfulResult delete(@PathVariable String id){
    	List<String> list = Arrays.asList(id.split(","));
    	if(ListUtils.isNotEmpty(list)) {
	    	List<String> ids = ListUtils.convertList(list);
			  meterBaseTravellingMerchantService.delete(ids);
    	}
      return success();
    }
}
