package com.huyi.service.financeRecord.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.*;
import com.huyi.service.financeRecord.service.FinanceRecordService;
import com.keao.tianhu.starter.mybatis.plus.entity.QueryRequest;
import com.sun.xml.internal.bind.v2.TODO;
import com.tianhu.common.core.constant.SalaryConstants;
import com.tianhu.common.core.domain.R;
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.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * 融资管理Controller
 *
 * @author pxh
 * @date 2021-02-04
 */

@RestController
@RequestMapping("/financeRecord")
public class FinanceRecordController extends BaseController {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private FinanceRecordService financeRecordService;
    @Autowired
    private IZcFinanceInfService zcFinanceInfService;
    @Autowired
    private IZcFinanceProComRelService iZcFinanceProComRelService;
    @Autowired
    private IZcFinanceProductService iZcFinanceProductService;
    @Autowired
    private IPayAccInfService iPayAccInfService;
    @Autowired
    private IZcFinanceBillRelService iZcFinanceBillRelService;
    @Autowired
    private IZcBillInfService iZcBillInfService;
    @Autowired
    private IZcFinanceRecordService iZcFinanceRecordService;
     /**
     * 查询融资管理列表
     */
    @PreAuthorize(hasPermi = "finance:record:list")
    @GetMapping("/list")
    public R list(@RequestParam (required = false) String zfrStatus, QueryRequest request) {
        //查询当前操作员
        LoginUser userInfo = tokenService.getLoginUser();
        SysUser use = userInfo.getSysUser();
        //获取企业
        String companyId = use.getCompanyId();
        Map map = new HashMap();
        if (!SalaryConstants.OPEX.equals(companyId)) {
            map.put("companyId", companyId);
        }
        map.put("zfrStatus",zfrStatus);
        IPage<Map> list = financeRecordService.selectFinanceRecordList(map, request);
        return R.ok(list);
    }

    /**
     * 新增融资管理
     * @param map
     * @return
     * @throws Exception
     */
    @PreAuthorize(hasPermi = "finance:record:add")
    @Log(title = "融资管理", businessType = BusinessType.INSERT)
    @Transactional(rollbackFor = Exception.class)
    @PostMapping
    public AjaxResult add(@RequestBody Map<String,Object> map)throws Exception
    {
        //获取此操作员
        LoginUser userInfo = tokenService.getLoginUser();
        SysUser user = userInfo.getSysUser();
        String userId = user.getUserId() + "";
        //融信id
        String zfrFinanceId = CommonUtil.objToString(map.get("zfrFinanceId"));
        //融资金额
        String zfrAmount = CommonUtil.objToString(map.get("zfrAmount"));
        //融资收款账号
        String zfrCollectionAccount = CommonUtil.objToString(map.get("zfrCollectionAccount"));
        //融资利率
        String zfrRate = CommonUtil.objToString(map.get("zfrRate"));
        //融资放款方式(0:平台电子记账簿 1:供应商指定账户 2:供应商线下面签)
        String zfpcrLoanType = CommonUtil.objToString(map.get("zfpcrLoanType"));
        //融资产品
        String zfiProductId = CommonUtil.objToString(map.get("zfiProductId"));
        //承诺还款时间
        String zfrRepaymentDate = CommonUtil.objToString(map.get("zfrRepaymentDate"));
        //获取创建时间
        Date createTime =  DateUtils.getNowDate();
        //获取当前时间
        String currentTime = DateUtils.parseDateToStr("yyyyMMddHHmmss",createTime);
        if (CommonUtil.isEmpty(zfrFinanceId)) {
            throw new Exception("融信编号不能为空");
        }
        if (CommonUtil.isEmpty(zfrAmount)){
            throw new Exception("融资金额不能为空");
        }
        //融资编号
        String  zfrNumber = "MB";
        //查询融资产品编号
        ZcFinanceProduct zcFinanceProduct = iZcFinanceProductService.getById(zfiProductId);
        //资方id
        String zfpManagementId = zcFinanceProduct.getZfpManagementId();
        //融资产品编号
        String zfpNumber = zcFinanceProduct.getZfpNumber();
        zfpNumber = StringUtils.substring(zfpNumber,0,2);
        zfrNumber += zfpNumber;
        zfrNumber += currentTime;
        //融资放款方式为:平台电子记账簿=>融资收款账号为资方电子账户,供应商指定账户=>融资收款账号为必输,供应商线下面签=>融资收款账号为非必输
        if ("1".equals(zfpcrLoanType)){
            if (CommonUtil.isEmpty(zfrCollectionAccount)){
                throw new Exception("融资收款账号不能为空");
            }
        }else if ("0".equals(zfpcrLoanType)){
            //通过资方id查询电子账户表
            LambdaQueryWrapper<PayAccInf> accInfWrapper = new LambdaQueryWrapper<>();
            //账户状态(0:未开通，1：冻结,2已开通3:待激活)
            accInfWrapper.eq(PayAccInf::getPaiStatus,"2");
            //TODO 账户类型(00基本账户01贷款账户02信用账户03手续费账户04待结算账户05提现账户06邢台银行虚拟账户)
            accInfWrapper.eq(PayAccInf::getPaiAcctype,"00");
            //资方id
            accInfWrapper.eq(PayAccInf::getPaiCstno,zfpManagementId);
            List<PayAccInf> accInfList = iPayAccInfService.findPayAccInfs(accInfWrapper);
            if (accInfList.size() == 0){
                throw new Exception("暂无电子账户");
            }else {
                zfrCollectionAccount = accInfList.get(0).getPaiAccno();
            }
        }
        //执行新增
        ZcFinanceRecord zcFinanceRecord = new ZcFinanceRecord();
        //主键
        String zfrId = IdUtils.fastSimpleUUID();
        zcFinanceRecord.setZfrId(zfrId);
        //融资编号
        zcFinanceRecord.setZfrNumber(zfrNumber);
        //融信id
        zcFinanceRecord.setZfrFinanceId(zfrFinanceId);
        //融资金额
        zcFinanceRecord.setZfrAmount(zfrAmount);
        //融资利率
        zcFinanceRecord.setZfrRate(zfrRate);
        //融资收款账号
        zcFinanceRecord.setZfrCollectionAccount(zfrCollectionAccount);
        //承诺还款时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM
        zcFinanceRecord.setZfrRepaymentDate(simpleDateFormat.parse(zfrRepaymentDate));
        //融资申请日期
        zcFinanceRecord.setZfrApplyDate(createTime);
        //TODO 经办人
        zcFinanceRecord.setZfrHandler(userId);
        //审批状态
        //TODO
        //融资状态
        zcFinanceRecord.setZfrStatus("00");
        //创建者
        zcFinanceRecord.setCreateBy(userId);
        //创建时间
        zcFinanceRecord.setCreateTime(createTime);
        iZcFinanceRecordService.createZcFinanceRecord(zcFinanceRecord);
        return AjaxResult.success();
    }

    /**
     * 查询往来账款
     * @param zfiId 融信id
     * @return
     */
    @GetMapping("listBillInf/{zfiId}")
    public AjaxResult listBillInf(@PathVariable("zfiId") String zfiId) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        //最终结果
        Map result = new HashMap();
        //查询当前操作员
        LoginUser userInfo = tokenService.getLoginUser();
        SysUser user = userInfo.getSysUser();
        //获取企业
        String companyId = user.getCompanyId();
        LambdaQueryWrapper<ZcFinanceBillRel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ZcFinanceBillRel::getZfbrFinanceId,zfiId);
        List<ZcFinanceBillRel> relList = iZcFinanceBillRelService.findZcFinanceBillRels(queryWrapper);
        //查询往来账款
        Map map = new HashMap();
        if (relList.size() > 0){
            //提取所有的
            List<String>  billIdList = CommonUtil.getIdFromList(relList,"zfbrBillId");
            map.put("billIdList",CommonUtil.listToStr4InSql(billIdList));
        }
        List<Map> list = financeRecordService.selectBillInfList(map);
        return AjaxResult.success(list);
    }

}

