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


import com.alipay.api.domain.Person;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.business.entity.BillPushGoods;
import com.jpsoft.shinestar.modules.business.service.BillPushGoodsService;
import com.jpsoft.shinestar.modules.business.service.BillPushService;
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.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
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.util.*;

@RestController
@RequestMapping("/base/companyPaymentInfo")
@Api(description = "companyPaymentInfo")
public class CompanyPaymentInfoController {

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

    @Autowired
    private CompanyPaymentInfoService companyPaymentInfoService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private CompanyGoodInfoService companyGoodInfoService;

    @Autowired
    private UserService userService;

    @Autowired
    private GoodsInfoService goodsInfoService;

    @Autowired
    private CheckinInfoService checkinInfoService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private BillPushService billPushService;

    @Autowired
    private BillPushGoodsService billPushGoodsService;

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

        CompanyPaymentInfo companyPaymentInfo = new CompanyPaymentInfo();

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

        return msgResult;
    }

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

        try {
            companyPaymentInfo.setIsOpenAlipay(false);
            companyPaymentInfo.setIsOpenWechat(false);
            companyPaymentInfo.setIsDefault(false);
            companyPaymentInfo.setDelFlag(false);
            companyPaymentInfo.setCreateBy(subject);
            companyPaymentInfo.setCreateTime(new Date());

            int affectCount = companyPaymentInfoService.insert(companyPaymentInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(companyPaymentInfo);
            } 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<CompanyPaymentInfo> update(@RequestBody CompanyPaymentInfo companyPaymentInfo,@RequestAttribute String subject){
        MessageResult<CompanyPaymentInfo> msgResult = new MessageResult<>();

        try {
            companyPaymentInfo.setUpdateBy(subject);
            companyPaymentInfo.setUpdateTime(new Date());
            int affectCount = companyPaymentInfoService.update(companyPaymentInfo);

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

        try {
            CompanyPaymentInfo companyPaymentInfo = companyPaymentInfoService.get(id);

            if (companyPaymentInfo != null) {
                msgResult.setResult(true);
                msgResult.setData(companyPaymentInfo);
            } 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") Long id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            CompanyPaymentInfo companyPaymentInfo = companyPaymentInfoService.get(id);
            companyPaymentInfo.setDelFlag(true);
            companyPaymentInfo.setUpdateBy(subject);
            companyPaymentInfo.setUpdateTime(new Date());

            int affectCount = companyPaymentInfoService.update(companyPaymentInfo);

            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("list")
    public MessageResult<Object> list(@RequestAttribute String subject){
        MessageResult<Object> msgResult = new MessageResult<>();

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

            List<CompanyPaymentInfo> list = companyPaymentInfoService.findListByCompanyId(user.getCompanyId());

            msgResult.setResult(true);
            msgResult.setData(list);
        }
        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 companyId,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"));

        User user = userService.get(subject);

        if(StringUtils.isNotEmpty(companyId)){
            searchParams.put("companyId",companyId);
        }
        else{
            searchParams.put("companyId", user.getCompanyId());
        }

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


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

        for (CompanyPaymentInfo companyPaymentInfo:page) {
            CompanyInfo companyInfo = companyInfoService.get(companyPaymentInfo.getCompanyId());
            if(companyInfo!=null) {
                companyPaymentInfo.setCompanyName(companyInfo.getName());
            }
        }

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

        return msgResult;
    }


    @ApiOperation(value="修改是否支持微信支付宝支付")
    @PostMapping("updateIsOpenWechatOrAlipay")
    public MessageResult<Integer> updateIsOpenWechatOrAlipay(String id,Boolean isOpenWechat,Boolean isOpenAlipay, @RequestAttribute String subject) {
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            CompanyPaymentInfo companyPaymentInfo = companyPaymentInfoService.get(Long.parseLong(id));

            if(companyPaymentInfo!=null){
                if(isOpenWechat!=null) {
                    companyPaymentInfo.setIsOpenWechat(isOpenWechat);
                }
                if(isOpenAlipay!=null) {
                    companyPaymentInfo.setIsOpenAlipay(isOpenAlipay);
                }

                companyPaymentInfo.setUpdateBy(subject);
                companyPaymentInfo.setUpdateTime(new Date());

                int count = companyPaymentInfoService.update(companyPaymentInfo);

                msgResult.setResult(true);
                msgResult.setData(count);
            }
            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("setIsDefault")
    public MessageResult<Integer> setIsDefault(String id,Boolean isDefault, @RequestAttribute String subject) {
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            CompanyPaymentInfo companyPaymentInfo = companyPaymentInfoService.get(Long.parseLong(id));

            if(companyPaymentInfo!=null){

                if(isDefault) {

                    List<CompanyPaymentInfo> list = companyPaymentInfoService.findListByCompanyId(companyPaymentInfo.getCompanyId());

                    for (CompanyPaymentInfo item : list) {
                        item.setIsDefault(false);
                        companyPaymentInfoService.update(item);
                    }
                }

                companyPaymentInfo.setIsDefault(isDefault);
                companyPaymentInfo.setUpdateBy(subject);
                companyPaymentInfo.setUpdateTime(new Date());

                int count = companyPaymentInfoService.update(companyPaymentInfo);

                msgResult.setResult(true);
                msgResult.setData(count);
            }
            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("loadDetails")
    public MessageResult<Object> loadDetails(String id){
        MessageResult<Object> msgResult = new MessageResult<>();

        try {
            Map<String,Object> map = new HashMap<>();
            BigDecimal unitPrice = BigDecimal.ZERO;
            String unit = "";
            String goodType="";

            CompanyGoodInfo companyGoodInfo = companyGoodInfoService.get(id);

            GoodsInfo goodsInfo = goodsInfoService.get(companyGoodInfo.getGoodsId());

            if(goodsInfo!=null){
                unitPrice = goodsInfo.getUnitPrice();
                unit = goodsInfo.getUnit();
                goodType = goodsInfo.getType();
                if(companyGoodInfo.getUnitPrice()!=null){
                    unitPrice = companyGoodInfo.getUnitPrice();
                }
            }

            map.put("unitPrice",unitPrice);
            map.put("goodType",goodType);
            map.put("unit", unit);
            map.put("unitPriceStr",String.valueOf(unitPrice) + unit);

            //如果是电费读取账单中最后一次的止码作为本次起码
            if("7".equals(goodType)){
                BillPushGoods billPushGoods = billPushGoodsService.findLastByCheckinInfoIdAndGoodsId(companyGoodInfo.getCompanyId(),goodsInfo.getId());

                if (billPushGoods!=null && billPushGoods.getNumStr()!=null){
                    JSONObject jsonObject = JSONObject.fromObject(billPushGoods.getNumStr());

                    if (jsonObject.get("end") != null) {
                        String end = jsonObject.getString("end");
                        map.put("numStr", end);
                    }
                }
            }

            msgResult.setResult(true);
            msgResult.setData(map);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }


    @ApiOperation(value="读取收款单位列表")
    @PostMapping("getCompanyList")
    public MessageResult<Object> getCompanyList(@RequestAttribute String subject){
        MessageResult<Object> msgResult = new MessageResult<>();

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

            List<CheckinInfo> list = new ArrayList<>();

            CompanyPaymentInfo companyPaymentInfo = companyPaymentInfoService.findByCompanyId(user.getCompanyId());

            if(companyPaymentInfo!=null){
                String companyId = companyPaymentInfo.getCompanyId();
                list = checkinInfoService.findBypropertyId(companyId);
                for (CheckinInfo checkinInfo:list) {
                    CompanyInfo companyInfo = companyInfoService.get(checkinInfo.getCompanyId());
                    if(companyInfo!=null){
                        String companyName = companyInfo.getName()+"(楼栋："+checkinInfo.getBuilding();
                        if(StringUtils.isNotEmpty(checkinInfo.getRoom())){
                            companyName+="，房号："+checkinInfo.getRoom();
                        }
                        companyName+=")";
                        checkinInfo.setCompanyName(companyName);

                    }
                }
            }

            msgResult.setResult(true);
            msgResult.setData(list);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;

    }

    @ApiOperation(value = "根据公司查询租户")
    @PostMapping("findByCheckInId")
    public MessageResult<Object> findByCompanyId(String checkinInfoId) {
        MessageResult<Object> msgResult = new MessageResult<>();

        try {
            PersonInfo personInfo = new PersonInfo();
            CheckinInfo checkinInfo = checkinInfoService.get(checkinInfoId);

            if(checkinInfo!=null && checkinInfo.getArtificialPerson()!=null) {
               personInfo = personInfoService.get(checkinInfo.getArtificialPerson());
               personInfo.setCheckinInfoId(checkinInfo.getId());
            }

            msgResult.setResult(true);
            msgResult.setData(personInfo);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    @ApiOperation(value = "查询物业公司所在人员")
    @PostMapping("findPersonByCompanyId")
    public MessageResult<Object> findPersonByCompanyId(@RequestAttribute String subject) {
        MessageResult<Object> msgResult = new MessageResult<>();

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

            User user = userService.get(subject);

            searchParams.put("code","%"+user.getCompanyId()+"%");

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

            List<PersonInfo> list = personInfoService.findByCompanyCode(searchParams,sortList);

            msgResult.setResult(true);
            msgResult.setData(list);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }



    @ApiOperation(value = "查询物业公司所在人员")
    @PostMapping("findUserByCompanyId")
    public MessageResult<Object> findUserByCompanyId(@RequestAttribute String subject) {
        MessageResult<Object> msgResult = new MessageResult<>();

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

            User user = userService.get(subject);

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

            List<CompanyInfo> companyInfoList = companyInfoService.findAllCompanyByCode("%"+user.getCompanyId()+"%");

            searchParams.put("companyInfoList",companyInfoList);

            List<User> list = userService.findByCompanyList(searchParams,sortList);

            msgResult.setResult(true);
            msgResult.setData(list);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }
}
