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.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.*;
import com.yeejoin.amos.boot.module.hygf.api.entity.*;
import com.yeejoin.amos.boot.module.hygf.api.mapper.ContractTemplateMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.HouseholdContractMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.SealDictionaryMapper;
import com.yeejoin.amos.boot.module.hygf.api.service.IHouseholdContractService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.Period;
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;
    /**
     * 列表查询 示例
     */
    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() );



        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, qw);

        return warningQuestionInfoIPage;
    }

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

    public void addHouseholdContract(HouseholdContract householdContract){

        householdContract.setContractNumber(this.getnum());//合同编号
        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.setStatus(HouseholdContractEnum.合同状态_未签署.getCode());
        householdContract.setSignStatus(HouseholdContractEnum.签字状态_未签字.getCode());
        householdContract.setStampStatus(HouseholdContractEnum.盖章状态_未盖章.getCode());
        householdContract.setInitiateStatus(HouseholdContractEnum.发起状态_未发起.getCode());
        householdContractMapper.insert(householdContract);
    }

    public String getnum() {
        SimpleDateFormat format = new SimpleDateFormat("YYYYMMddHHmmssSSS");
        Date date = new Date();
        String s = "HT"+format.format(date);
        return s;
    }


    @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("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("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("componentPower",householdContract.getComponentPower()!=null?String.valueOf(householdContract.getComponentPower()):null));
        templateParam.add(new TemplateParamDto("stationPower",householdContract.getStationPower()!=null?String.valueOf(householdContract.getStationPower()):null));
        templateParam.add(new TemplateParamDto("signingTime",daty));
        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){


        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("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("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("componentPower",householdContract.getComponentPower()!=null?String.valueOf(householdContract.getComponentPower()):null));
        templateParam.add(new TemplateParamDto("stationPower",householdContract.getStationPower()!=null?String.valueOf(householdContract.getStationPower()):null));
        templateParam.add(new TemplateParamDto("signingTime",daty));

        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;

    }

}