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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.dto.GoodsInfoDTO;
import com.jpsoft.shinestar.modules.base.entity.CompanyGoodInfo;
import com.jpsoft.shinestar.modules.base.entity.GoodsInfo;
import com.jpsoft.shinestar.modules.base.entity.GoodsType;
import com.jpsoft.shinestar.modules.base.service.CompanyGoodInfoService;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.base.service.GoodsInfoService;
import com.jpsoft.shinestar.modules.base.service.GoodsTypeService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
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.ApiOperation;
import lombok.extern.slf4j.Slf4j;
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 java.util.*;

/**
 * @author 墨鱼_mo
 * @date 2020-7-31 17:30
 */
@RestController
@RequestMapping("/base/goodsInfo")
@Slf4j
public class GoodsInfoController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private GoodsInfoService goodsInfoService;
    @Autowired
    private DataDictionaryService dataDictionaryService;
    @Autowired
    private GoodsTypeService goodsTypeService;
    @Autowired
    private UserService userService;
    @Autowired
    private CompanyInfoService companyInfoService;
    @Autowired
    private CompanyGoodInfoService companyGoodInfoService;

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

        GoodsInfo goodsInfo = new GoodsInfo();
        goodsInfo.setIsActivation(true);

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

        return msgResult;
    }

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

        try {
            goodsInfo.setId(UUID.randomUUID().toString());
            goodsInfo.setDelFlag(false);
            goodsInfo.setCreateBy(subject);
            goodsInfo.setCreateTime(new Date());

            int affectCount = goodsInfoService.insert(goodsInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(goodsInfo);
            } 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<GoodsInfo> edit(@PathVariable("id") String id){
        MessageResult<GoodsInfo> msgResult = new MessageResult<>();

        try {
            GoodsInfo goodsInfo = goodsInfoService.get(id);

            if (goodsInfo != null) {
                msgResult.setResult(true);
                msgResult.setData(goodsInfo);
            } 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<GoodsInfo> update(@RequestBody GoodsInfo goodsInfo,@RequestAttribute String subject){
        MessageResult<GoodsInfo> msgResult = new MessageResult<>();

        try {
            goodsInfo.setUpdateBy(subject);
            goodsInfo.setUpdateTime(new Date());

            int affectCount = goodsInfoService.update(goodsInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(goodsInfo);
            } 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 {
            GoodsInfo goodsInfo = goodsInfoService.get(id);
            goodsInfo.setDelFlag(true);
            goodsInfo.setUpdateBy(subject);
            goodsInfo.setUpdateTime(new Date());

            int affectCount = goodsInfoService.update(goodsInfo);

            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="批量删除")
    @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) {
                GoodsInfo goodsInfo = goodsInfoService.get(id);
                goodsInfo.setDelFlag(true);
                goodsInfo.setUpdateBy(subject);
                goodsInfo.setUpdateTime(new Date());

                affectCount += goodsInfoService.update(goodsInfo);
            }

            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(
            String id,
            @RequestParam(value="name",defaultValue="") String name,
            @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("create_time","desc"));

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

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

        Page<GoodsInfo> page = goodsInfoService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);
        for(GoodsInfo gi : page.getResult()){
            gi.setScenesName(dataDictionaryService.findNameByCatalogNameAndValue("积分使用场景",gi.getScenes()));
        }

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

        return msgResult;
    }

    @ApiOperation(value = "类型集合")
    @PostMapping("typeList")
    public MessageResult<List<GoodsInfo>> typeList(@RequestBody Map map) {
        MessageResult<List<GoodsInfo>> msgResult = new MessageResult<>();

        String type = (String) map.get("type");

        try {
            List<GoodsInfo> list = null;
            if (StringUtils.isBlank(type)) {
                list = goodsInfoService.list();
            } else {
                list = goodsInfoService.findByType(type);
            }
            msgResult.setData(list);
            msgResult.setCode(200);
            msgResult.setResult(true);


        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            msgResult.setMessage(ex.getMessage());
            msgResult.setResult(false);
            msgResult.setCode(500);
        }


        return msgResult;
    }

    @ApiOperation(value = "查询商品原价")
    @PostMapping("findByGoodsId")
    public MessageResult<GoodsInfo> findByGoodsId(String goodsId) {
        MessageResult<GoodsInfo> msgResult = new MessageResult<>();
        try {
            GoodsInfo goodsInfo = goodsInfoService.get(goodsId);

            msgResult.setData(goodsInfo);
            msgResult.setCode(200);
            msgResult.setResult(true);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            msgResult.setMessage(ex.getMessage());
            msgResult.setResult(false);
            msgResult.setCode(500);
        }
        return msgResult;
    }


    @ApiOperation(value = "类型集合")
    @PostMapping("goodsTypeList")
    public MessageResult<List<GoodsType>> goodsTypeList() {
        MessageResult<List<GoodsType>> msgResult = new MessageResult<>();

        try {
            List<GoodsType> list = goodsTypeService.list();

            msgResult.setData(list);
            msgResult.setCode(200);
            msgResult.setResult(true);


        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            msgResult.setMessage(ex.getMessage());
            msgResult.setResult(false);
            msgResult.setCode(500);
        }


        return msgResult;
    }


    @ApiOperation(value="添加信息")
    @PostMapping("addPayService")
    public MessageResult<GoodsInfo> addPayService(@RequestBody GoodsInfo goodsInfo,@RequestAttribute String subject){
        MessageResult<GoodsInfo> msgResult = new MessageResult<>();

        try {
            User user = userService.get(subject);

            goodsInfo.setId(UUID.randomUUID().toString());
            goodsInfo.setDelFlag(false);
            goodsInfo.setCreateBy(subject);
            goodsInfo.setCreateTime(new Date());

            int affectCount = goodsInfoService.insertPayService(goodsInfo,user.getCompanyId());

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(goodsInfo);
            } 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 = "payServicePageList",method = RequestMethod.POST)
    public MessageResult<Map> payServicePageList(
            String companyId,
            @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<>();

        if(StringUtils.isNotEmpty(companyId)) {

            List<String> goodInfoIdList = new ArrayList<>();

            List<CompanyGoodInfo> companyGoodInfoList = companyGoodInfoService.findByCompanyId(companyId);

            for (CompanyGoodInfo companyGoodInfo : companyGoodInfoList) {
                goodInfoIdList.add(companyGoodInfo.getGoodsId());
            }

            if(goodInfoIdList.size() == 0){
                goodInfoIdList.add("-1");
            }
            searchParams.put("goodInfoIdList",goodInfoIdList);
        }

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("create_time","desc"));


        Page<GoodsInfo> page = goodsInfoService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);

        Page<GoodsInfoDTO> pageDto = new Page<>();

        for (GoodsInfo goodsInfo : page) {
            GoodsInfoDTO goodsInfoDTO = new GoodsInfoDTO();
            goodsInfoDTO.setId(goodsInfo.getId());
            goodsInfoDTO.setCost(goodsInfo.getCost());
            goodsInfoDTO.setDesc(goodsInfo.getDesc());
            goodsInfoDTO.setIsActivation(goodsInfo.getIsActivation());
            goodsInfoDTO.setName(goodsInfo.getName());

            String type = goodsInfo.getType();
            GoodsType goodsType = goodsTypeService.get(type);
            goodsInfoDTO.setTypeN(goodsType.getGoodsName());
            goodsInfoDTO.setPic(goodsType.getIconPic());
            goodsInfoDTO.setUnit(goodsInfo.getUnit());
            goodsInfoDTO.setUnitPrice(goodsInfo.getUnitPrice());

            pageDto.add(goodsInfoDTO);
        }

        pageDto.setPageSize(page.getPageSize());
        pageDto.setTotal(page.getTotal());
        pageDto.setPageNum(page.getPageNum());

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

        return msgResult;
    }

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

        try {
            GoodsInfo goodsInfo = goodsInfoService.get(id);

            if (goodsInfo != null) {
                msgResult.setResult(true);
                msgResult.setData(goodsInfo);
            } 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 = "payServiceList",method = RequestMethod.POST)
    public MessageResult<Map> payServiceList(
            @RequestParam(value="businessKey",defaultValue="") String businessKey,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);
        User user = userService.get(subject);

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

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

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("create_time","desc"));

        List<String> goodInfoIdList = new ArrayList<>();
        List<CompanyGoodInfo> companyGoodInfoList = companyGoodInfoService.findByCompanyId(user.getCompanyId());
        for(CompanyGoodInfo companyGoodInfo : companyGoodInfoList){
            goodInfoIdList.add(companyGoodInfo.getGoodsId());
        }

        if(goodInfoIdList.size() == 0){
            goodInfoIdList.add("-1");
        }
        searchParams.put("goodInfoIdList",goodInfoIdList);

        Page<GoodsInfo> page = goodsInfoService.pageSearch(searchParams,1,100,false,sortList);
        for(GoodsInfo goodsInfo : page.getResult()){
            CompanyGoodInfo companyGoodInfo = companyGoodInfoService.findByCompanyIdAndGoodsId(businessKey,goodsInfo.getId());
            if(companyGoodInfo != null){
                goodsInfo.setUnitPrice(companyGoodInfo.getUnitPrice());
            }

            goodsInfo.setUpdateBy(businessKey);
        }

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

        return msgResult;
    }

    @ApiOperation(value="写入收费项目")
    @PostMapping("addList")
    public MessageResult<GoodsInfo> addList(@RequestBody List<GoodsInfo> list,@RequestAttribute String subject){
        MessageResult<GoodsInfo> msgResult = new MessageResult<>();

        try {
            for(GoodsInfo goodsInfo : list) {
                CompanyGoodInfo companyGoodInfo = companyGoodInfoService.findByCompanyIdAndGoodsId(goodsInfo.getUpdateBy(),goodsInfo.getId());
                if(companyGoodInfo == null) {
                    companyGoodInfo = new CompanyGoodInfo();
                    companyGoodInfo.setId(UUID.randomUUID().toString());
                    companyGoodInfo.setCompanyId(goodsInfo.getUpdateBy());//CheckinId
                    companyGoodInfo.setGoodsId(goodsInfo.getId());
                    companyGoodInfo.setUnitPrice(goodsInfo.getUnitPrice());
                    companyGoodInfo.setDelFlag(false);
                    companyGoodInfo.setCreateBy(subject);
                    companyGoodInfo.setCreateTime(new Date());

                    companyGoodInfoService.insert(companyGoodInfo);
                }
                else{
                    companyGoodInfo.setUnitPrice(goodsInfo.getUnitPrice());
                    companyGoodInfo.setUpdateBy(subject);
                    companyGoodInfo.setUpdateTime(new Date());

                    companyGoodInfoService.update(companyGoodInfo);
                }
            }
            msgResult.setResult(true);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }
}
