package com.yeejoin.amos.boot.module.hygf.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yeejoin.amos.boot.module.hygf.api.Enum.CodeEnum;
import com.yeejoin.amos.boot.module.hygf.api.Enum.HouseholdContractEnum;
import com.yeejoin.amos.boot.module.hygf.api.Enum.TaskTypeStationEnum;
import com.yeejoin.amos.boot.module.hygf.api.dto.ContractDataDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.HouseholdContractDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.HouseholdContractPageDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.TemplateParamDto;
import com.yeejoin.amos.boot.module.hygf.api.entity.*;
import com.yeejoin.amos.boot.module.hygf.api.mapper.*;
import com.yeejoin.amos.boot.module.hygf.api.service.IHouseholdContractService;
import com.yeejoin.amos.boot.module.hygf.api.util.NumberUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 服务实现类
 *
 * @author system_generator
 * @date 2023-08-21
 */
@Service
public class HouseholdContractServiceImpl extends BaseService<HouseholdContractDto,HouseholdContract,HouseholdContractMapper> implements IHouseholdContractService {


    @Autowired
    HouseholdContractMapper householdContractMapper;
    @Autowired
    QiyuesuoServiceImpl qiyuesuoServiceImpl;

    @Autowired
    SealDictionaryMapper sealDictionaryMapper;

    @Autowired
    ContractTemplateMapper contractTemplateMapper;

    @Autowired
    ToDoTasksServiceImpl toDoTasksServiceImpl;

    @Autowired
    PeasantHouseholdServiceImpl peasantHouseholdServiceImpl;
    @Autowired
    ContractFillDataMapper contractFillDataMapper;

    @Autowired
    RegionalCompaniesMapper regionalCompaniesMapper;
    /**
     * 列表查询 示例
     */
    public List<HouseholdContractDto> queryForHouseholdContractList()   {
        return this.queryForList("" , false);
    }


    /**
     * 分页查询
     */
    public IPage<HouseholdContract> queryForPreparationMoneyPage(HouseholdContractPageDto dto)   {

//        //列表数据组装
//        QueryWrapper<HouseholdContract> qw = new QueryWrapper<>();
//        qw.like(StringUtils.isNotEmpty(dto.getName()), "name", dto.getName());
//        qw.like(StringUtils.isNotEmpty(dto.getContractNumber()), "contract_number", dto.getContractNumber());
//        qw.eq(StringUtils.isNotEmpty(dto.getInitiateStatus()), "initiate_status",dto.getInitiateStatus() );
//
//        qw.eq(dto.getPeasantHouseholdId()!=null, "peasant_household_id",dto.getPeasantHouseholdId() );
//        qw.eq(dto.getDealerId()!=null, "dealer_id",dto.getDealerId() );
//        qw.eq(StringUtils.isNotEmpty(dto.getSurveyStatus()), "survey_status",dto.getSurveyStatus() );
//        qw.eq(StringUtils.isNotEmpty(dto.getSignStatus()), "sign_status",dto.getSignStatus() );
//        qw.eq(StringUtils.isNotEmpty(dto.getUserId()), "project_user_id",dto.getUserId() );
//        qw.like(StringUtils.isNotEmpty(dto.getPartyA()), "party_a",dto.getPartyA() );
//
//
//        if (StringUtils.isNotEmpty(dto.getOrderBy())) {
//            qw.orderBy(Boolean.TRUE, dto.getIsASC(), dto.getOrderBy());
//        }else{
//            qw.orderBy(Boolean.TRUE, Boolean.FALSE, "rec_date");
//        }
        IPage<HouseholdContract> warningQuestionInfoIPage = householdContractMapper.selectPage(dto);

        return warningQuestionInfoIPage;
    }

    //农户注册成功后生成合同

    public void addHouseholdContract(HouseholdContract householdContract){

        householdContract.setContractNumber(this.getnum(householdContract.getRegionalCompaniesSeq()));//合同编号
        householdContract.setSurveyStatus(HouseholdContractEnum.勘察状态_未勘察.getCode());
        householdContract.setStatus(HouseholdContractEnum.合同状态_未签署.getCode());
        householdContract.setSignStatus(HouseholdContractEnum.签字状态_未签字.getCode());
        householdContract.setStampStatus(HouseholdContractEnum.盖章状态_未盖章.getCode());
        householdContract.setInitiateStatus(HouseholdContractEnum.发起状态_未发起.getCode());
        householdContractMapper.insert(householdContract);
    }
    public void reissueHouseholdContract(HouseholdContract householdContract){

        householdContract.setContractNumber(this.getnum(householdContract.getRegionalCompaniesSeq()));//合同编号
        householdContract.setStatus(HouseholdContractEnum.合同状态_未签署.getCode());
        householdContract.setSignStatus(HouseholdContractEnum.签字状态_未签字.getCode());
        householdContract.setStampStatus(HouseholdContractEnum.盖章状态_未盖章.getCode());
        householdContract.setInitiateStatus(HouseholdContractEnum.发起状态_未发起.getCode());
        householdContractMapper.insert(householdContract);
    }

    public String getnum(Long sequenceNbr) {
        RegionalCompanies da= regionalCompaniesMapper.selectRegionName(sequenceNbr);
        if(da.getCompanyCode()==null||da.getCompanyCode().isEmpty()){
            throw new BadRequest("区域公司编号为空, 请设置编号");
        }
        if(da.getRegionalAddress()==null||da.getRegionalAddress().isEmpty()){
            throw new BadRequest("区域公司省市区为空, 请设置省市区");
        }
        String code=  NumberUtil.getCode(CodeEnum.勘察.getCode(),da.getCompanyCode(),da.getRegionalAddress());
        return code;
    }


    @Transactional
    public HouseholdContract initiateHouseholdContract(HouseholdContractDto model){
        HouseholdContract householdContract=  householdContractMapper.selectById(model.getSequenceNbr());
        householdContract.setPartyA(model.getPartyA());
        householdContract.setPartyB(model.getPartyB());
        householdContract.setContractTemplateId(model.getContractTemplateId());
        householdContract.setRentFree(model.getRentFree());
        householdContract.setRentCalculationDate(model.getRentCalculationDate());
        householdContract.setLeaseEndDate(model.getLeaseEndDate());
        householdContract.setConstructionScale(model.getConstructionScale());
        householdContract.setComponentQuantityBlock(model.getComponentQuantityBlock());
        householdContract.setTotalInvestment(model.getTotalInvestment());
        householdContract.setComponentPower(model.getComponentPower());
        householdContract.setStationPower(model.getStationPower());
        householdContract.setName(model.getName());
        //调用第三方
        ContractDataDto contractDataDto =new ContractDataDto();
        contractDataDto.setUsername(model.getPartyA());
        contractDataDto.setContact(model.getPeasantHouseholdPhone());
        contractDataDto.setIDCard(model.getPeasantHouseholdCard());
        contractDataDto.setSubject(model.getName());

        QueryWrapper<SealDictionary> queryWrapper=new QueryWrapper();
        queryWrapper.eq("amos_company_seq",householdContract.getRegionalCompaniesSeq());
        SealDictionary sealDictionary=sealDictionaryMapper.selectOne(queryWrapper);
        contractDataDto.setCategory(sealDictionary.getCategory());
        contractDataDto.setCompanyTenantName(sealDictionary.getCompanyTenantName());
        contractDataDto.setCompanyUsername(sealDictionary.getSealedUser());
        contractDataDto.setCompanyContact(sealDictionary.getSealedPhone());
        List<Long> listSealId= new ArrayList<>();
        listSealId.add(sealDictionary.getSealId());
        contractDataDto.setSealId(listSealId);



        QueryWrapper<ContractTemplate> qu=new QueryWrapper();
        qu.eq("template_id",model.getContractTemplateId());
        ContractTemplate contractTemplate=contractTemplateMapper.selectOne(qu);
        contractDataDto.setEmplateId(model.getContractTemplateId());
        contractDataDto.setCompanykeyword(contractTemplate.getCompanyKeyword());
        contractDataDto.setCompanyPage(contractTemplate.getCompanyPage());
        contractDataDto.setCompanyOffsetX(contractTemplate.getCompanyOffsetx());
        contractDataDto.setCompanyOffsetY(contractTemplate.getCompanyOffsety());
        contractDataDto.setCompanyKeywordIndex(contractTemplate.getCompanyKeywordIndex());
        contractDataDto.setPersonalkeyword(contractTemplate.getPersonalKeyword());
        contractDataDto.setPersonalPage(contractTemplate.getPersonalPage());
        contractDataDto.setPersonalOffsetX(contractTemplate.getPersonalOffsetx());
        contractDataDto.setPersonalOffsetY(contractTemplate.getPersonalOffsety());
        contractDataDto.setPersonalKeywordIndex(contractTemplate.getPersonalKeywordIndex());
        SimpleDateFormat myFmt2=new SimpleDateFormat("yyyy-MM-dd");
        Date now=new Date();
        String daty= myFmt2.format(now);
        List<TemplateParamDto> templateParam=new ArrayList<>();
        //公共字段填充
        SimpleDateFormat sdfdate = new SimpleDateFormat("yyyy-MM-dd");
        templateParam.add(new TemplateParamDto("partyA",householdContract.getPartyA()!=null?householdContract.getPartyA():null));
        templateParam.add(new TemplateParamDto("peasantHouseholdPhone",householdContract.getPeasantHouseholdPhone()!=null?householdContract.getPeasantHouseholdPhone():null));
        templateParam.add(new TemplateParamDto("peasantHouseholdCard",householdContract.getPeasantHouseholdCard()!=null?householdContract.getPeasantHouseholdCard():null));
        templateParam.add(new TemplateParamDto("permanentAddressDetail",householdContract.getPermanentAddressName()!=null?householdContract.getPermanentAddressName()+householdContract.getPermanentAddressDetail():null));
        templateParam.add(new TemplateParamDto("projectAddressDetail",householdContract.getProjectAddressName()!=null?householdContract.getProjectAddressName()+householdContract.getProjectAddressDetail():null));
        templateParam.add(new TemplateParamDto("signingTime",daty));

        //合同动态填充字段
//        templateParam.add(new TemplateParamDto("rentFree",householdContract.getRentFree()!=null?sdfdate.format(householdContract.getRentFree()):null));
//        templateParam.add(new TemplateParamDto("rentCalculationDate",householdContract.getRentCalculationDate()!=null?sdfdate.format(householdContract.getRentCalculationDate()):null));
//        templateParam.add(new TemplateParamDto("leaseEndDate",householdContract.getLeaseEndDate()!=null?sdfdate.format(householdContract.getLeaseEndDate()):null));
 //      templateParam.add(new TemplateParamDto("constructionScale",householdContract.getConstructionScale()!=null?String.valueOf(householdContract.getConstructionScale()):null));
//        templateParam.add(new TemplateParamDto("componentQuantityBlock",householdContract.getComponentQuantityBlock()!=null?String.valueOf(householdContract.getComponentQuantityBlock()):null));
//        templateParam.add(new TemplateParamDto("totalInvestment",householdContract.getTotalInvestment()!=null?String.valueOf(householdContract.getTotalInvestment()):null));
//        templateParam.add(new TemplateParamDto("componentPower",householdContract.getComponentPower()!=null?String.valueOf(householdContract.getComponentPower()):null));
//        templateParam.add(new TemplateParamDto("stationPower",householdContract.getStationPower()!=null?String.valueOf(householdContract.getStationPower()):null));

        List<ContractFillData> contractFillData= model.getContractFillData();
        if(contractFillData!=null&&!contractFillData.isEmpty()){
            for (ContractFillData contractFillDatum : contractFillData) {
                templateParam.add(new TemplateParamDto(contractFillDatum.getField(),contractFillDatum.getValue()));
                //保存动态值
                contractFillDatum.setSequenceNbr(null);
                contractFillDatum.setContractId(householdContract.getSequenceNbr());
                contractFillDataMapper.insert(contractFillDatum);
            }
        }

        Long  contractLockId=qiyuesuoServiceImpl.addContract(contractDataDto , templateParam);
        householdContract.setContractLockId(contractLockId);
        householdContract.setInitiateStatus(HouseholdContractEnum.发起状态_已发起.getCode());
        householdContractMapper.updateById(householdContract);
        //创建农户待办

        ToDoTasks toDoTasks1=  new ToDoTasks (  TaskTypeStationEnum.合同填报.getCode(),  householdContract.getSequenceNbr(),   "用户"+householdContract.getPartyA()+"的合同填写",householdContract.getDealerCode());
        PeasantHousehold peasantHousehold=peasantHouseholdServiceImpl.getById(householdContract.getPeasantHouseholdId());
        toDoTasksServiceImpl.addToDoTasksByUserId(peasantHousehold.getAmosUserId(),toDoTasks1,"任务明细：合同发起成功");
        return householdContract;

    }


     @Transactional
    public HouseholdContract reissueinitiateHouseholdContract(HouseholdContract model){
         // 查询已存在的合同，如果存在有效(非作废)的合同，则无法重新发起
         Long peasantHouseholdId = model.getPeasantHouseholdId();
         Integer count = householdContractMapper.selectCount(
                 Wrappers.<HouseholdContract>lambdaQuery()
                         .eq(HouseholdContract::getPeasantHouseholdId, peasantHouseholdId)
                         .ne(HouseholdContract::getStatus, HouseholdContractEnum.合同状态_已作废.getCode())
                         .eq(HouseholdContract::getIsDelete, false)
         );
         if (count > 0) {
             throw new BadRequest("已存在有效的合同，无法重新发起");
         }

         HouseholdContract peasantHousehold=  this.getById(model.getSequenceNbr());
        //生成合同
        HouseholdContract householdContract=new HouseholdContract();
        householdContract.setPartyA(model.getPartyA());
        householdContract.setPartyB(model.getPartyB());
        householdContract.setContractTemplateId(model.getContractTemplateId());
        householdContract.setRentFree(model.getRentFree());
        householdContract.setRentCalculationDate(model.getRentCalculationDate());
        householdContract.setLeaseEndDate(model.getLeaseEndDate());
        householdContract.setConstructionScale(model.getConstructionScale());
        householdContract.setComponentQuantityBlock(model.getComponentQuantityBlock());
        householdContract.setTotalInvestment(model.getTotalInvestment());
        householdContract.setComponentPower(model.getComponentPower());
        householdContract.setStationPower(model.getStationPower());
        householdContract.setName(model.getName());


        householdContract.setPeasantHouseholdNumber(peasantHousehold.getPeasantHouseholdNumber());
        householdContract.setPeasantHouseholdCard(peasantHousehold.getPeasantHouseholdCard());
        householdContract.setDealerId(peasantHousehold.getDealerId());
        householdContract.setDealerCode(peasantHousehold.getDealerCode());
        householdContract.setDealerName(peasantHousehold.getDealerName());
        householdContract.setPeasantHouseholdId(peasantHousehold.getPeasantHouseholdId());
        householdContract.setRegionalCompaniesCode(peasantHousehold.getRegionalCompaniesCode());
        householdContract.setRegionalCompaniesName(peasantHousehold.getRegionalCompaniesName());
        householdContract.setRegionalCompaniesSeq(peasantHousehold.getRegionalCompaniesSeq());
        householdContract.setPeasantHouseholdPhone(peasantHousehold.getPeasantHouseholdPhone());
        householdContract.setProjectAddressDetail(peasantHousehold.getProjectAddressDetail());
        householdContract.setProjectAddressName(peasantHousehold.getProjectAddressName());
        householdContract.setPermanentAddressDetail(peasantHousehold.getPermanentAddressDetail());
        householdContract.setPermanentAddressName(peasantHousehold.getPermanentAddressName());
        householdContract.setProjectUserId(peasantHousehold.getProjectUserId());
        householdContract.setSurveyStatus(peasantHousehold.getSurveyStatus());
        this.reissueHouseholdContract(householdContract);




        ContractDataDto contractDataDto =new ContractDataDto();
        contractDataDto.setUsername(householdContract.getPartyA());
        contractDataDto.setContact(householdContract.getPeasantHouseholdPhone());
        contractDataDto.setIDCard(householdContract.getPeasantHouseholdCard());
        contractDataDto.setSubject(householdContract.getName());


        QueryWrapper<SealDictionary> queryWrapper=new QueryWrapper();
        queryWrapper.eq("amos_company_seq",householdContract.getRegionalCompaniesSeq());
        SealDictionary sealDictionary=sealDictionaryMapper.selectOne(queryWrapper);
        contractDataDto.setCategory(sealDictionary.getCategory());
        contractDataDto.setCompanyTenantName(sealDictionary.getCompanyTenantName());
        contractDataDto.setCompanyUsername(sealDictionary.getSealedUser());
        contractDataDto.setCompanyContact(sealDictionary.getSealedPhone());
        List<Long> listSealId= new ArrayList<>();
        listSealId.add(sealDictionary.getSealId());
        contractDataDto.setSealId(listSealId);

        QueryWrapper<ContractTemplate> qu=new QueryWrapper();
        qu.eq("template_id",householdContract.getContractTemplateId());
        ContractTemplate contractTemplate=contractTemplateMapper.selectOne(qu);
        contractDataDto.setEmplateId(householdContract.getContractTemplateId());
        contractDataDto.setCompanykeyword(contractTemplate.getCompanyKeyword());
        contractDataDto.setCompanyPage(contractTemplate.getCompanyPage());
        contractDataDto.setCompanyOffsetX(contractTemplate.getCompanyOffsetx());
        contractDataDto.setCompanyOffsetY(contractTemplate.getCompanyOffsety());
        contractDataDto.setCompanyKeywordIndex(contractTemplate.getCompanyKeywordIndex());
        contractDataDto.setPersonalkeyword(contractTemplate.getPersonalKeyword());
        contractDataDto.setPersonalPage(contractTemplate.getPersonalPage());
        contractDataDto.setPersonalOffsetX(contractTemplate.getPersonalOffsetx());
        contractDataDto.setPersonalOffsetY(contractTemplate.getPersonalOffsety());
        contractDataDto.setPersonalKeywordIndex(contractTemplate.getPersonalKeywordIndex());

         SimpleDateFormat myFmt2=new SimpleDateFormat("yyyy-MM-dd");
         Date now=new Date();
         String daty= myFmt2.format(now);

        List<TemplateParamDto> templateParam=new ArrayList<>();
        SimpleDateFormat sdfdate = new SimpleDateFormat("yyyy-MM-dd");
        templateParam.add(new TemplateParamDto("partyA",householdContract.getPartyA()!=null?householdContract.getPartyA():null));
        templateParam.add(new TemplateParamDto("peasantHouseholdPhone",householdContract.getPeasantHouseholdPhone()!=null?householdContract.getPeasantHouseholdPhone():null));
        templateParam.add(new TemplateParamDto("peasantHouseholdCard",householdContract.getPeasantHouseholdCard()!=null?householdContract.getPeasantHouseholdCard():null));
        templateParam.add(new TemplateParamDto("permanentAddressDetail",householdContract.getPermanentAddressName()!=null?householdContract.getPermanentAddressName()+householdContract.getPermanentAddressDetail():null));
        templateParam.add(new TemplateParamDto("projectAddressDetail",householdContract.getProjectAddressName()!=null?householdContract.getProjectAddressName()+householdContract.getProjectAddressDetail():null));
        templateParam.add(new TemplateParamDto("signingTime",daty));


         //合同动态填充字段
//        templateParam.add(new TemplateParamDto("rentFree",householdContract.getRentFree()!=null?sdfdate.format(householdContract.getRentFree()):null));
//        templateParam.add(new TemplateParamDto("rentCalculationDate",householdContract.getRentCalculationDate()!=null?sdfdate.format(householdContract.getRentCalculationDate()):null));
//        templateParam.add(new TemplateParamDto("leaseEndDate",householdContract.getLeaseEndDate()!=null?sdfdate.format(householdContract.getLeaseEndDate()):null));
//        templateParam.add(new TemplateParamDto("constructionScale",householdContract.getConstructionScale()!=null?String.valueOf(householdContract.getConstructionScale()):null));
//        templateParam.add(new TemplateParamDto("componentQuantityBlock",householdContract.getComponentQuantityBlock()!=null?String.valueOf(householdContract.getComponentQuantityBlock()):null));
//        templateParam.add(new TemplateParamDto("totalInvestment",householdContract.getTotalInvestment()!=null?String.valueOf(householdContract.getTotalInvestment()):null));
//        templateParam.add(new TemplateParamDto("componentPower",householdContract.getComponentPower()!=null?String.valueOf(householdContract.getComponentPower()):null));
//        templateParam.add(new TemplateParamDto("stationPower",householdContract.getStationPower()!=null?String.valueOf(householdContract.getStationPower()):null));

         List<ContractFillData> contractFillData= model.getContractFillData();
         if(contractFillData!=null&&!contractFillData.isEmpty()){
             for (ContractFillData contractFillDatum : contractFillData) {
                 templateParam.add(new TemplateParamDto(contractFillDatum.getField(),contractFillDatum.getValue()));
                 //保存动态值
                 contractFillDatum.setSequenceNbr(null);
                 contractFillDatum.setContractId(householdContract.getSequenceNbr());
                 contractFillDataMapper.insert(contractFillDatum);
             }
         }


        Long  contractLockId=qiyuesuoServiceImpl.addContract(contractDataDto , templateParam);
        householdContract.setContractLockId(contractLockId);
        householdContract.setInitiateStatus(HouseholdContractEnum.发起状态_已发起.getCode());
        householdContractMapper.updateById(householdContract);

         //生成填报任务
         ToDoTasks toDoTasks1=  new ToDoTasks (  TaskTypeStationEnum.合同填报.getCode(),  householdContract.getSequenceNbr(),   "用户"+householdContract.getPartyA()+"的合同填写",householdContract.getDealerCode());
         PeasantHousehold peasan=peasantHouseholdServiceImpl.getById(householdContract.getPeasantHouseholdId());
         toDoTasksServiceImpl.addToDoTasksByUserId(peasan.getAmosUserId(),toDoTasks1,"任务明细：合同发起成功");



         return householdContract;

    }

}