package com.yunzhi.marketing.eContract.controller;

import com.alibaba.fastjson.JSONObject;
import com.fadada.sdk.client.FddClientBase;
import com.yunzhi.marketing.base.BaseController;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.bo.request.ContractRecordRequestBO;
import com.yunzhi.marketing.common.CommonUtils;
import com.yunzhi.marketing.config.FadadaProperties;
import com.yunzhi.marketing.eContract.entity.TaContract;
import com.yunzhi.marketing.eContract.service.ITaContractService;
import com.yunzhi.marketing.entity.TaPerson;
import com.yunzhi.marketing.entity.TaRaiseRecord;
import com.yunzhi.marketing.service.ITaPersonService;
import com.yunzhi.marketing.entity.TaRaise;
import com.yunzhi.marketing.entity.TaSalesBatch;
import com.yunzhi.marketing.service.ITaRaiseService;
import com.yunzhi.marketing.service.ITaSalesBatchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.List;
import java.time.LocalDateTime;


/**
 * <p>
 * 合同列表  前端控制器
 * </p>
 *
 * @author fxf
 * @since 2020-03-26
 */
@RestController
@RequestMapping("/api")
public class TaContractController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(TaContractController.class);

    @Autowired
    private ITaContractService iTaContractService;

    @Autowired
    private ITaRaiseService iTaRaiseService;

    @Autowired
    private ITaSalesBatchService iTaSalesBatchService;


    @Autowired
    public ITaPersonService taPersonService;

    @Autowired
    private FadadaProperties fadadaProperties;

    /**
     * 条件查询合同列表 -- admin端
     *
     * @param pageNum
     * @param pageSize
     * @param contractName
     * @param archives
     * @param signatoryName
     * @param signatoryStatus   甲方是否签署，1是，0否，2全部
     * @param customerName
     * @param customerStatus    乙方是否签署，1是，0否，2全部
     * @param archivesStartDate
     * @param archivesEndDate
     * @return
     */
    @RequestMapping(value = "/admin/contract/list", method = RequestMethod.GET)
    public ResponseBean listContractForAdmin(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                             @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                             String contractName, Boolean archives,
                                             String signatoryName, Integer signatoryStatus,
                                             String customerName, Integer customerStatus,
                                             @RequestParam(value = "archivesStartDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate archivesStartDate,
                                             @RequestParam(value = "archivesEndDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate archivesEndDate,
                                             HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaContractService.listContractForAdmin(pageNum, pageSize, contractName, archives, signatoryName, signatoryStatus, customerName, customerStatus, archivesStartDate, archivesEndDate, getOrgId(request));
            logger.info("TaContractController.listContractForAdmin 返回结果：{}", JSONObject.toJSONString(responseBean));
        } catch (Exception e) {
            logger.error("TaContractController.listContractForAdmin 异常：", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    /**
     * 条件查询合同列表 -- channel端
     *
     * @param requestBO
     * @return
     */
    @RequestMapping(value = "/channel/contract/list", method = RequestMethod.GET)
    public ResponseBean listContractForChannel(ContractRecordRequestBO requestBO) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaContractService.listContractForChannel(requestBO);
            logger.info("TaContractController.listContractForChannel 返回结果:{}", JSONObject.toJSONString(responseBean));
        } catch (Exception e) {
            logger.error("TaContractController.listContractForChannel 异常：", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 批量结算
     *
     * @return
     */
    @RequestMapping(value = "/channel/contract/batchUpdatePrice", method = RequestMethod.PUT)
    public ResponseBean batchUpdateSettlementPrice(@RequestBody TaContract taContract) {
        ResponseBean responseBean = new ResponseBean();
        try {
            // 校验参数
            if (taContract.getPrice() == null) {
                responseBean.addError("请填写结算金额");
                return responseBean;
            }

            // 校验金额是否符合要求
            if (!CommonUtils.isAmount(taContract.getPrice() + "")) {
                responseBean.addError("结算金额不符合要求");
                return responseBean;
            }

            // 元转分
            Double price = taContract.getPrice() * 100;
            taContract.getTaContractList().stream().forEach(record -> {
                record.setSettlement(true);
                record.setSettlementPrice(price.intValue());
                record.setSettlementTime(LocalDateTime.now());
            });
            responseBean.addSuccess(iTaContractService.updateBatchById(taContract.getTaContractList()));

        } catch (Exception e) {
            logger.error("TaContractController.batchUpdateSettlementPrice 异常：", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     *
     * @param taContract 实体对象
     * @return
     */
    @RequestMapping(value = "/taContract", method = RequestMethod.POST)
    public ResponseBean taContractAdd(@RequestBody TaContract taContract) {
        ResponseBean responseBean = new ResponseBean();
        try {
            if (iTaContractService.save(taContract)) {
                responseBean.addSuccess(taContract);
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taContractAdd -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id删除对象
     *
     * @param id 实体ID
     */
    @ResponseBody
    @RequestMapping(value = "/taContract/{id}", method = RequestMethod.DELETE)
    public ResponseBean taContractDelete(@PathVariable Integer id) {
        ResponseBean responseBean = new ResponseBean();
        try {
            if (iTaContractService.removeById(id)) {
                responseBean.addSuccess("success");
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taContractDelete -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     *
     * @param id         实体ID
     * @param taContract 实体对象
     * @return
     */
    @RequestMapping(value = "/admin/contract/{id}", method = RequestMethod.PUT)
    public ResponseBean taContractUpdate(@PathVariable Integer id,
                                         @RequestBody TaContract taContract) {
        ResponseBean responseBean = new ResponseBean();
        try {
            if (taContract.getArchives() != null && taContract.getArchives()) {
                taContract.setArchivesTime(LocalDateTime.now());
            }
            if (iTaContractService.updateById(taContract)) {
                FddClientBase base = new FddClientBase(fadadaProperties.getAppId(),fadadaProperties.getAppSecret(),fadadaProperties.getVersion(),fadadaProperties.getServeHost());
                String contract_id = taContract.getContractId().toString();
                String result = base.invokeContractFilling(contract_id);
                logger.info("合同归档结果{}",result);
                responseBean.addSuccess(iTaContractService.getById(taContract.getContractId()));
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taContractUpdate -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     *
     * @param id 实体ID
     */
    @RequestMapping(value = "/admin/contract/{id}", method = RequestMethod.GET)
    public ResponseBean taContractGet(@PathVariable Integer id) {
        ResponseBean responseBean = new ResponseBean();
        try {
            TaContract taContract = iTaContractService.getById(id);
            if(taContract != null){
                TaRaise taRaise = iTaRaiseService.getById(taContract.getTargetId());
                if(taRaise != null){
                    TaSalesBatch taSalesBatch = iTaSalesBatchService.getById(taRaise.getSalesBatchId());
                    if(taSalesBatch != null){
                        taContract.setTargetName(taSalesBatch.getSalesBatchName());
                    }
                }
            }
            responseBean.addSuccess(taContract);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taContractDelete -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 自动签署合同
     */
    @RequestMapping(value = "/wx/contract/auto", method = RequestMethod.POST)
    public ResponseBean autoContract(@RequestBody TaRaiseRecord taRaiseRecord, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            String openid = getOpenId(request);
            List<TaPerson> taPersons = taPersonService.getPersonsByOpenId(openid);
            if (null == taPersons || taPersons.size() != 1) {
                return ResponseBean.error("验证人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
            }
            TaPerson person = taPersons.get(0);
            TaContract taContract = iTaContractService.autoContract(taRaiseRecord, person);
            responseBean.addSuccess(taContract);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taCompanyList -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    /**
     * 手动签署合同
     */
    @RequestMapping(value = "/wx/contract/manual", method = RequestMethod.POST)
    public ResponseBean manualContract(@RequestBody TaContract taContract, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            String openid = getOpenId(request);
            List<TaPerson> taPersons = taPersonService.getPersonsByOpenId(openid);
            if (null == taPersons || taPersons.size() != 1) {
                return ResponseBean.error("验证人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
            }
            TaPerson person = taPersons.get(0);
            String signUrl = iTaContractService.manualContract(taContract, person);
            return ResponseBean.success(signUrl);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taCompanyList -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    /**
     * 自动签署合同
     */
    @RequestMapping(value = "/wx/contract/check", method = RequestMethod.POST)
    public ResponseBean checkContract(@RequestBody TaRaiseRecord taRaiseRecord, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            String openid = getOpenId(request);
            List<TaPerson> taPersons = taPersonService.getPersonsByOpenId(openid);
            if (null == taPersons || taPersons.size() != 1) {
                return ResponseBean.error("验证人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
            }
            TaPerson person = taPersons.get(0);
            TaContract taContract = iTaContractService.checkContract(taRaiseRecord, person);
            responseBean.addSuccess(taContract);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taCompanyList -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
