package com.yeejoin.amos.boot.module.hygf.biz.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.module.hygf.api.Enum.ArrivalStateeEnum;
import com.yeejoin.amos.boot.module.hygf.api.Enum.HouseholdContractEnum;
import com.yeejoin.amos.boot.module.hygf.api.Enum.HygfRouthTypeEnum;
import com.yeejoin.amos.boot.module.hygf.api.Enum.TaskTypeStationEnum;
import com.yeejoin.amos.boot.module.hygf.api.config.UserLimits;
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.PeasantHouseholdDto;
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.biz.service.impl.*;
import com.yeejoin.amos.boot.module.hygf.biz.vo.RouthPathVO;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.*;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 
 *
 * @author system_generator
 * @date 2023-08-21
 */
@RestController
@Api(tags = "农户合同Api")
@RequestMapping(value = "/household-contract")
@Slf4j
public class HouseholdContractController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(HouseholdContractController.class);
    @Autowired
    HouseholdContractServiceImpl householdContractServiceImpl;
    @Value("${regionalCompanies.company.seq}")
    private Long regionalCompanies;
    @Autowired
    QiyuesuoServiceImpl qiyuesuoServiceImpl;

    @Autowired
    ToDoTasksServiceImpl toDoTasksServiceImpl;

    @Autowired
    PeasantHouseholdServiceImpl peasantHouseholdServiceImpl;
    @Autowired
    protected EmqKeeper emqKeeper;
    @Value("${dealer.engineering}")
    private String engineering;
    @Autowired
    PersonnelBusinessMapper personnelBusinessMapper;
    @Autowired
    ToDoTasksMapper toDoTasksMapper;
    @Autowired
    UserMessageMapper userMessageMapper;

    @Autowired
    ContractFillDataMapper contractFillDataMapper;
    @Autowired
    PowerStationServiceImpl powerStationServiceImpl;
    @Autowired
    HouseholdContractMapper householdContractMapper;
    @Autowired
    HygfContractCallRecordMapper hygfContractCallRecordMapper;
    /**
     * 新增
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增", notes = "新增")
	public ResponseModel<HouseholdContractDto> save(@RequestBody HouseholdContractDto model) {
	    model = householdContractServiceImpl.createWithModel(model);
	    return ResponseHelper.buildResponse(model);
	}

	/**
     * 根据sequenceNbr更新
     *
     * @param sequenceNbr 主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PutMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新", notes = "根据sequenceNbr更新")
	public ResponseModel<HouseholdContractDto> updateBySequenceNbrHouseholdContract(@RequestBody HouseholdContractDto model,@PathVariable(value = "sequenceNbr") Long sequenceNbr) {
	    model.setSequenceNbr(sequenceNbr);
	    return ResponseHelper.buildResponse(householdContractServiceImpl.updateWithModel(model));
	}

	/**
     * 根据sequenceNbr删除
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除", notes = "根据sequenceNbr删除")
    public ResponseModel<Boolean> deleteBySequenceNbr(HttpServletRequest request, @PathVariable(value = "sequenceNbr") Long sequenceNbr){
        return ResponseHelper.buildResponse(householdContractServiceImpl.removeById(sequenceNbr));
    }

    /**
     * 根据sequenceNbr查询
     *
	 * @param sequenceNbr  主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET",value = "根据sequenceNbr查询单个",  notes = "根据sequenceNbr查询单个")
	public ResponseModel<HouseholdContract> selectOne(@PathVariable Long sequenceNbr) {

        HouseholdContract householdContract = householdContractServiceImpl.getById(sequenceNbr);
        //合同填充字段
        LambdaQueryWrapper<ContractFillData> up=new LambdaQueryWrapper<>();
        up.eq(ContractFillData::getContractId,sequenceNbr);
        List<ContractFillData>   da=contractFillDataMapper.selectList(up);

        householdContract.setContractFillData(da);

	    if(householdContract.getContractLockId()!=null){
         String url=   qiyuesuoServiceImpl.getdownloadUrl(householdContract.getContractLockId());
         householdContract.setContractUrl(url);
//            householdContractServiceImpl.updateById(householdContract);
        }
	    return ResponseHelper.buildResponse(householdContract);
	}

	/**
     * 列表分页查询
     *
     * @param current 当前页
     * @param current 每页大小
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/page")
	@ApiOperation(httpMethod = "GET",value = "分页查询",  notes = "分页查询")
    @UserLimits
	public ResponseModel<IPage< HouseholdContract > > queryForPage(HouseholdContractPageDto dto) {


//        //获取用户所在经销商单位
//        UserUnitInformationDto userUnitInformationDto=personnelBusinessMapper.getUserUnitInformationDto(getUserId());
//
//         if(userUnitInformationDto!=null&&userUnitInformationDto.getAmosDealerId()!=null){
//             dto.setDealerId(userUnitInformationDto.getAmosDealerId());
//         }

        return ResponseHelper.buildResponse(householdContractServiceImpl.queryForPreparationMoneyPage(dto));
	}

	/**
	 * 列表全部数据查询
     *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET",value = "列表全部数据查询",   notes = "列表全部数据查询")
	@GetMapping(value = "/list")
	public ResponseModel<List<HouseholdContractDto>> selectForList() {
	    return ResponseHelper.buildResponse(householdContractServiceImpl.queryForHouseholdContractList());
	}


    //去签署
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "POST", value = "根据sequenceNbr发起", notes = "根据sequenceNbr发起")
    public ResponseModel<HouseholdContractDto> qsBySequenceNbrHouseholdContract(@RequestBody HouseholdContractDto model,@PathVariable(value = "sequenceNbr") Long sequenceNbr) {

        return ResponseHelper.buildResponse(householdContractServiceImpl.updateWithModel(model));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping (value = "/signing/{sequenceNbr}")
    @ApiOperation(httpMethod = "POST", value = "签字", notes = "签字")
    public ResponseModel<Boolean> signing(@PathVariable(value = "sequenceNbr") Long sequenceNbr) {

        HouseholdContract householdContrac=  householdContractServiceImpl.getById(sequenceNbr);
        householdContrac.setSignStatus(HouseholdContractEnum.签字状态_已签字.getCode());
        householdContrac.setStatus(HouseholdContractEnum.合同状态_农户已签署.getCode());

        //生成填报任务
//        RouthPathVO routhPathVO = new RouthPathVO();
//        routhPathVO.setRouthPathId(String.valueOf(householdContrac.getSequenceNbr()));
//        String routhPath = toDoTasksServiceImpl.getRouthPath(TaskTypeStationEnum.合同.getCode(), HygfRouthTypeEnum.HYGF_HTGZ.getCode(), routhPathVO);
//        String wxRouthPath = toDoTasksServiceImpl.getWxRouthPath(TaskTypeStationEnum.合同.getCode(), HygfRouthTypeEnum.HYGF_HTGZ.getCode(), routhPathVO);
//        ToDoTasks toDoTasks = new ToDoTasks(TaskTypeStationEnum.合同.getCode(), householdContrac.getSequenceNbr(), householdContrac.getPartyA()+"待合同盖章", householdContrac.getRegionalCompaniesCode(),routhPath,wxRouthPath);
//        List<String> todoUserIds = toDoTasksServiceImpl.getTodoUserIds(householdContrac.getRegionalCompaniesCode(), engineering);
//        toDoTasksServiceImpl.completeAndAddToDoTask(todoUserIds, toDoTasks,"");

        return ResponseHelper.buildResponse(householdContractServiceImpl.updateById(householdContrac));
    }
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping (value = "/stamp/{sequenceNbr}")
    @ApiOperation(httpMethod = "POST", value = "盖章", notes = "盖章")
    public ResponseModel<Boolean> stamp(@PathVariable(value = "sequenceNbr") Long sequenceNbr) {


        return ResponseHelper.buildResponse(this.stampdata(sequenceNbr));
    }

    @Transactional
    public boolean stampdata(Long sequenceNbr){
        HouseholdContract householdContrac=null;
        try {
        householdContrac=  householdContractServiceImpl.getById(sequenceNbr);
        householdContrac.setStampStatus(HouseholdContractEnum.盖章状态_已盖章.getCode());
        householdContrac.setSigningTime(new Date());
        householdContrac.setStatus(HouseholdContractEnum.合同状态_双方已签署.getCode());
        householdContrac.setSealedUser(getUserInfo().getRealName());

        PeasantHousehold peasantHousehold = peasantHouseholdServiceImpl.getDataByState(householdContrac.getPeasantHouseholdId());
        System.out.println("开始更新农户发货状态"+householdContrac.getPeasantHouseholdId());
        if (peasantHousehold != null){
            System.out.println("开始更新农户发货状态"+householdContrac.getPeasantHouseholdId());
                peasantHousehold.setPreparationMoneyState(ArrivalStateeEnum.待发货.getCode());
                peasantHouseholdServiceImpl.getBaseMapper().updateById(peasantHousehold);
            System.out.println("更新成功"+householdContrac.getPeasantHouseholdId());
        }
        ToDoTasks toDoTasks = new ToDoTasks(TaskTypeStationEnum.合同.getCode(), householdContrac.getSequenceNbr());
        toDoTasksServiceImpl.completeToDoTasks(toDoTasks,"");

        }catch (Exception e){
            HygfContractCallRecord hygfContractCallRecord = new HygfContractCallRecord();
            hygfContractCallRecord.setContractId(sequenceNbr.toString());
            hygfContractCallRecord.setData(JSON.toJSONString(e.getStackTrace()));
            hygfContractCallRecordMapper.insert(hygfContractCallRecord);
            throw new BadRequest("系统异常");
        }
        return householdContractServiceImpl.updateById(householdContrac);

    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping (value = "/cancel/{sequenceNbr}")
    @ApiOperation(httpMethod = "POST", value = "作废", notes = "作废")
    public ResponseModel<Boolean> cancel(@PathVariable(value = "sequenceNbr") Long sequenceNbr) {
        return ResponseHelper.buildResponse(this.canceldata(sequenceNbr));
    }



    @Transactional
    public boolean canceldata(Long sequenceNbr){
        HouseholdContract householdContrac=null;
        try {
        householdContrac=  householdContractServiceImpl.getById(sequenceNbr);
        householdContrac.setStatus(HouseholdContractEnum.合同状态_已作废.getCode());
        //如果作废删除此合同之前的待办并产生新的待办
        LambdaQueryWrapper<ToDoTasks> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ToDoTasks::getType, TaskTypeStationEnum.合同.getCode());
        wrapper.eq(ToDoTasks::getBusinessId, householdContrac.getSequenceNbr());
        toDoTasksMapper.delete(wrapper);
        //产生新的的待办
        PeasantHouseholdDto peasantHouseholdDto = peasantHouseholdServiceImpl.queryBySeq(householdContrac.getPeasantHouseholdId());
        if(Objects.nonNull(peasantHouseholdDto)){
            List<String> todoUserIds = new ArrayList<>();
            todoUserIds.add(peasantHouseholdDto.getDeveloperUserId());
            RouthPathVO routhPathVO1 = new RouthPathVO();
            routhPathVO1.setRouthPathId(String.valueOf(householdContrac.getSequenceNbr()));
            String routhPath1 = toDoTasksServiceImpl.getRouthPath(TaskTypeStationEnum.合同.getCode(), HygfRouthTypeEnum.HYGF_HTFQ.getCode(), routhPathVO1);
            String wxRouthPath1 = toDoTasksServiceImpl.getWxRouthPath(TaskTypeStationEnum.合同.getCode(), HygfRouthTypeEnum.HYGF_HTFQ.getCode(), routhPathVO1);
            ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.合同.getCode(),  HygfRouthTypeEnum.HYGF_HTCXFQ.getBusiness(),  householdContrac.getPartyA()+"待合同重新发起",householdContrac.getDealerCode(),routhPath1,wxRouthPath1);
            toDoTasksServiceImpl.addToDoTasksByUserIds(todoUserIds,toDoTasks1);
        }
    }catch (Exception e){
        e.printStackTrace();
        throw new BadRequest(e.getMessage());
    }
        return householdContractServiceImpl.updateById(householdContrac);

    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @GetMapping(value = "/sealId/tree")
    @ApiOperation(httpMethod = "GET", value = "印章", notes = "印章")
    public ResponseModel<List<CompanyModel>> sealId() {
        FeignClientResult<Collection<CompanyModel>> feignClientResult=  Privilege.companyClient.querySubAgencyTree(regionalCompanies);
        List<CompanyModel>  companyModel = (List<CompanyModel>)feignClientResult.getResult();
        companyModel=companyModel.stream().filter(compan->compan.getCompanyCode()!=null&&!"".equals(compan.getCompanyCode())).collect(Collectors.toList());
        return ResponseHelper.buildResponse(companyModel);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @PostMapping (value = "/reissue")
    @ApiOperation(httpMethod = "POST", value = "重新发起", notes = "重新发起")
    public ResponseModel<HouseholdContract> reissue(@RequestBody HouseholdContract model ) {
        HouseholdContract   householdContract = new HouseholdContract();
       try {
           householdContract = householdContractServiceImpl.reissueinitiateHouseholdContract(model);
       }catch (Exception e){
           log.error("重新发起合同错误, 入参: {}, error:", JSON.toJSONString(model), e);
           throw new BadRequest(e.getMessage());
       }
        return ResponseHelper.buildResponse(householdContract);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getUrl/{contractLockId}")
    @ApiOperation(httpMethod = "GET",value = "",  notes = "根据sequenceNbr查询单个")
    public ResponseModel<String> getUrl(@PathVariable Long contractLockId) {
        String url = qiyuesuoServiceImpl.getUrl(contractLockId);
        return ResponseHelper.buildResponse(url);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getdownloadUrl")
    @ApiOperation(httpMethod = "GET",value = "根据sequenceNbr查询单个",  notes = "根据sequenceNbr查询单个")
    public ResponseModel<HouseholdContract> getdownloadUrl(Long sequenceNbr) {

        PowerStation pd= powerStationServiceImpl.getById(sequenceNbr);

        LambdaQueryWrapper<HouseholdContract> qu=new LambdaQueryWrapper<>();
        qu.ne(HouseholdContract::getStatus,"已作废");
        qu.eq(HouseholdContract::getIsDelete,false);
        qu.eq(HouseholdContract::getPeasantHouseholdId,pd.getPeasantHouseholdId());

        HouseholdContract householdContract = householdContractMapper.selectOne(qu);

        if(householdContract.getContractLockId()!=null){
            String url=   qiyuesuoServiceImpl.getdownloadUrl(householdContract.getContractLockId());
            householdContract.setContractUrl(url);
        }
        return ResponseHelper.buildResponse(householdContract);
    }


//    public static void main(String[] args) {
//        String ChineseStr = "北京";
//        StringBuilder sb = new StringBuilder();
//        for (char c : ChineseStr.toCharArray()) {
//            String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(c);
//            if (pinyin != null) {
//                sb.append(pinyin[0].charAt(0));
//            } else {
//                sb.append(c);
//            }
//        }
//        System.out.println(sb.toString().toUpperCase());
//    }

}
