package com.huyi.service.contract.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.huyi.service.base.entity.*;
import com.huyi.service.base.service.IPubFileInfService;
import com.huyi.service.base.service.IZcFinanceContractService;
import com.huyi.service.base.service.IZcFinanceProConRelService;
import com.huyi.service.base.service.IZcFinanceQuotaConRelService;
import com.huyi.service.contract.service.IOwnContractService;
import com.keao.tianhu.starter.mybatis.plus.entity.QueryRequest;
import com.tianhu.common.core.utils.CommonUtil;
import com.tianhu.common.core.utils.DateUtils;
import com.tianhu.common.core.utils.IdUtils;
import com.tianhu.common.core.web.controller.BaseController;
import com.tianhu.common.core.web.domain.AjaxResult;
import com.tianhu.common.log.annotation.Log;
import com.tianhu.common.log.enums.BusinessType;
import com.tianhu.common.security.annotation.PreAuthorize;
import com.tianhu.common.security.service.TokenService;
import com.tianhu.system.api.domain.SysUser;
import com.tianhu.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 合同controller
 *
 * @author ch
 * @date 2021-8-20
 */

@RestController
@RequestMapping("/contract")
public class ContractControllers extends BaseController {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IOwnContractService ownContractService;
    @Autowired
    private IZcFinanceContractService zcFinanceContractService;
    @Autowired
    private IZcFinanceProConRelService zcFinanceProConRelService;
    @Autowired
    private IZcFinanceQuotaConRelService zcFinanceQuotaConRelService;
    @Autowired
    private IPubFileInfService pubFileInfService;

    @GetMapping("/list")
    public AjaxResult list(String zfcName, String scyName,String zfcSubject , String zfcStatus, QueryRequest request) {
        //查询当前操作员
        LoginUser userInfo = tokenService.getLoginUser();
        SysUser use = userInfo.getSysUser();
        //获取企业
//        String companyId = use.getCompanyId();
        Map map = new HashMap(16);
//        if(CommonUtil.isNotEmpty(companyId)){
//            map.put("companyId",companyId);
//        }
        //合同模板名称
        if(CommonUtil.isNotEmpty(zfcName)){
            map.put("zfcName",zfcName);
        }
        //资方
        if(CommonUtil.isNotEmpty(scyName)){
            map.put("scyName",scyName);
        }
        //合同状态
        if(CommonUtil.isNotEmpty(zfcStatus)){
            map.put("zfcStatus",zfcStatus);
        }
        //签署主体
        if(CommonUtil.isNotEmpty(zfcSubject)){
            map.put("zfcSubject",zfcSubject);
        }
        IPage<Map> list = ownContractService.selectContractList(map,request);
        return AjaxResult.success(list);
    }

    /**
     * 查询合同详情
     * @param zfcId
     * @return
     */
    @PreAuthorize(hasPermi = "service:contract:query")
    @GetMapping(value = "/{zfcId}")
    public AjaxResult getInfo(@PathVariable("zfcId") String zfcId)
    {
        ZcFinanceContract zcFinanceContract = zcFinanceContractService.getById(zfcId);
        Map map = new HashMap(16);
        map.put("zcFinanceContract",zcFinanceContract);
        String zfcFile = zcFinanceContract.getZfcFile();
        PubFileInf pubFileInf = pubFileInfService.getById(zfcFile);
        if(pubFileInf !=null){
            String fileUrl = pubFileInf.getPfiUrl();
            String fileId = pubFileInf.getPfiFileId();
            String fileName = pubFileInf.getPfiFileName();
            map.put("fileUrl",fileUrl);
            map.put("fileId",fileId);
            map.put("fileName",fileName);
        }
        return AjaxResult.success(map);
    }

    @PreAuthorize(hasPermi = "service:contract:add")
    @Log(title = "合同", businessType = BusinessType.INSERT)
    @Transactional(rollbackFor=Exception.class)
    @PostMapping
    public AjaxResult add(@RequestBody Map<String,Object> map) throws Exception {
        //获取当前用户
        LoginUser userInf = tokenService.getLoginUser();
        String user = CommonUtil.objToString(userInf.getSysUser().getUserId());
        //合同模板名称
        String zfcName = CommonUtil.objToString(map.get("zfcName"));
        if(CommonUtil.isEmpty(zfcName)){
            return AjaxResult.error("合同模板名称不能为空");
        }
        //合同类型
        String zfcType = CommonUtil.objToString(map.get("zfcType"));
        if(CommonUtil.isEmpty(zfcType)){
            return AjaxResult.error("请选择合同类型");
        }
        //资金方
        String zfcManagementId = CommonUtil.objToString(map.get("zfcManagementId"));
        if(CommonUtil.isEmpty(zfcManagementId)){

            return AjaxResult.error("请选择资金方");
        }
        //签署主体
        String zfcSubject = CommonUtil.objToString(map.get("zfcSubject"));
        if(CommonUtil.isEmpty(zfcSubject)){
            return AjaxResult.error("请选择签署主体");
        }
        //签署节点
        String zfcNode = CommonUtil.objToString(map.get("zfcNode"));
        if(CommonUtil.isEmpty(zfcNode)){
            return AjaxResult.error("请选择签署节点");
        }
        //合同描述
        String zfcDesc = CommonUtil.objToString(map.get("zfcDesc"));
        //合同状态
        String zfcStatus = "00";
        //附件url
        List<Map<String, String>> file = (List<Map<String, String>>) map.get("zfcFile");
        if(file.size() == 0){
            return AjaxResult.error("请上传附件");
        }
        String zfcFile="";
        String zfcFileId = "";
        if(file.size()>0) {
            for (int j = 0; j < file.size(); j++) {
                Map<String, String> fileUrl = file.get(j);
                if (j == 0) {
                    zfcFile = fileUrl.get("url");
                    zfcFileId = CommonUtil.objToString(fileUrl.get("uid"));
                } else {
                    zfcFile += "," + fileUrl.get("url");
                    zfcFileId += "," + CommonUtil.objToString(fileUrl.get("uid"));
                }
            }
        }
        //截取符合要求的附件url
        if (CommonUtil.isNotEmpty(zfcFile)) {
            zfcFile = zfcFile.substring(0,zfcFile.indexOf("getBytes/")+41);
        }
        //主键
        String zfcId = IdUtils.fastUUID();
        //新增合同信息
        ZcFinanceContract zcFinanceContract = new ZcFinanceContract();
        zcFinanceContract.setZfcId(zfcId);
        zcFinanceContract.setZfcName(zfcName);
        zcFinanceContract.setZfcType(zfcType);
        zcFinanceContract.setZfcSubject(zfcSubject);
        zcFinanceContract.setZfcManagementId(zfcManagementId);
        zcFinanceContract.setZfcNode(zfcNode);
        zcFinanceContract.setZfcDesc(zfcDesc);
        zcFinanceContract.setZfcStatus(zfcStatus);
        zcFinanceContract.setZfcFile(zfcFileId);
        zcFinanceContract.setCreateBy(user);
        zcFinanceContract.setCreateTime(DateUtils.getNowDate());
        zcFinanceContractService.createZcFinanceContract(zcFinanceContract);
        return AjaxResult.success();
    }
    /**
     * 修改合同信息
     */
    @PreAuthorize(hasPermi = "service:contract:edit")
    @Log(title = "合同信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Map map)throws Exception {
        //获取当前用户
        LoginUser userInf = tokenService.getLoginUser();
        String user = CommonUtil.objToString(userInf.getSysUser().getUserId());
        //合同模板名称
        String zfcName = CommonUtil.objToString(map.get("zfcName"));
        if(CommonUtil.isEmpty(zfcName)){
            return AjaxResult.error("合同模板名称不能为空");
        }
        //合同类型
        String zfcType = CommonUtil.objToString(map.get("zfcType"));
        if(CommonUtil.isEmpty(zfcType)){
            return AjaxResult.error("请选择合同类型");
        }
        //资金方
        String zfcManagementId = CommonUtil.objToString(map.get("zfcManagementId"));
        if(CommonUtil.isEmpty(zfcManagementId)){
            return AjaxResult.error("请选择资金方");
        }
        //签署主体
        String zfcSubject = CommonUtil.objToString(map.get("zfcSubject"));
        if(CommonUtil.isEmpty(zfcSubject)){
            return AjaxResult.error("请选择签署主体");
        }
        //签署节点
        String zfcNode = CommonUtil.objToString(map.get("zfcNode"));
        if(CommonUtil.isEmpty(zfcNode)){
            return AjaxResult.error("请选择签署节点");
        }
        //合同描述
        String zfcDesc = CommonUtil.objToString(map.get("zfcDesc"));
        //合同状态
        String zfcStatus = CommonUtil.objToString(map.get("zfcStatus"));
        //附件url
        List<Map<String, String>> file = (List<Map<String, String>>) map.get("zfcFile");
        if(file.size() == 0){
            return AjaxResult.error("请上传附件");
        }
        String zfcFile="";
        String zfcFileId = "";
        if(file.size()>0) {
            for (int j = 0; j < file.size(); j++) {
                Map<String, String> fileUrl = file.get(j);
                if (j == 0) {
                    zfcFile = fileUrl.get("url");
                    zfcFileId = CommonUtil.objToString(fileUrl.get("uid"));
                } else {
                    zfcFile += "," + fileUrl.get("url");
                    zfcFileId += "," + CommonUtil.objToString(fileUrl.get("uid"));
                }
            }
        }
        //截取符合要求的附件url
//        if (CommonUtil.isNotEmpty(zfcFile)) {
//            zfcFile = zfcFile.substring(0,zfcFile.indexOf("getBytes/")+41);
//        }
        //主键
        String zfcId = IdUtils.fastUUID();
        //新增合同信息
        ZcFinanceContract zcFinanceContract = new ZcFinanceContract();
        zcFinanceContract.setZfcId(zfcId);
        zcFinanceContract.setZfcName(zfcName);
        zcFinanceContract.setZfcType(zfcType);
        zcFinanceContract.setZfcSubject(zfcSubject);
        zcFinanceContract.setZfcManagementId(zfcManagementId);
        zcFinanceContract.setZfcNode(zfcNode);
        zcFinanceContract.setZfcDesc(zfcDesc);
        zcFinanceContract.setZfcStatus(zfcStatus);
        zcFinanceContract.setZfcFile(zfcFileId);
        zcFinanceContract.setUpdateBy(user);
        zcFinanceContract.setUpdateTime(DateUtils.getNowDate());
        zcFinanceContractService.updateZcFinanceContract(zcFinanceContract);
        return AjaxResult.success();
    }
    /**
     * 修改合同启用状态
     * @param zfcId
     * @return
     */
    @PreAuthorize(hasPermi = "service:contract:change")
    @Log(title = "合同状态", businessType = BusinessType.UPDATE)
    @PutMapping("/change/{zfcId}")
    public AjaxResult changState(@PathVariable String zfcId){
        //查询产品原状态
        ZcFinanceContract zcFinanceContract =  zcFinanceContractService.getById(zfcId);
        String state = zcFinanceContract.getZfcStatus();
        //如果是启用改为停用
        if("01".equals(state)){
            //查询合同是否关联产品
            LambdaQueryWrapper<ZcFinanceProConRel> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ZcFinanceProConRel::getZfpcrContractId,zfcId);
            int count = zcFinanceProConRelService.count(queryWrapper);
            //查询合同是否关联授信
            LambdaQueryWrapper<ZcFinanceQuotaConRel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ZcFinanceQuotaConRel::getZfqcrContractId,zfcId);
            int count1 = zcFinanceQuotaConRelService.count(lambdaQueryWrapper);
            //若已关联提示不可停用
            if(count > 0 || count1 > 0){
                return AjaxResult.error("合同已被使用,不可停用!");
            }else {
                zcFinanceContract.setZfcStatus("00");
            }
        }else {
            //反之改为启用
            zcFinanceContract.setZfcStatus("01");
        }
        //执行修改
        zcFinanceContractService.updateZcFinanceContract(zcFinanceContract);
        return AjaxResult.success();
    }
    /**
     * 删除合同
     * @param zfcId
     * @return
     */
    @PreAuthorize(hasPermi = "service:contract:delete")
    @Log(title = "合同删除", businessType = BusinessType.UPDATE)
    @DeleteMapping("/{zfcId}")
    public AjaxResult delete(@PathVariable String zfcId){
        //查询产品原状态
        ZcFinanceContract zcFinanceContract =  zcFinanceContractService.getById(zfcId);
        //查询合同是否关联产品
        LambdaQueryWrapper<ZcFinanceProConRel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZcFinanceProConRel::getZfpcrContractId,zfcId);
        int count = zcFinanceProConRelService.count(queryWrapper);
        //查询合同是否关联授信
        LambdaQueryWrapper<ZcFinanceQuotaConRel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ZcFinanceQuotaConRel::getZfqcrContractId,zfcId);
        int count1 = zcFinanceQuotaConRelService.count(lambdaQueryWrapper);
        //若已关联提示不可停用
        if(count > 0 || count1 > 0){
            return AjaxResult.error("合同已被使用,不可删除!");
        }else {
            zcFinanceContract.setZfcStatus("02");
        }
        //执行修改
        zcFinanceContractService.updateZcFinanceContract(zcFinanceContract);
        return AjaxResult.success();
    }

}
