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.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.UserUnitInformationDto;
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.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.Collection;
import java.util.Date;
import java.util.List;
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;
    /**
     * 新增
     *
     * @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());

        //生成填报任务
        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);

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

        }

            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());
        List<ToDoTasks> doTasks= toDoTasksMapper.selectList(wrapper);
        if(doTasks!=null){
            doTasks.forEach(e->{
                try {
                    e.setState("作废");
                    e.setIsDelete(true);
                    toDoTasksMapper.updateById(e);
                    emqKeeper.getMqttClient().publish("TASK_MESSAGE" ,JSON.toJSONString(e).getBytes(), 2 ,false);
                    UserMessage userMessage=  new UserMessage( e.getType(),  e.getBusinessId(),  e.getAmosUserId(),  new Date(),  e.getTaskName()+"已作废",  e.getAmosOrgCode());
                    userMessageMapper.insert(userMessage);
                    emqKeeper.getMqttClient().publish("MY_MESSAGE" , JSON.toJSONString(userMessage).getBytes(), 2 ,false);
                } catch (MqttException mqttException) {
                    mqttException.printStackTrace();
                }
            });
        }
    }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());
//    }

}
