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

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.module.hygf.api.config.UserLimits;
import com.yeejoin.amos.boot.module.hygf.api.dto.*;
import com.yeejoin.amos.boot.module.hygf.api.entity.DesignInformation;
import com.yeejoin.amos.boot.module.hygf.api.entity.HygfReplenishment;
import com.yeejoin.amos.boot.module.hygf.api.entity.PeasantHousehold;
import com.yeejoin.amos.boot.module.hygf.api.entity.PreparationMoney;
import com.yeejoin.amos.boot.module.hygf.api.mapper.*;
import com.yeejoin.amos.boot.module.hygf.api.util.CommonResponseNewUtil;
import com.yeejoin.amos.boot.module.hygf.biz.service.impl.DesignInformationServiceImpl;
import com.yeejoin.amos.boot.module.hygf.biz.service.impl.HygfReplenishmentServiceImpl;
import com.yeejoin.amos.boot.module.hygf.biz.service.impl.PreparationMoneyServiceImpl;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 发货单
 *
 * @author system_generator
 * @date 2023-08-17
 * @date 2023-08-17
 */
@RestController
@Api(tags = "发货单Api")
@RequestMapping(value = "/preparation-money")
public class PreparationMoneyController extends BaseController {

    @Autowired
    PreparationMoneyServiceImpl preparationMoneyServiceImpl;
    @Autowired
    PreparationMoneyMapper preparationMoneyMapper;
	@Autowired
	HouseholdContractMapper householdContractMapper;
	@Autowired
	PowerStationEngineeringInfoMapper powerStationEngineeringInfoMapper;
    @Autowired
    DesignInformationServiceImpl designInformationService;
    @Autowired
    PersonnelBusinessMapper personnelBusinessMapper;
    @Autowired
    DocumentStationMapper documentStationMapper;
    @Autowired
	HygfReplenishmentServiceImpl hygfReplenishmentService;
    /**
     * 新增发货单
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增发货单", notes = "新增发货单")
	@Transactional
	@UserLimits
	public ResponseModel<PreparationMoney> save( @RequestParam("isSubmit") String isSubmit, @RequestBody PreparationMoney model) {
        AgencyUserModel agencyUserModel= getUserInfo();
	   model = preparationMoneyServiceImpl.saveOrUpdateObjectNew(model,agencyUserModel, isSubmit);
		//   model = preparationMoneyServiceImpl.saveOrUpdateObject(model,agencyUserModel);
	    return ResponseHelper.buildResponse(model);
	}

	/**
     * 根据sequenceNbr更新
     *
     * @param sequenceNbr 主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PutMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新发货单", notes = "根据sequenceNbr更新发货单")
	public ResponseModel<PreparationMoneyDto> updateBySequenceNbrPreparationMoney(@RequestBody PreparationMoneyDto model,@PathVariable(value = "sequenceNbr") Long sequenceNbr) {
//	    model.setSequenceNbr(sequenceNbr);
//	    return ResponseHelper.buildResponse(preparationMoneyServiceImpl.saveOrUpdateObject(model));
        return null;
    }

	/**
     * 根据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(preparationMoneyServiceImpl.removeById(sequenceNbr));
    }

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

        PreparationMoney   preparationMoney =preparationMoneyServiceImpl.selectOnebyId(sequenceNbr);

	    return ResponseHelper.buildResponse(preparationMoney);
	}

	/**
     * 列表分页查询
     *
     * @param current 当前页
     * @param current 每页大小
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping (value = "/page")
	@ApiOperation(httpMethod = "post",value = "发货单分页查询",  notes = "发货单分页查询")
	@UserLimits
	public ResponseModel<IPage<PreparationMoney>> queryForPage(@RequestBody  PreparationPageDto preparationPageDto
    ) {


        //获取用户所在经销商单位
//        AgencyUserModel userInfo = getUserInfo();
//        UserUnitInformationDto userUnitInformationDto=personnelBusinessMapper.getUserUnitInformationDto(userInfo.getUserId());
//
//        if(userUnitInformationDto!=null&&userUnitInformationDto.getAmosDealerName()!=null){
//            preparationPageDto.setAmosUnitId(String.valueOf(userUnitInformationDto.getAmosUnitInfoId()));
//        }

	    return ResponseHelper.buildResponse(preparationMoneyServiceImpl.queryForPreparationMoneyPage(preparationPageDto));
	}

	/**
     * 作废
     * */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/zfPreparationMoney")
    @ApiOperation(httpMethod = "GET",value = "作废发货单",  notes = "作废发货单")
    public ResponseModel<Boolean> zfPreparationMoney(Long  sequenceNbr
    ) {
        AgencyUserModel agencyUserModel= getUserInfo();
        return ResponseHelper.buildResponse(preparationMoneyServiceImpl.zfPreparationMoney(sequenceNbr,agencyUserModel));
    }




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

	/**
	 * 发货价格中金额列联动接口
	 *
	 * -根据发货电站表单传入的场站ID 查询数据然后计算相应的金额
	 * 
	 * 
	 * @param  
	 * @return {@link  ResponseModel< List< PreparationMoneyDto>>}
	 * @author Provence
	 * @throws 
	 * @date 2023/8/17 18:23
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/getShippingPrice")
	@ApiOperation(httpMethod = "POST", value = "发货价格数据查询", notes = "发货价格数据查询")
	public ResponseModel<PreparationMoneyDto> getShippingPrice(@RequestBody List<PeasantHouseholdDto> dtos) {
		List<Long> powerHouseholdIds = dtos.stream().map(PeasantHouseholdDto::getSequenceNbr).collect(Collectors.toList());
		return ResponseHelper.buildResponse(preparationMoneyServiceImpl.caculateShippingPriceByPowerHouseHoldIds(powerHouseholdIds));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/detail")
	@ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个发货单详情", notes = "根据sequenceNbr查询单个发货单详情")
	public ResponseModel<PreparationMoneyDto> getObject(@RequestParam Long sequenceNbr) {
		//return ResponseHelper.buildResponse(preparationMoneyServiceImpl.getObjectBySequenceNbr(sequenceNbr));
        return null;
	}


	/**
	 * 根据sequenceNbr更新
	 *
	 * @param sequenceNbr 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/updatePreparationMoneyStatus")
	@ApiOperation(httpMethod = "POST", value = "根据sequenceNbr更新发货单", notes = "根据sequenceNbr更新发货单")
	public ResponseModel<Boolean> updateBySequenceNbr(@RequestParam(value = "sequenceNbr") Long sequenceNbr, @RequestParam(value = "operationType") String operationType) {
		return ResponseHelper.buildResponse(preparationMoneyServiceImpl.updatePreparationMoneyStatus(sequenceNbr, operationType));
	}

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "列表全部数据查询",   notes = "列表全部数据查询")
    @GetMapping(value = "/getPeasantHouseholdData")
    public ResponseModel<  Page<PeasantHousehold>  > getPeasantHouseholdData(
            @RequestParam(required=false) Long sequenceNbr,
            @RequestParam(required=false) String ownersName,
			@RequestParam(required=false) String projectAddress
    ) {
        List<PeasantHousehold>  list=preparationMoneyMapper.getPeasantHouseholdData(sequenceNbr,ownersName, projectAddress);

		if(list != null && list.size() > 0) {
			list.forEach(e -> {
				if(e.getPeasantHouseholdNo() != null) {
					e.setScale(householdContractMapper.getHygfCommercialScale(e.getPeasantHouseholdNo()));
					e.setRealScale(powerStationEngineeringInfoMapper.getRealScaleByPeasantHouseholdNo(e.getPeasantHouseholdNo()));
				}
			});

		}


       Page<PeasantHousehold> pagenew = new Page<>();
        pagenew.setRecords(list);
        pagenew.setTotal(list.size());
        return ResponseHelper.buildResponse(pagenew);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "bom",   notes = "bom")
    @GetMapping(value = "/getDesignInformationData")
    public ResponseModel<  DesignInformation > getDesignInformationData(
            @RequestParam(required=false) Long sequenceNbr
    ) {
        QueryWrapper<DesignInformation> designInformationQueryWrapper = new QueryWrapper<>();
        designInformationQueryWrapper.eq("peasant_household_id", sequenceNbr);
        DesignInformation designInformation = designInformationService.getBaseMapper().selectOne(designInformationQueryWrapper);
        return ResponseHelper.buildResponse(designInformation);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/selectOnePreparationMoney")
    @ApiOperation(httpMethod = "GET",value = "根据sequenceNbr查询单个发货单",  notes = "根据sequenceNbr查询单个发货单")
    public ResponseModel<Map<String,Object>> selectOnePreparationMoney( String sequenceNbr) {

        return ResponseHelper.buildResponse(preparationMoneyServiceImpl.selectOnePreparationMoney(sequenceNbr));
    }


	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/uploadVoucher")
	@ApiOperation(httpMethod = "POST",value = "上传收获凭证",  notes = "上传收获凭证")
	@Transactional
	public ResponseModel uploadVoucher(@RequestParam(value = "instanceId",required = false) String instanceId,@RequestBody PreparationMoney model, String isSubmit) {

		preparationMoneyServiceImpl.uploadVoucher(model,instanceId,isSubmit);
		return CommonResponseNewUtil.success();
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/excuteFlow")
	@ApiOperation(httpMethod = "POST",value = "收货审核",  notes = "收货审核")
	@Transactional
	public ResponseModel excuteFlow(@RequestParam(value = "instanceId" ,required = false) String instanceId,
									@RequestParam(value = "sequenceNbr") Long sequenceNbr,@RequestBody Map<String, Object> kv) {

		preparationMoneyServiceImpl.excuteFlow(instanceId,kv,sequenceNbr);
		return CommonResponseNewUtil.success();
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/replenishmentSubmit")
	@ApiOperation(httpMethod = "POST",value = "补货申请",  notes = "补货申请")
	@Transactional
	public ResponseModel replenishmentSubmit( @RequestBody HygfReplenishment hygfReplenishment) {
//		HygfReplenishment hygfReplenishment1 = new HygfReplenishment();
//		BeanUtils.copyProperties(hygfReplenishment,hygfReplenishment1);
//		hygfReplenishment1.setFile(JSON.toJSONString(hygfReplenishment.getFile()));
		hygfReplenishmentService.save(hygfReplenishment);
		preparationMoneyServiceImpl.replenishmentSubmit(hygfReplenishment.getPreparationMoneyId());
		return CommonResponseNewUtil.success();
	}



	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PutMapping(value = "/replenishmentRollback")
	@ApiOperation(httpMethod = "PUT",value = "补货撤回",  notes = "补货撤回")

	public ResponseModel  replenishmentRollback(@RequestParam(value = "sequenceNbr") Long sequenceNbr) {
		preparationMoneyServiceImpl.replenishmentRollback(sequenceNbr);
		return CommonResponseNewUtil.success();
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/replenishmentAudit")
	@ApiOperation(httpMethod = "POST",value = "补货审核",  notes = "补货审核")
	@Transactional
	public ResponseModel  replenishmentAudit(@RequestParam(value = "sequenceNbr") Long sequenceNbr,@RequestBody Map<String,Object> kv) {
		preparationMoneyServiceImpl.replenishmentAudit(sequenceNbr,kv);
		return CommonResponseNewUtil.success();
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/submitOrder")
	@ApiOperation(httpMethod = "POST",value = "补货审核",  notes = "补货审核")
	@Transactional
	public ResponseModel  submitOrder(@RequestParam(value = "instanceId") String instanceId,
									  @RequestParam(value = "isSubmit") String isSubmit,
									  @RequestBody PreparationMoney model) {
		preparationMoneyServiceImpl.submitOrder( model,  instanceId,  isSubmit);
		return CommonResponseNewUtil.success();
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/preparationStation")
	@ApiOperation(httpMethod = "GET",value = "发货电站",  notes = "发货电站")
	@UserLimits
	public ResponseModel<IPage<Map<String,Object>>> preparationStation(
			@RequestParam(value = "current") Integer current,
			@RequestParam(value = "size") Integer size,
			@RequestParam(value = "ownersName",required = false) String ownersName,
			@RequestParam(value = "regionalcompaniesSeq",required = false) String regionalcompaniesSeq,
			@RequestParam(value = "developerId",required = false) String developerId,
			@RequestParam(value = "state",required = false) String state,
			@RequestParam(value = "preparationMoneyState") String preparationMoneyState,
			@RequestParam(value = "province",required = false) String province,
			@RequestParam(value = "projectAddress",required = false) String projectAddress,
			@RequestParam(value = "startTime",required = false) String startTime,
			@RequestParam(value = "endTime",required = false) String endTime,
			@RequestParam(value = "routhPathId",required = false) String routhPathId){

		return ResponseHelper.buildResponse(preparationMoneyServiceImpl.preparationStation(current,size,preparationMoneyState,ownersName,regionalcompaniesSeq,developerId,state,province, projectAddress, startTime, endTime,routhPathId)) ;
	}


	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getFromInfo")
	@ApiOperation(httpMethod = "GET",value = "获取发货电站及区域，经销商公司",  notes = "获取发货电站及区域")
	public ResponseModel<PreparationMoney> getFromInfo(
			@RequestParam(value = "ids") String ids){
		List<String> list = Arrays.asList(ids.split(","));
		AgencyUserModel userInfo = getUserInfo();
		PreparationMoney fromInfo = preparationMoneyServiceImpl.getFromInfo(list);
		fromInfo.setOrderUser(userInfo.getRealName());
		return ResponseHelper.buildResponse(fromInfo) ;
	}
}
