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

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.hygf.api.dto.RegionalCompaniesDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.UserUnitInformationDto;
import com.yeejoin.amos.boot.module.hygf.api.entity.RegionalCompanies;
import com.yeejoin.amos.boot.module.hygf.api.mapper.PersonnelBusinessMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.RegionalCompaniesMapper;
import com.yeejoin.amos.boot.module.hygf.biz.service.impl.RegionalCompaniesServiceImpl;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
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.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 
 *
 * @author system_generator
 * @date 2023-08-29
 */
@RestController
@Api(tags = "Api")
@RequestMapping(value = "/regional-companies")
public class RegionalCompaniesController extends BaseController {

    @Autowired
    RegionalCompaniesServiceImpl regionalCompaniesServiceImpl;

    @Autowired
    RegionalCompaniesMapper regionalCompaniesMapper;

    @Autowired
    PersonnelBusinessMapper personnelBusinessMapper;

    @Autowired
    RedisUtils redisUtil;
    private static final String regionRedis="app_region_redis";
    /**
     * 新增
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增", notes = "新增")
	public ResponseModel<RegionalCompaniesDto> save(@RequestBody RegionalCompaniesDto model) {
	    model = regionalCompaniesServiceImpl.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<RegionalCompanies> updateBySequenceNbrRegionalCompanies(@RequestBody RegionalCompanies model,@PathVariable(value = "sequenceNbr") Long sequenceNbr) {
	    model.setSequenceNbr(sequenceNbr);
        JSONArray regionName = getRegionName();
        List<RegionModel> list = JSONArray.parseArray(regionName.toJSONString(), RegionModel.class);
        String ConsigneeRegion="";
       List<Integer>  da=model.getConsigneeRegionCode();
       if(da!=null&&!da.isEmpty()){
        for (int i = 0; i < da.size(); i++) {
            for (RegionModel re : list) {
                if (re.getRegionCode().equals(Integer.valueOf(da.get(i)))) {
                    if(da.size()-1==i){
                        ConsigneeRegion = ConsigneeRegion + re.getRegionName();
                    }else{
                        ConsigneeRegion = ConsigneeRegion + re.getRegionName() + "-";
                    }
                    break;
                }
            }
        }

        model.setConsigneeRegion(ConsigneeRegion);
       }
        regionalCompaniesMapper.updateById(model);

	    return ResponseHelper.buildResponse(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(regionalCompaniesServiceImpl.removeById(sequenceNbr));
    }

    /**
     * 根据sequenceNbr查询
     *
	 * @param sequenceNbr  主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET",value = "根据sequenceNbr查询单个",  notes = "根据sequenceNbr查询单个")
	public ResponseModel<RegionalCompanies> selectOne(@PathVariable Long sequenceNbr) {
        RegionalCompanies regionalCompaniesData=regionalCompaniesMapper.selectById(sequenceNbr);
        RegionalCompanies regionalCompanies= regionalCompaniesMapper.selectByid(sequenceNbr);
        regionalCompaniesData.setRegionalAddress(regionalCompanies.getRegionalAddress());
	    return ResponseHelper.buildResponse(regionalCompaniesData);
	}

	/**
     * 列表分页查询
     *
     * @param current 当前页
     * @param current 每页大小
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/page")
	@ApiOperation(httpMethod = "GET",value = "分页查询",  notes = "分页查询")
	public ResponseModel<Page<RegionalCompaniesDto>> queryForPage(@RequestParam(value = "current") int current,@RequestParam
                    (value = "size") int size) {
	    Page<RegionalCompaniesDto> page = new Page<RegionalCompaniesDto>();
	    page.setCurrent(current);
	    page.setSize(size);
	    return ResponseHelper.buildResponse(regionalCompaniesServiceImpl.queryForRegionalCompaniesPage(page));
	}

	/**
	 * 列表全部数据查询
     *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET",value = "列表全部数据查询",   notes = "列表全部数据查询")
	@GetMapping(value = "/list")
	public ResponseModel<Page<RegionalCompanies> > selectForList(
	        @RequestParam(required=false) String regionalCompaniesName,
            @RequestParam(required=false) Long sequenceNbr,
            @RequestParam(value = "current") int current,
            @RequestParam(value = "size") int size
            ) {
        //获取用户所在经销商单位
        Long unitId=null;
        if(sequenceNbr==null){
            UserUnitInformationDto userUnitInformationDto=personnelBusinessMapper.getUserUnitInformationDto( getUserInfo().getUserId());
            unitId=userUnitInformationDto.getAmosDealerId();
        }
        PageHelper.startPage(current, size);
        List<RegionalCompanies> date=regionalCompaniesMapper.selectListData( regionalCompaniesName,unitId,sequenceNbr);

        PageInfo<RegionalCompanies> pages = new PageInfo(date);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<RegionalCompanies> pagenew = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<RegionalCompanies>();
        pagenew.setCurrent(current);
        pagenew.setTotal(pages.getTotal());
        pagenew.setSize(size);
        pagenew.setRecords(pages.getList());
	    return ResponseHelper.buildResponse(pagenew);
	}

    public JSONArray getRegionName() {
        JSONArray jsonArray = new JSONArray();
        if (redisUtil.hasKey(regionRedis)) {
            jsonArray = JSONArray.parseArray(redisUtil.get(regionRedis).toString());
        } else {
            Collection<RegionModel> regionChild = new ArrayList<>();
            RegionModel regionModel1 = new RegionModel();
            regionChild.add(regionModel1);
            FeignClientResult<Collection<RegionModel>> collectionFeignClientResult = Systemctl.regionClient.queryForTreeParent(610000L);
            Collection<RegionModel> result = collectionFeignClientResult.getResult();
            for (RegionModel regionModel : result) {
                if (null != regionModel && null != regionModel.getChildren()) {
                    for (RegionModel child : regionModel.getChildren()) {
                        if (null != child && null != child.getChildren()) {
                            for (RegionModel childChild : child.getChildren()) {
                                jsonArray.add(childChild);
                            }
                            child.setChildren(regionChild);
                            jsonArray.add(child);
                        }
                    }
                    regionModel.setChildren(regionChild);
                    jsonArray.add(regionModel);
                }
            }

            redisUtil.set(regionRedis, jsonArray);
        }
        return jsonArray;
    }
}
