/*
 *    Copyright (c) 2018-2025, hnqz All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: hnqz
 */

package com.qunzhixinxi.hnqz.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDictItem;
import com.qunzhixinxi.hnqz.admin.entity.WmDaDistribution;
import com.qunzhixinxi.hnqz.admin.entity.WmTask;
import com.qunzhixinxi.hnqz.admin.entity.WmTaskContent;
import com.qunzhixinxi.hnqz.admin.service.SysDictItemService;
import com.qunzhixinxi.hnqz.admin.service.WmDaDistributionService;
import com.qunzhixinxi.hnqz.admin.service.WmDaHospitalService;
import com.qunzhixinxi.hnqz.admin.service.WmTaskContentService;
import com.qunzhixinxi.hnqz.admin.service.WmTaskService;
import com.qunzhixinxi.hnqz.admin.util.MapUtil;
import com.qunzhixinxi.hnqz.common.core.util.R;
import com.qunzhixinxi.hnqz.common.log.annotation.SysLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;


/**
 * 档案-配送公司
 *
 * @author gaoyanng
 * @date 2020-06-25 23:35:42
 */
@RestController
@AllArgsConstructor
@RequestMapping("/wmdadistribution")
@Api(value = "wmdadistribution", tags = "档案-配送公司管理")
public class WmDaDistributionController {

	private final WmDaDistributionService wmDaDistributionService;

	private final WmDaHospitalService wmDaHospitalService;

	private final WmTaskService wmTaskService;

	private final WmTaskContentService wmTaskContentService;

	private final SysDictItemService sysDictItemService;

	/**
	 * 分页查询
	 *
	 * @param page             分页对象
	 * @param wmDaDistribution 档案-配送公司
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/page")
	@PreAuthorize("@pms.hasPermission('admin_wmdadistribution_view')")
	public R getWmDaDistributionPage(Page page, WmDaDistribution wmDaDistribution) {
		String hospital = wmDaDistribution.getGsmc();
		OrderItem orderItem = new OrderItem();
		orderItem.setColumn("create_time");
		orderItem.setAsc(false);
		page.addOrder(orderItem);
		if (null != hospital) {
			wmDaDistribution.setGsmc(null);
			return R.ok(wmDaDistributionService.page(page, Wrappers.query(wmDaDistribution).lambda().like(WmDaDistribution::getGsmc, hospital)));
		}
		return R.ok(wmDaDistributionService.page(page, Wrappers.query(wmDaDistribution)));
	}

	/**
	 * 分页查询
	 *
	 * @param page             分页对象
	 * @param wmDaDistribution 档案-医院
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/pageAudit")
	public R pageAudit(Page page, WmDaDistribution wmDaDistribution) {
		if (null != wmDaDistribution.getUpdateUser()) {
			WmTask wmTask = wmTaskService.getById(wmDaDistribution.getUpdateUser());
			if (null != wmTask) {
				WmTaskContent wmTaskContent = wmTaskContentService.getById(wmTask.getTaskContentId());
				if (null != wmTaskContent && null != wmTaskContent.getTemp29()) {
					wmDaDistribution.setId(wmTaskContent.getTemp29());
				} else {
					wmDaDistribution.setId("-1");
				}
			}
			wmDaDistribution.setUpdateUser(null);
		}

		return R.ok(wmDaDistributionService.page(page, Wrappers.query(wmDaDistribution)));
	}

	/**
	 * 通过id查询档案-配送公司
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/{id}")
	public R getById(@PathVariable("id") Integer id) {
		WmDaDistribution distribution = wmDaDistributionService.getById(id);
		// 设置药品信息化追溯体系名称
		if (distribution != null && StringUtils.isNotBlank(distribution.getMedicineTraceability())) {
			SysDictItem medicineTraceabilityDict = sysDictItemService.getOne(Wrappers.<SysDictItem>lambdaQuery()
					.eq(SysDictItem::getType, "medicine_traceability")
					.eq(SysDictItem::getValue, distribution.getMedicineTraceability()));
			if (medicineTraceabilityDict != null) {
				distribution.setMedicineTraceabilityName(medicineTraceabilityDict.getLabel());
			}
		}
		return R.ok(distribution);
	}

	/**
	 * 新增档案-配送公司
	 *
	 * @param wmDaDistribution 档案-配送公司
	 * @return R
	 */
	@ApiOperation(value = "新增档案-配送公司", notes = "新增档案-配送公司")
	@SysLog("新增档案-配送公司")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('admin_wmdadistribution_add')")
	public R save(@RequestBody WmDaDistribution wmDaDistribution) {


		WmDaDistribution query = new WmDaDistribution();
		query.setGsmc(wmDaDistribution.getGsmc());
		List<WmDaDistribution> list = wmDaDistributionService.list(Wrappers.query(query));

		if (list.size() > 0) {
			return R.failed("配送公司名称已存在");
		}
		wmDaDistribution.setCreateTime(LocalDateTime.now());

		Integer hid = wmDaDistribution.getUpdateUser();
		wmDaDistribution.setUpdateUser(0);
		wmDaDistribution.setDelFlag(0);
		wmDaDistribution.setEnableFlag(0);

		wmDaDistributionService.save(wmDaDistribution);
		if (null != hid && 0 != hid) {
			WmTask wmTask = wmTaskService.getById(hid);
			if (null != wmTask) {
				WmTaskContent wmTaskContent = wmTaskContentService.getById(wmTask.getTaskContentId());
				if (null != wmTaskContent) {
					wmTaskContent.setTemp29(wmDaDistribution.getId());
					wmTaskContentService.updateById(wmTaskContent);
				}
				wmTask.setPlatAuditStatus("1");
				wmTaskService.updateById(wmTask);
			}
		}

		return R.ok();
	}

	/**
	 * 修改档案-配送公司
	 *
	 * @param wmDaDistribution 档案-配送公司
	 * @return R
	 */
	@ApiOperation(value = "修改档案-配送公司", notes = "修改档案-配送公司")
	@SysLog("修改档案-配送公司")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('admin_wmdadistribution_edit')")
	public R updateById(@RequestBody WmDaDistribution wmDaDistribution) {
		Integer hid = wmDaDistribution.getUpdateUser();
		wmDaDistribution.setUpdateUser(0);
		wmDaDistributionService.updateById(wmDaDistribution);
		if (null != hid && 0 != hid) {
			WmTask wmTask = wmTaskService.getById(hid);
			if (null != wmTask) {
				WmTaskContent wmTaskContent = wmTaskContentService.getById(wmTask.getTaskContentId());
				if (null != wmTaskContent) {
					wmTaskContent.setTemp29(wmDaDistribution.getId());
					wmTaskContentService.updateById(wmTaskContent);
				}
				wmTask.setPlatAuditStatus("1");
				wmTaskService.updateById(wmTask);
			}
		}
		return R.ok();
	}

	/**
	 * 通过id删除档案-配送公司
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id删除档案-配送公司", notes = "通过id删除档案-配送公司")
	@SysLog("通过id删除档案-配送公司")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('admin_wmdadistribution_del')")
	public R removeById(@PathVariable Integer id) {
		return R.ok(wmDaDistributionService.removeById(id));
	}


	/**
	 * 获取药企列表
	 */
	@GetMapping("/listDistributionByName")
	public R listDistributionByName(Page page, String name) {
		WmDaDistribution wmDaHospital = new WmDaDistribution();
		wmDaHospital.setDelFlag(0);
		wmDaHospital.setEnableFlag(0);
		if (null != name) {
			return R.ok(wmDaDistributionService.page(page, Wrappers.query(wmDaHospital).like(true, "gsmc", name)));

		} else {
			return R.ok(wmDaDistributionService.page(page, Wrappers.query(wmDaHospital)));
		}
	}

	/**
	 * 获取药企列表
	 */
	@GetMapping("/getDistributionByName")
	public R getDistributionByName(String name) {
		WmDaDistribution wmDaHospital = new WmDaDistribution();
		wmDaHospital.setDelFlag(0);
		wmDaHospital.setEnableFlag(0);
		if (StringUtils.isNotEmpty(name)) {
			wmDaHospital.setGsmc(name);
			List<WmDaDistribution> distributions = wmDaDistributionService.
					list(Wrappers.query(wmDaHospital));
			if (CollectionUtils.isNotEmpty(distributions)) {
				return R.ok(distributions.get(0));
			}
		}
		return R.ok();
	}

	/**
	 * 获取药企列表
	 *
	 * @return 角色列表
	 */
	@GetMapping("/listDistributionByNameNoPage")
	public R listDistributionByNameNoPage(String name) {
		WmDaDistribution wmDaHospital = new WmDaDistribution();
		wmDaHospital.setDelFlag(0);
		wmDaHospital.setEnableFlag(0);
		if (null != name) {
			return R.ok(wmDaDistributionService.list(Wrappers.query(wmDaHospital).like(true, "gsmc", name)));

		} else {
			return R.ok(wmDaDistributionService.list(Wrappers.query(wmDaHospital)));
		}
	}


	/**
	 * 获取药企列表
	 *
	 * @return 角色列表
	 */
	@GetMapping("/parseAddress")
	public R parseAddress() {
		LambdaQueryWrapper<WmDaDistribution> wmDaHospitalLambdaQueryWrapper = Wrappers.lambdaQuery();

		wmDaHospitalLambdaQueryWrapper.isNull(WmDaDistribution::getLatitude);

		List<WmDaDistribution> wmDaDistributionList = wmDaDistributionService.list(wmDaHospitalLambdaQueryWrapper);

		if (wmDaDistributionList.size() > 0) {
			for (WmDaDistribution wmDaDistribution : wmDaDistributionList) {
				JSONObject jsonObject = MapUtil.getLatAndLogByName(wmDaDistribution.getAddress());
				if (null == jsonObject) {
					continue;
				}
				wmDaDistribution.setProvince(jsonObject.getString("province"));
				wmDaDistribution.setCity(jsonObject.getString("city"));
				wmDaDistribution.setArea(jsonObject.getString("district"));
				String sygsdz = jsonObject.getString("province");
				if(StringUtils.isNotEmpty(jsonObject.getString("city"))){
					sygsdz = sygsdz + jsonObject.getString("city");
				}
				if(StringUtils.isNotEmpty(jsonObject.getString("district"))){
					sygsdz = sygsdz + jsonObject.getString("district");
				}
				wmDaDistribution.setSygsdz(sygsdz);
				String location = jsonObject.getString("location");
				if (null != location && location.split(",").length > 0) {
					wmDaDistribution.setLongitude(location.split(",")[0]);
					wmDaDistribution.setLatitude(location.split(",")[1]);
				}

				wmDaDistributionService.saveOrUpdate(wmDaDistribution);
			}
		}

		return R.ok();
	}

	/**
	 * 调查信息审核--商业公司
	 *
	 * @return
	 */
	@ApiOperation(value = "调查信息审核", notes = "调查信息审核")
	@GetMapping("/approvalDistribution")
	public R approvalDistribution(String taskId) {

		return wmDaDistributionService.approvalDistribution(taskId);
	}

	/**
	 * 审核意见保存--商业公司
	 *
	 * @return
	 */
	@ApiOperation(value = "审核意见保存", notes = "审核意见保存")
	@PostMapping("/updateByApproval")
	public R updateByApproval(@RequestBody Map<String, String> map) {
		return wmDaDistributionService.updateByApproval(map);

	}
}
