package com.yeejoin.equipmanage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.equipmanage.common.dto.SocialPowerImportParam;
import com.yeejoin.equipmanage.common.entity.SocialPower;
import com.yeejoin.equipmanage.common.entity.UploadFile;
import com.yeejoin.equipmanage.common.entity.dto.FireResourceStatsDTO;
import com.yeejoin.equipmanage.common.utils.CommonRequest;
import com.yeejoin.equipmanage.common.utils.CommonResponseUtil;
import com.yeejoin.equipmanage.common.utils.FileItem;
import com.yeejoin.equipmanage.common.utils.StringUtil;
import com.yeejoin.equipmanage.service.ISocialPowerService;
import com.yeejoin.equipmanage.service.IUploadFileService;
import com.yeejoin.equipmanage.utils.FileHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
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.HttpServletResponse;
import java.util.*;

/**
 * 社会力量表
 *
 * @author system_generator
 * @date 2022-02-18
 */
@RestController
@Api(tags = "社会力量表Api")
@RequestMapping(value = "/social/power", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class SocialPowerController extends AbstractBaseController {

    @Autowired
	ISocialPowerService socialPowerService;

	@Autowired
	IUploadFileService iUploadFileService;

    /**
     * 新增
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增社会力量表", notes = "新增社会力量表")
	public ResponseModel<SocialPower> save(@RequestBody Map<String, SocialPower> model) {
		ReginParams reginParams = getSelectedOrgInfo();
		String bizOrgCode = reginParams.getPersonIdentity().getBizOrgCode();
		String bizOrgName = reginParams.getPersonIdentity().getCompanyName();
		SocialPower socialPower = model.get("socialPowerAdd");
		socialPower.setBizOrgCode(bizOrgCode);
		socialPower.setBizOrgName(bizOrgName);
		boolean bool = socialPowerService.save(socialPower);
		if (!CollectionUtils.isEmpty(socialPower.getAttachFiles())) {
			if (0 < socialPower.getAttachFiles().size() && bool) {
				iUploadFileService.saveBatch(convertAttachFiles(socialPower.getAttachFiles(), socialPower.getId()));
			}
		}
	    return ResponseHelper.buildResponse(socialPower);
	}

	/**
     * 根据id更新
     *
     * @param
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@PutMapping(value = "/update")
	@ApiOperation(httpMethod = "PUT", value = "根据id更新社会力量", notes = "根据id更新社会力量")
	public ResponseModel<SocialPower> updateByIdWlSocialPower(@RequestBody SocialPower model) {
		model.setContactUser(StringUtil.isNotEmpty(model.getContactUser()) ? model.getContactUser() : null);
		model.setContactPhone(StringUtil.isNotEmpty(model.getContactPhone()) ? model.getContactPhone() : null);
		model.setArrivalDistance(StringUtil.isNotEmpty(model.getArrivalDistance()) ? model.getArrivalDistance() : null);
		model.setArrivalTime(StringUtil.isNotEmpty(model.getArrivalTime()) ? model.getArrivalTime() : null);
		model.setRemark(StringUtil.isNotEmpty(model.getRemark()) ? model.getRemark() : null);
		model.setAttachFiles(CollectionUtils.isEmpty(model.getAttachFiles()) ? null : model.getAttachFiles());
		if (CollectionUtils.isEmpty(model.getAttachFiles())) {
			Map<String, Object> map = new HashMap<>();
			map.put("object_id", model.getId());
			iUploadFileService.removeByMap(map);
		}
		boolean bool = socialPowerService.updateById(model);
		if (!CollectionUtils.isEmpty(model.getAttachFiles())) {
			if (0 < model.getAttachFiles().size() && bool) {
				Map<String, Object> map = new HashMap<>();
				map.put("object_id", model.getId());
				iUploadFileService.removeByMap(map);
				iUploadFileService.saveBatch(convertAttachFiles(model.getAttachFiles(), model.getId()));
			}
		}
	    return ResponseHelper.buildResponse(model);
	}

	private List<UploadFile> convertAttachFiles(List<FileItem> items, Long objectId) {
		List<UploadFile> files = new ArrayList<>();
		items.forEach(x -> {
			UploadFile file = new UploadFile();
			BeanUtils.copyProperties(x, file);
			file.setObjectId(objectId);
			file.setObjectType("SocialPower");
			file.setOrgCode(x.getUid());
			file.setDepartmentOrgcode(x.getStatus());
			files.add(file);
		});
		return files;
	}

	/**
     * 根据id删除
     *
     * @param ids 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @DeleteMapping(value = "/batchDelete")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除社会力量", notes = "根据id删除社会力量")
    public ResponseModel<Boolean> deleteOneById(@RequestParam("ids") Long[] ids){
		if (0 < ids.length) {
			List<Long> list = Arrays.asList(ids);
			return ResponseHelper.buildResponse(socialPowerService.removeByIds(list));
		} else {
			return CommonResponseUtil.failure("请选择要删除的行！");
		}
    }

    /**
     * 根据id查询
     *
	 * @param id  主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@GetMapping(value = "/detail")
	@ApiOperation(httpMethod = "GET",value = "根据id查询单个社会力量",  notes = "根据id查询单个社会力量")
	public ResponseModel<SocialPower> selectOne(@RequestParam Long socialId) {
		SocialPower socialPower = socialPowerService.getById(socialId);
		QueryWrapper<UploadFile> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("object_id", socialId);
		List<UploadFile> uploadFiles = iUploadFileService.list(queryWrapper);
		if (0 < uploadFiles.size()) {
			List<FileItem> items = new ArrayList<>();
			uploadFiles.forEach(x -> {
				FileItem item = new FileItem();
				BeanUtils.copyProperties(x, item);
				item.setStatus(x.getDepartmentOrgcode());
				item.setUid(x.getOrgCode());
				items.add(item);
			});
			socialPower.setAttachFiles(items);
		}
	    return ResponseHelper.buildResponse(socialPower);
	}

	/**
	 * 列表全部数据查询
     *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "社会力量列表全部数据查询",   notes = "社会力量列表全部数据查询")
	@GetMapping(value = "/list")
	public ResponseModel<List<SocialPower>> selectForList() {
		ReginParams reginParams = getSelectedOrgInfo();
		String bizOrgCode = reginParams.getPersonIdentity().getBizOrgCode();
		return ResponseHelper.buildResponse(socialPowerService.query().eq("biz_org_code", bizOrgCode).list());
	}

	/**
	 * 列表全部数据查询
     *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "社会力量列表全部数据查询",   notes = "社会力量列表全部数据查询")
	@GetMapping(value = "/page")
	public Page<SocialPower> selectForList(Page page,
										  @RequestParam(value = "companyName",required = false) String companyName,
										  @RequestParam(value = "contactUser",required = false) String contactUser,
										   @RequestParam(value = "remark",required = false) String remark,
										   @RequestParam(value = "bizOrgCode", required = false) String bizOrgCode,
										   @RequestParam(value = "powerStatus", required = false) String powerStatus) {
		if (StringUtils.isEmpty(bizOrgCode)) {
			ReginParams reginParams = getSelectedOrgInfo();
			bizOrgCode = reginParams.getPersonIdentity().getBizOrgCode();
		}
		SocialPower dto = new SocialPower();
		dto.setBizOrgCode(bizOrgCode);
		dto.setCompanyName(companyName);
		dto.setContactUser(contactUser);
		dto.setRemark(remark);
		dto.setPowerStatus(powerStatus);
		return socialPowerService.listPage(page, dto);
	}

	/**
	 * 模板导出
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "模板导出",   notes = "模板导出")
	@GetMapping(value = "/export")
	public ResponseModel exportTemplate(HttpServletResponse response) {
		String fileName = "社会力量模板.xls"; //模板名称
		String[] handers = {"单位名称","所在地","联系人","联系电话","到站距离","到站时间","备注信息"}; //列标题
		List<String[]> downData = new ArrayList();
		String [] downRows = {}; //下拉的列序号数组(序号从0开始)
		try {
			FileHelper.createExcelTemplate(fileName, handers, downData, downRows, response);
		} catch (Exception e) {
			CommonResponseUtil.failure(e.getMessage());
		}
		return CommonResponseUtil.success();
	}

	/**
	 * 导入
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@PostMapping(value = "/import")
	@ApiOperation(httpMethod = "POST", value = "模板填充数据导入", notes = "模板填充数据导入")
	public ResponseModel importSocialPower(@ApiParam(value="导入数据文件", required=true) MultipartFile file) {
		String fileName = file.getOriginalFilename();
		ReginParams reginParams = getSelectedOrgInfo();
		if (!fileName.endsWith(".xls")) {
			return CommonResponseUtil.failure("文件格式错误");
		}
		try {
			List<SocialPowerImportParam> list = FileHelper.importExcel(file, 0, 1, SocialPowerImportParam.class);
			if (0 < list.size()) {
				List<SocialPower> powers = new ArrayList<>();
				for (SocialPowerImportParam dto : list) {
					SocialPower socialPower = new SocialPower();
					BeanUtils.copyProperties(dto, socialPower);
					if (StringUtil.isNotEmpty(dto.getCompanyName())) {
						socialPower.setCompanyName(dto.getCompanyName());
					} else {
						return CommonResponseUtil.failure("请补充单位名称信息！");
					}

					if (StringUtil.isNotEmpty(dto.getLocation())) {
						socialPower.setLocation(dto.getLocation());
					} else {
						return CommonResponseUtil.failure("请补充所在地信息！");
					}
					socialPower.setBizOrgName(reginParams.getCompany().getCompanyName());
					socialPower.setBizOrgCode(reginParams.getPersonIdentity().getBizOrgCode());
					powers.add(socialPower);
				}
				socialPowerService.saveOrUpdateBatch(powers);
			}
			return CommonResponseUtil.success();
		} catch (Exception e) {
			e.printStackTrace();
			return CommonResponseUtil.failure(e.getLocalizedMessage());
		}
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(value = "数据导出", notes = "数据导出")
	@PostMapping(value = "/exportListPointNew", produces = "application/json;charset=UTF-8")
	public ResponseModel exportListPointNew(@ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests,
											HttpServletResponse response) {

		ReginParams reginParams = getSelectedOrgInfo();
		String bizOrgCode = reginParams.getPersonIdentity().getBizOrgCode();
		if (ObjectUtils.isEmpty(reginParams)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {

			Map<String, Object> map = new HashMap<>();
			map.put("biz_org_code", bizOrgCode);
			List<SocialPower> socials = (List<SocialPower>) socialPowerService.listByMap(map);
			List<SocialPowerImportParam> socialList = new ArrayList<>();
			if (!CollectionUtils.isEmpty(socials)) {
				socials.forEach(x -> {
					SocialPowerImportParam s = new SocialPowerImportParam();
					BeanUtils.copyProperties(x, s);
					socialList.add(s);
				});
			}
			FileHelper.exportExcel(socialList, "社会联动力量列表", "社会联动力量信息", SocialPowerImportParam.class, "社会联动力量.xls", response);
			return CommonResponseUtil.success("导出成功");
		} catch (Exception e) {
			return CommonResponseUtil.failure("导出社会联动力量失败");
		}
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "资源概览社会力量数据统计",   notes = "资源概览社会力量数据统计")
	@GetMapping(value = "/statistics")
	public ResponseModel getStatistics(@RequestParam(required = false) String bizOrgCode) {
		if (StringUtils.isEmpty(bizOrgCode)) {
			ReginParams reginParams = getSelectedOrgInfo();
			bizOrgCode = reginParams.getPersonIdentity().getBizOrgCode();;
		}
		FireResourceStatsDTO socialPowerStats = socialPowerService.getStatistics(bizOrgCode);
		Map<String, FireResourceStatsDTO> map = new HashMap<String, FireResourceStatsDTO>(){{
			put("socialPowerStats", socialPowerStats);
		}};
		return ResponseHelper.buildResponse(map);
	}

}
