package com.jpsoft.shinestar.modules.base.controller;

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.CompanyInfo;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.base.entity.ParkingMerchant;
import com.jpsoft.shinestar.modules.base.service.ParkingMerchantService;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import com.jpsoft.shinestar.modules.sys.service.UserService;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 商户管理
 * sz
 */
@RestController
@RequestMapping("/base/parkingMerchant")
@Api(description = "parkingMerchant")
public class ParkingMerchantController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ParkingMerchantService parkingMerchantService;
    @Autowired
    private DataDictionaryService dataDictionaryService;
    @Autowired
    private UserService userService;
    @Autowired
    private CompanyInfoService companyInfoService;

    @ApiOperation(value="创建空记录")
    @GetMapping("create")
    public MessageResult<ParkingMerchant> create(){
        MessageResult<ParkingMerchant> msgResult = new MessageResult<>();

        ParkingMerchant parkingMerchant = new ParkingMerchant();

        msgResult.setData(parkingMerchant);
        msgResult.setResult(true);

        return msgResult;
    }
    
    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<ParkingMerchant> add(@RequestBody ParkingMerchant parkingMerchant,@RequestAttribute String subject){
        MessageResult<ParkingMerchant> msgResult = new MessageResult<>();

        try {
//            parkingMerchant.setId(UUID.randomUUID().toString());
//            parkingMerchant.setDelFlag(false);
//            parkingMerchant.setCreateBy(subject);
//            parkingMerchant.setCreateTime(new Date());
//
//            int affectCount = parkingMerchantService.insert(parkingMerchant);
            //创建商户
            parkingMerchant = parkingMerchantService.createMerchant("",parkingMerchant.getCompanyId(),parkingMerchant.getMerchantName(),String.valueOf(parkingMerchant.getReduce()));
            //创建商户操作人员
            parkingMerchantService.createShopMember(parkingMerchant);
            //赠送优惠券
            parkingMerchantService.giveReductionTicket(parkingMerchant);

            msgResult.setResult(true);
            msgResult.setData(parkingMerchant);

//            if (affectCount > 0) {
//                msgResult.setResult(true);
//                msgResult.setData(parkingMerchant);
//            } else {
//                msgResult.setResult(false);
//                msgResult.setMessage("数据库添加失败");
//            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="获取信息")
    @GetMapping("edit/{id}")
    public MessageResult<ParkingMerchant> edit(@PathVariable("id") String id){
        MessageResult<ParkingMerchant> msgResult = new MessageResult<>();

        try {
            ParkingMerchant parkingMerchant = parkingMerchantService.get(id);

            if (parkingMerchant != null) {
                msgResult.setResult(true);
                msgResult.setData(parkingMerchant);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="更新用户")
    @PostMapping("update")
    public MessageResult<ParkingMerchant> update(@RequestBody ParkingMerchant parkingMerchant,@RequestAttribute String subject){
        MessageResult<ParkingMerchant> msgResult = new MessageResult<>();

        try {
            parkingMerchant.setUpdateBy(subject);
            parkingMerchant.setUpdateTime(new Date());
            
            //int affectCount = parkingMerchantService.update(parkingMerchant);

            parkingMerchant = parkingMerchantService.createMerchant(parkingMerchant.getMerchantNo(),parkingMerchant.getCompanyId(),parkingMerchant.getMerchantName(),String.valueOf(parkingMerchant.getReduce()));

            msgResult.setResult(true);
            msgResult.setData(parkingMerchant);

//            if (affectCount > 0) {
//                //修改商户
//
//                msgResult.setResult(true);
//                msgResult.setData(parkingMerchant);
//            } else {
//                msgResult.setResult(false);
//                msgResult.setMessage("数据库更新失败");
//            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

	@ApiOperation(value="删除")
    @PostMapping("delete/{id}")
    public MessageResult<Integer> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
//            ParkingMerchant parkingMerchant = parkingMerchantService.get(id);
//            parkingMerchant.setDelFlag(true);
//            parkingMerchant.setUpdateBy(subject);
//            parkingMerchant.setUpdateTime(new Date());
//
//            int affectCount = parkingMerchantService.update(parkingMerchant);
//
//            if (affectCount > 0) {
//                msgResult.setResult(true);
//                msgResult.setData(affectCount);
//            } else {
//                msgResult.setResult(false);
//                msgResult.setMessage("删除失败");
//            }

            parkingMerchantService.deleteMerchant(id);
            msgResult.setResult(true);
            msgResult.setData(1);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value="批量删除")
    @PostMapping("batchDelete")
    public MessageResult<Integer> batchDelete(@RequestBody List<String> idList,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            for (String id : idList) {
                ParkingMerchant parkingMerchant = parkingMerchantService.get(id);
                parkingMerchant.setDelFlag(true);
                parkingMerchant.setUpdateBy(subject);
                parkingMerchant.setUpdateTime(new Date());

                affectCount += parkingMerchantService.update(parkingMerchant);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            @RequestParam(value="id",defaultValue="") String id,
            @RequestParam(value="companyId",defaultValue="") String companyId,
            @RequestParam(value="merchantName",defaultValue="") String merchantName,
            @RequestParam(value="type",defaultValue="") String type,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);

        MessageResult<Map> msgResult = new MessageResult<>();

        Map<String,Object> searchParams = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("b.sort_no","asc"));
        sortList.add(new Sort("a.create_time","asc"));

        if (StringUtils.isNotEmpty(id)) {
            searchParams.put("id","%" + id + "%");
        }

        if (StringUtils.isNotEmpty(companyId)) {
            searchParams.put("companyId",companyId);
        }
        if (StringUtils.isNotEmpty(merchantName)) {
            searchParams.put("merchantName","%" + merchantName + "%");
        }
        if (StringUtils.isNotEmpty(type)) {
            searchParams.put("type",type);
        }

        //当前用户ID
        User user = userService.get(subject);
        if (!userService.hasRole(subject,"SYSADMIN")) {
            CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());

            searchParams.put("parentCompanyCode", companyInfo.getCode() + "%");
        }

        Page<ParkingMerchant> page = parkingMerchantService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);
        for(ParkingMerchant pm : page.getResult()){
            pm.setTypeName(dataDictionaryService.findNameByCatalogNameAndValue("优惠券类型",pm.getType()));
        }

        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(page));

        return msgResult;
    }

    @GetMapping("/saveOpenId")
    @ResponseBody
    @ApiOperation(value = "保存openId")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openId", paramType = "query", required = false, value = "openId")

    })
    public MessageResult saveOpenId(String openId,String merchantId) {
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            ParkingMerchant parkingMerchant = parkingMerchantService.get(merchantId);
            String oldOpenId = parkingMerchant.getOpenId();
            if(StringUtils.isNotEmpty(oldOpenId)) {
                parkingMerchant.setOpenId(oldOpenId + "," + openId);
            }else{
                parkingMerchant.setOpenId(openId);
            }

            affectCount = parkingMerchantService.update(parkingMerchant);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("关联失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }
        return msgResult;
    }
}
