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


import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.dto.CanteenDiningRecordDTO;
import com.jpsoft.shinestar.modules.base.dto.CanteenRechargeRecordDTO;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
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 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 java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/mobile/canteenApi")
@Api(description = "食堂就餐相关接口")
public class CanteenApiController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private CanteenOutsourcerRechargeRecordService canteenOutsourcerRechargeRecordService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private CanteenOutsourcerBalanceService canteenOutsourcerBalanceService;

    @Autowired
    private CanteenDiningRecordService canteenDiningRecordService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @ApiOperation(value="外协人员充值记录")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Object> pageList(
            String token,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){

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


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

        try {

            PersonInfo personInfo = personInfoService.get(Long.parseLong(subject));

            if (personInfo == null) {
                throw new Exception("用户不存在！");
            }

            CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());

            if(companyInfo==null){
                throw new Exception("单位不存在！");
            }

            if(!"1".equals(companyInfo.getIsOutsourcer())){
                throw new Exception("人员不属于外协部门！");
            }

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

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

            searchParams.put("personId", personInfo.getId());

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

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

            for (CanteenOutsourcerRechargeRecord canteenOutsourcerRechargeRecord:page) {
                CanteenRechargeRecordDTO dto = new CanteenRechargeRecordDTO();
                dto.setId(canteenOutsourcerRechargeRecord.getId());
                dto.setCreateTime(canteenOutsourcerRechargeRecord.getCreateTime());
                dto.setRechargeAmount(canteenOutsourcerRechargeRecord.getRechargeAmount());

                pageDto.add(dto);
            }

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

            msgResult.setResult(true);
            msgResult.setData(PojoUtils.pageWrapper(pageDto));
        }
        catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msgResult.setResult(false);
        }
        return msgResult;
    }


    @ApiOperation(value="获取充值记录详情")
    @GetMapping("detail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "充值记录id", required = true, paramType = "query"),
    })
    public MessageResult<CanteenRechargeRecordDTO> detail(String id, String token){
        MessageResult<CanteenRechargeRecordDTO> msgResult = new MessageResult<>();

        try {
            CanteenOutsourcerRechargeRecord canteenOutsourcerRechargeRecord = canteenOutsourcerRechargeRecordService.get(id);

            CanteenRechargeRecordDTO dto = new CanteenRechargeRecordDTO();
            dto.setId(canteenOutsourcerRechargeRecord.getId());
            dto.setRechargeAmount(canteenOutsourcerRechargeRecord.getRechargeAmount());
            dto.setCreateTime(canteenOutsourcerRechargeRecord.getCreateTime());
            dto.setRemark(canteenOutsourcerRechargeRecord.getRemark());

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

        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    @ApiOperation(value="饭卡主页余额")
    @GetMapping("remainingAmount")
    public MessageResult<Object> remainingAmount(String token, @RequestAttribute String subject){
        MessageResult<Object> msgResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(Long.parseLong(subject));

            if (personInfo == null) {
                throw new Exception("用户不存在！");
            }

            CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());

            if(companyInfo==null){
                throw new Exception("单位不存在！");
            }

            if(!"1".equals(companyInfo.getIsOutsourcer())){
                throw new Exception("人员不属于外协部门！");
            }

            CanteenOutsourcerBalance canteenOutsourcerBalance = canteenOutsourcerBalanceService.findByPersonId(personInfo.getId());

            if (canteenOutsourcerBalance != null) {
                msgResult.setResult(true);
                msgResult.setData(canteenOutsourcerBalance.getAmount());
            } else {
                msgResult.setResult(false);
                msgResult.setData(0);
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }


    @ApiOperation(value="人员就餐记录")
    @RequestMapping(value = "personDiningList",method = RequestMethod.POST)
    public MessageResult<Object> personDiningList(
            String token,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){

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


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

        try {

            PersonInfo personInfo = personInfoService.get(Long.parseLong(subject));

            if (personInfo == null) {
                throw new Exception("用户不存在！");
            }

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

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

            searchParams.put("personId", personInfo.getId());

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

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

            for (CanteenDiningRecord canteenDiningRecord:page) {
                CanteenDiningRecordDTO dto = new CanteenDiningRecordDTO();
                dto.setId(canteenDiningRecord.getId());
                dto.setCategoryAmount(canteenDiningRecord.getCategoryAmount());
                dto.setRecordTime(canteenDiningRecord.getRecordTime());
                dto.setIsOutsourcer(canteenDiningRecord.getIsOutsourcer());
                String categoryN = dataDictionaryService.findNameByCatalogNameAndValue("就餐类型",canteenDiningRecord.getCategory());
                dto.setCategoryN(categoryN);

                pageDto.add(dto);
            }

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

            msgResult.setResult(true);
            msgResult.setData(PojoUtils.pageWrapper(pageDto));
        }
        catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msgResult.setResult(false);
        }
        return msgResult;
    }

    @ApiOperation(value="人员就餐详情")
    @GetMapping("personDiningDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "就餐记录id", required = true, paramType = "query"),
    })
    public MessageResult<CanteenDiningRecordDTO> personDiningDetail(String id, String token){
        MessageResult<CanteenDiningRecordDTO> msgResult = new MessageResult<>();

        try {
            CanteenDiningRecord canteenDiningRecord = canteenDiningRecordService.get(id);

            CanteenDiningRecordDTO dto = new CanteenDiningRecordDTO();
            dto.setCategoryAmount(canteenDiningRecord.getCategoryAmount());
            dto.setRecordTime(canteenDiningRecord.getRecordTime());
            dto.setRemark(canteenDiningRecord.getRemark());
            dto.setIsOutsourcer(canteenDiningRecord.getIsOutsourcer());
            String categoryN = dataDictionaryService.findNameByCatalogNameAndValue("就餐类型",canteenDiningRecord.getCategory());
            dto.setCategoryN(categoryN);

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

        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

}
