package com.iformall.controller.contract;

import com.iformall.annotation.SystemControllerLog;
import com.iformall.annotation.UserDataRuleAnnotation;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.controller.base.BaseController;
import com.iformall.domain.po.MallUserInfo;
import com.iformall.domain.po.WxBillProperty;
import com.iformall.domain.po.WxMerchant;
import com.iformall.domain.po.WxPropertyContract;
import com.iformall.enums.EnumIsPreview;
import com.iformall.enums.EnumRentStartType;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.WxPropertyContractMapper;
import com.iformall.service.WxBillPropertyService;
import com.iformall.service.WxPropertyContractService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
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 javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @author gongbiao
 */
@RestController
@RequestMapping("wxPropertyContract")
public class WxPropertyContractController extends BaseController {
    @Autowired
    private WxPropertyContractService wxPropertyContractService;
    @Autowired
    private WxBillPropertyService wxBillPropertyService;
    @Autowired
    private WxPropertyContractMapper wxPropertyContractMapper;

    private Logger logger = LoggerFactory.getLogger(WxPropertyContractController.class);

    @UserDataRuleAnnotation("property_contract_list")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)})
    @SystemControllerLog(description = "物业合同-列表")
    public ResultData list(@ModelAttribute WxPropertyContract wxPropertyContract, Integer pageNum, Integer pageSize) {
        logger.debug("[" + getIpAddr() + "] WxPropertyContractController::list");
        if (null == wxPropertyContract) {
            wxPropertyContract = new WxPropertyContract();
        }
        wxPropertyContract.setTenantId(getTenantId());
        Map<String, Object> result = wxPropertyContractService.listAsPage(wxPropertyContract, pageNum, pageSize);
        return new ResultData(result);
    }

    @PostMapping("add")
    @SystemControllerLog(description = "物业合同-新增")
    public ResultData add(@RequestBody WxPropertyContract wxPropertyContract) {
        logger.debug("[" + getIpAddr() + "] WxPropertyContractController::add");
        MallUserInfo user = getUser();
        wxPropertyContract.setTenantId(user.getTenantId());
        wxPropertyContract.setAdjustPeriodHandle();

        if(wxPropertyContract.getRentStartType()!=null && wxPropertyContract.getRentStartType().equals(EnumRentStartType.STARTTIME.getCode())){
            wxPropertyContract.setRentalStartDate(wxPropertyContract.getStartDate());
        }
        return wxPropertyContractService.saveOrUpdate(wxPropertyContract, user.getId(), user.getName());
    }

    @PostMapping("updateRentStartTime")
    @SystemControllerLog(description = "物业合同-更新租赁开始日期")
    public ResultData updateRentStartTime(@RequestBody WxPropertyContract wxPropertyContract) {
        logger.debug("[" + getIpAddr() + "] WxPropertyContractController::updateRentStartTime");
        WxPropertyContract propertyContract = wxPropertyContractMapper.selectById(wxPropertyContract.getId());
        MallUserInfo user = getUser();
        propertyContract.setTenantId(user.getTenantId());
        propertyContract.setAdjustPeriodHandle();
        propertyContract.setRentStartType(wxPropertyContract.getRentStartType());
        return wxPropertyContractService.saveOrUpdate(propertyContract, user.getId(), user.getName());
    }

    @PostMapping("update")
    @SystemControllerLog(description = "物业合同-修改")
    public ResultData update(@RequestBody WxPropertyContract wxPropertyContract) {
        logger.debug("[" + getIpAddr() + "] WxPropertyContractController::update");
        MallUserInfo user = getUser();
        wxPropertyContract.setTenantId(user.getTenantId());
        wxPropertyContract.setAdjustPeriodHandle();
        //第三步提交 SWITCH
        return wxPropertyContractService.saveOrUpdate(wxPropertyContract, user.getId(), user.getName());

    }

    @GetMapping("/del")
    @ApiImplicitParam(name = "id", value = "id", dataType = "Long", paramType = "query", required = true)
    @SystemControllerLog(description = "物业合同-删除")
    public ResultData delete(Long id) {
        logger.debug("[" + getIpAddr() + "] WxPropertyContractController::delete");
        wxPropertyContractService.deleteById(id);
        return new ResultData(Result.SUCCESS, "删除成功", null);
    }

    @GetMapping("/findById")
    @ApiImplicitParam(name = "id", value = "id", dataType = "Long", paramType = "query", required = true)
    @SystemControllerLog(description = "物业合同-根据ID查询")
    public ResultData findById(Long id) {
        logger.debug("[" + getIpAddr() + "] WxPropertyContractController::findById");
        WxBillProperty wxBillProperty = new WxBillProperty();
        wxBillProperty.setTenantId(super.getTenantId());
        wxBillPropertyService.updateBillStatus(wxBillProperty);
        try {
            Map<String, Object> data = wxPropertyContractService.getById(id);
            return new ResultData(data);
        } catch (MallinkException e) {
            logger.error(e.getMessage());
            return new ResultData(e.getErrorCode(), e.getMessage());
        }
    }

    @RequestMapping("/download")
    @SystemControllerLog(description = "物业合同-下载")
    public void download(HttpServletRequest request, HttpServletResponse response) {
        logger.debug("[" + getIpAddr() + "] WxPropertyContractController::download");
        wxPropertyContractService.download(request, response, getTenantId());
    }

    @GetMapping("/getPropertyContractStatusInfo")
    @SystemControllerLog(description = "物业合同-状态信息")
    public ResultData getPropertyContractStatusInfo(@ModelAttribute WxPropertyContract wxPropertyContract) {
        logger.debug("[" + getIpAddr() + "] WxPropertyContractController::getPropertyContractStatusInfo");
        wxPropertyContract.setTenantId(getTenantId());
        return new ResultData(Result.SUCCESS, "查询成功", wxPropertyContractService.getRentContractStatusInfo(wxPropertyContract));
    }

    @GetMapping("/endPropertyContract")
    @ApiImplicitParam(name = "id", value = "id", dataType = "Long", paramType = "query", required = true)
    @SystemControllerLog(description = "物业合同-终止")
    public ResultData endRentContract(Long id) {
        logger.debug("[" + getIpAddr() + "] WxPropertyContractController::endRentContract");
        return wxPropertyContractService.endRentContract(id);
    }

    @GetMapping("/getRentContractList")
    @SystemControllerLog(description = "物业合同-查询列表")
    public ResultData getRentContractList(@ModelAttribute WxPropertyContract wxPropertyContract) {
        logger.debug("[" + getIpAddr() + "] WxPropertyContractController::getRentContractList");
        wxPropertyContract.setTenantId(getTenantId());
        return new ResultData(Result.SUCCESS, "查询成功", wxPropertyContractService.getRentContractList(wxPropertyContract));
    }

    @GetMapping("/endPropertyContractByRentContractId")
    @ApiImplicitParam(name = "rentContractId", value = "rentContractId", dataType = "Long", paramType = "query", required = true)
    @SystemControllerLog(description = "物业合同-根据租赁合同终止")
    public ResultData endPropertyContractByRentContractId(Long rentContractId) {
        logger.debug("[" + getIpAddr() + "] WxPropertyContractController::endPropertyContractByRentContractId");
        return wxPropertyContractService.endPropertyContractByRentContractId(rentContractId);
    }

    @GetMapping("/hasRentContract")
    @ApiImplicitParam(name = "rentContractId", value = "rentContractId", dataType = "Long", paramType = "query", required = true)
    @SystemControllerLog(description = "物业合同-是否存在相关的租赁合同")
    public ResultData hasRentContract(Long rentContractId) {
        logger.debug("[" + getIpAddr() + "] WxPropertyContractController::hasRentContract");
        return wxPropertyContractService.hasRentContract(rentContractId);
    }

    @PostMapping("updatePropertyContractStatus")
    @ApiImplicitParam(name = "id", value = "id", dataType = "Long", paramType = "query", required = true)
    @SystemControllerLog(description = "物业合同-更新合同状态")
    public ResultData updatePropertyContractStatus(@RequestBody WxPropertyContract wxPropertyContract) {
        logger.debug("[" + getIpAddr() + "] WxPropertyContractController::updateRentContractStatus");
        return wxPropertyContractService.updatePropertyContractStatus(wxPropertyContract.getId());
    }

    @PostMapping("endContract")
    @SystemControllerLog(description = "物业合同-终止合同")
    public ResultData endContract(@RequestBody WxPropertyContract wxPropertyContract) {
        logger.debug("[" + getIpAddr() + "] WxRentContractController::endContract");
        wxPropertyContractService.endContract(wxPropertyContract);
        return new ResultData();
    }

    /**
     * 预览账单展示，编辑账期，后端生成账单金额
     * @param wxPropertyContract
     * @return
     */
    @PostMapping("buildBillPriceList")
    @SystemControllerLog(description = "物业合同-生成账单列表金额")
    public ResultData buildBillPriceList(@RequestBody WxPropertyContract wxPropertyContract) throws Exception{
        logger.debug("[" + getIpAddr() + "] WxRentContractController::buildBillPriceList");
        WxPropertyContract dbRent = wxPropertyContractMapper.selectById(wxPropertyContract.getId());
        dbRent.setPreviewBillRentList(wxPropertyContract.getPreviewBillRentList());
        if(dbRent.getRentStartType()!=null && dbRent.getRentStartType().equals(EnumRentStartType.STARTTIME.getCode())){
            dbRent.setRentalStartDate(dbRent.getStartDate());
        }
        List<WxBillProperty> result = wxPropertyContractService.buildProperty(new WxMerchant(),getUserId(),dbRent,  EnumIsPreview.YES.getCode(), false);
        return new ResultData(result);
    }
}
