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.module.hygf.api.Enum.HouseholdContractEnum;
import com.yeejoin.amos.boot.module.hygf.api.Enum.TaskTypeStationEnum;
import com.yeejoin.amos.boot.module.hygf.api.dto.HouseholdContractPageDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.UserUnitInformationDto;
import com.yeejoin.amos.boot.module.hygf.api.entity.HouseholdContract;
import com.yeejoin.amos.boot.module.hygf.api.entity.PeasantHousehold;
import com.yeejoin.amos.boot.module.hygf.api.entity.ToDoTasks;
import com.yeejoin.amos.boot.module.hygf.api.entity.UserMessage;
import com.yeejoin.amos.boot.module.hygf.api.mapper.HouseholdContractMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.PersonnelBusinessMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.ToDoTasksMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.UserMessageMapper;
import com.yeejoin.amos.boot.module.hygf.biz.service.impl.PeasantHouseholdServiceImpl;
import com.yeejoin.amos.boot.module.hygf.biz.service.impl.QiyuesuoServiceImpl;
import com.yeejoin.amos.boot.module.hygf.biz.service.impl.ToDoTasksServiceImpl;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RestController;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.yeejoin.amos.boot.module.hygf.biz.service.impl.HouseholdContractServiceImpl;
import org.typroject.tyboot.component.emq.EmqKeeper;
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 org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;


import org.springframework.web.bind.annotation.*;
import com.yeejoin.amos.boot.module.hygf.api.dto.HouseholdContractDto;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.foundation.enumeration.UserType;

/**
 * 
 *
 * @author system_generator
 * @date 2023-08-21
 */
@RestController
@Api(tags = "Api")
@RequestMapping(value = "/household-contract")
public class HouseholdContractController extends BaseController {

    @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;
    /**
     * 新增
     *
     * @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);

	    if(householdContract.getContractLockId()!=null&&householdContract.getContractUrl()==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 = "分页查询")
	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());

        //生成填报任务
        ToDoTasks toDoTasks1=  new ToDoTasks (  TaskTypeStationEnum.合同填报.getCode(),  householdContrac.getSequenceNbr(),  "用户"+householdContrac.getPartyA()+"合同盖章",null);
        toDoTasksServiceImpl.addToDoTasksByRole(engineering,toDoTasks1,"发起合同成功");


        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());

        LambdaQueryWrapper<ToDoTasks> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ToDoTasks::getType, TaskTypeStationEnum.合同填报.getCode());
        wrapper.eq(ToDoTasks::getState, "待办");
        wrapper.eq(ToDoTasks::getBusinessId, householdContrac.getSequenceNbr());
        ToDoTasks doTasks= toDoTasksMapper.selectOne(wrapper);
        if(doTasks!=null){
            doTasks.setState("已办");
            doTasks.setCompleteTime(new Date());
            toDoTasksMapper.updateById(doTasks);
            emqKeeper.getMqttClient().publish("TASK_MESSAGE" ,JSON.toJSONString(doTasks).getBytes(), 2 ,false);

            UserMessage userMessage=  new UserMessage( doTasks.getType(),  doTasks.getBusinessId(),  doTasks.getAmosUserId(),  new Date(),  doTasks.getTaskName()+"已完成",  doTasks.getAmosOrgCode());
            userMessageMapper.insert(userMessage);
            emqKeeper.getMqttClient().publish("MY_MESSAGE" , JSON.toJSONString(userMessage).getBytes(), 2 ,false);

        }
        }catch (Exception e){
            e.printStackTrace();
            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::getState, "待办");
        wrapper.eq(ToDoTasks::getBusinessId, householdContrac.getSequenceNbr());
        ToDoTasks doTasks= toDoTasksMapper.selectOne(wrapper);
        if(doTasks!=null){
            doTasks.setState("作废");
            toDoTasksMapper.updateById(doTasks);
            emqKeeper.getMqttClient().publish("TASK_MESSAGE" ,JSON.toJSONString(doTasks).getBytes(), 2 ,false);

            UserMessage userMessage=  new UserMessage( doTasks.getType(),  doTasks.getBusinessId(),  doTasks.getAmosUserId(),  new Date(),  doTasks.getTaskName()+"已作废",  doTasks.getAmosOrgCode());
            userMessageMapper.insert(userMessage);
            emqKeeper.getMqttClient().publish("MY_MESSAGE" , JSON.toJSONString(userMessage).getBytes(), 2 ,false);

        }
    }catch (Exception e){
        e.printStackTrace();
        throw new BadRequest("系统异常");
    }
        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= householdContractServiceImpl.reissueinitiateHouseholdContract(model);
        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);
    }
}
