/*
 *    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.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qunzhixinxi.hnqz.admin.api.dto.UserInfo;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDept;
import com.qunzhixinxi.hnqz.admin.api.entity.SysUser;
import com.qunzhixinxi.hnqz.admin.entity.*;
import com.qunzhixinxi.hnqz.admin.enums.SubjectTypeEnum;
import com.qunzhixinxi.hnqz.admin.mapper.SysDeptMapper;
import com.qunzhixinxi.hnqz.admin.mapper.SysUserMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmTaskTypeEntRefMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmTaskTypeMapper;
import com.qunzhixinxi.hnqz.admin.service.*;
import com.qunzhixinxi.hnqz.common.core.util.R;
import com.qunzhixinxi.hnqz.common.log.annotation.SysLog;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * 档案-药企
 *
 * @author gaoyanng
 * @date 2020-06-25 23:35:42
 */
@RestController
@AllArgsConstructor
@RequestMapping("/wmdadrugent")
@Api(value = "wmdadrugent", tags = "档案-药企管理")
public class WmDaDrugEntController {

	private final WmDaDrugEntService wmDaDrugEntService;
	private final WmDaAgentService wmDaAgentService;
	private final SysUserService userService;
	private final SysDeptService sysDeptService;
	private final SysDeptSubService sysDeptSubService;
	private final WmTaskTypeEntRefMapper wmTaskTypeEntRefMapper;
	private final WmTaskTypeMapper wmTaskTypeMapper;
	private final SysDeptMapper sysDeptMapper;
	private final SysUserMapper sysUserMapper;

	/**
	 * 分页查询
	 *
	 * @param page        分页对象
	 * @param wmDaDrugEnt 档案-药企
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/page")
	@PreAuthorize("@pms.hasPermission('admin_wmdadrugent_view')")
	public R getWmDaDrugEntPage(Page page, WmDaDrugEnt wmDaDrugEnt) {
		return R.ok(wmDaDrugEntService.selectPage(page, wmDaDrugEnt));
	}


	/**
	 * 通过id查询档案-药企
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('admin_wmdadrugent_view')")
	public R getById(@PathVariable("id") Integer id) {
		return R.ok(wmDaDrugEntService.getById(id));
	}


	/**
	 * @Modify: start
	 * @Version: v2021.4.16
	 * @Author: ryz
	 * @Date: 2021/5/26  弃用
	*/
	/**
	 * 新增档案-药企
	 *
	 * @param wmDaDrugEnt 档案-药企
	 * @return R
	 */
	@ApiOperation(value = "新增档案-药企", notes = "新增档案-药企")
	@SysLog("新增档案-药企")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('admin_wmdadrugent_add')")
	public R save(@RequestBody WmDaDrugEnt wmDaDrugEnt) {

		WmDaDrugEnt query = new WmDaDrugEnt();
		query.setEntname(wmDaDrugEnt.getEntname());
		List<WmDaDrugEnt> list = wmDaDrugEntService.list(Wrappers.query(query));

		if (list.size() > 0) {
			return R.failed("药企公司名称已存在");
		}

		wmDaDrugEnt.setCreateTime(LocalDateTime.now());
		return R.ok(wmDaDrugEntService.saveDrugEnt(wmDaDrugEnt));
	}


	/**
	 * 新增档案-药企
	 *
	 * @param wmDaDrugEnt 档案-药企
	 * @return R
	 */
	@ApiOperation(value = "新增档案-药企", notes = "新增档案-药企")
	@SysLog("新增档案-药企")
	@PostMapping("saves")
	@PreAuthorize("@pms.hasPermission('admin_wmdadrugent_add')")
	public R saves(@RequestBody WmDaDrugEnt wmDaDrugEnt) {

		WmDaDrugEnt query = new WmDaDrugEnt();
		query.setEntname(wmDaDrugEnt.getEntname());
		List<WmDaDrugEnt> list = wmDaDrugEntService.list(Wrappers.query(query));

		if (list.size() > 0) {
			return R.failed("药企公司名称已存在");
		}

		WmDaDrugEnt query1 = new WmDaDrugEnt();
		query1.setEntcode(wmDaDrugEnt.getEntcode());
		List<WmDaDrugEnt> list1 = wmDaDrugEntService.list(Wrappers.query(query1));

		if (list1.size() > 0) {
			return R.failed("统一社会信用代码已经存在");
		}

		wmDaDrugEnt.setManagement("1");
		wmDaDrugEnt.setPgqx(1 + "");
		if (wmDaDrugEntService.saveDrugEnts(wmDaDrugEnt)) {
			System.out.println("+++++++++++" + wmDaDrugEnt.getDeptId());
			SysDept sysDept = sysDeptService.getById(wmDaDrugEnt.getDeptId());
			if (2 == sysDept.getLevel()) {
				WmTaskTypeEntRef wmTaskTypeEntRef = new WmTaskTypeEntRef();
				wmTaskTypeEntRef.setDrugentId(wmDaDrugEnt.getId());
				wmTaskTypeEntRef.setAgentId(wmDaDrugEnt.getId());
				WmTaskType wmTaskType = new WmTaskType();
				wmTaskType.setDurgentId(wmDaDrugEnt.getId());
				wmTaskType.setDelFlag("0");
				List<WmTaskType> lists = wmTaskTypeMapper.selectList(Wrappers.query(wmTaskType));
				if (lists.size() > 0) {
					return R.failed("一代积分规则已分配");
				} else {
					if (null != wmDaDrugEnt) {
						wmTaskTypeEntRef.setDeptId(wmDaDrugEnt.getDeptId());
					}
					int isSave = wmTaskTypeEntRefMapper.insert(wmTaskTypeEntRef);

					WmTaskType wmTaskTypeQ = new WmTaskType();
					wmTaskTypeQ.setTaskTypeLevel("1");
					wmTaskTypeQ.setStatus("0");
					wmTaskTypeQ.setDelFlag("0");

					List<WmTaskType> tempList = wmTaskTypeMapper.selectList(Wrappers.query(wmTaskTypeQ));

					for (WmTaskType wmTaskType1 : tempList) {
						WmTaskType newOne = wmTaskType1;
						newOne.setId(null);
//						newOne.setLevel1Id(wmTaskTypeEntRef.getAgentId());
						newOne.setDurgentId(wmTaskTypeEntRef.getAgentId());
						newOne.setTaskTypeLevel("2");
						newOne.setTaskEntId(wmTaskTypeEntRef.getAgentId());
						newOne.setDeptId(wmDaDrugEnt.getDeptId() + "");
						newOne.setCreateTime(LocalDateTime.now());
						newOne.setStatus("0");
						newOne.setBaseId(wmTaskType1.getId());
						newOne.setRuleId(wmTaskTypeEntRef.getAgentId());
						newOne.setParentId(wmTaskType1.getParentId());
						wmTaskTypeMapper.insert(newOne);
					}
				}
			}
		}
		wmDaDrugEnt.setCreateTime(LocalDateTime.now());

		return R.ok();
	}

	/**
	 * 修改档案-药企
	 *
	 * @param wmDaDrugEnt 档案-药企
	 * @return R
	 */
	@ApiOperation(value = "修改档案-药企", notes = "修改档案-药企")
	@SysLog("修改档案-药企")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('admin_wmdadrugent_edit')")
	public R updateById(@RequestBody WmDaDrugEnt wmDaDrugEnt) {

		SysDept sysDept1 = new SysDept();
		sysDept1.setDeptId(Integer.parseInt(wmDaDrugEnt.getDeptId()));
		SysDept sysDept = sysDeptMapper.selectDept(sysDept1);
		sysDept.setDelFlag(wmDaDrugEnt.getEnableFlag());
		sysDept.setName(wmDaDrugEnt.getEntname());
		sysDept.setDeptId(Integer.parseInt(wmDaDrugEnt.getDeptId()));


		/**
		* @Modify: start
		* @Author: ryz
		* @Date: 2021/4/19
		*/
		if(!Arrays.equals(sysDept.getSubjectType(),wmDaDrugEnt.getSubjectType())){
			sysDeptSubService.update(Wrappers.<SysDeptSub>lambdaUpdate()
					.eq(SysDeptSub::getDeptId,sysDept.getDeptId())
					.set(SysDeptSub::getEnableFlag,SubjectTypeEnum.ENABLE_FLAG_FALSE.getCode()));

			for (String subType : wmDaDrugEnt.getSubjectType()) {
				SysDeptSub condition = new SysDeptSub();
				condition.setDeptId(sysDept.getDeptId());
				condition.setSubjectType(subType);
				SysDeptSub existSub = sysDeptSubService.getOne(Wrappers.query(condition));
				if(null != existSub){
					existSub.setEnableFlag(SubjectTypeEnum.ENABLE_FLAG_TRUE.getCode());
					sysDeptSubService.updateById(existSub);
				}else {
					existSub = new SysDeptSub();
					existSub.setEnableFlag(SubjectTypeEnum.ENABLE_FLAG_TRUE.getCode());
					existSub.setDeptId(sysDept.getDeptId());
					existSub.setSubjectType(subType);
					sysDeptSubService.save(existSub);
				}
			}
		}
		sysDept.setTaxCode(wmDaDrugEnt.getEntcode());
		/**
		* @Modify: end
		*/

		sysDept.setSubjectType(wmDaDrugEnt.getSubjectType());
		sysDept.setDeptPermissions(wmDaDrugEnt.getDeptPermissions());
		sysDeptMapper.updateByPrimaryKeySelective(sysDept);
		SysUser sysUserCondition = new SysUser();
		sysUserCondition.setDeptId(Integer.parseInt(wmDaDrugEnt.getDeptId()));
		List<SysUser> sysUserList = sysUserMapper.selectUserById(sysUserCondition);
//		List<Integer> id1 = sysUserList.stream().map(p -> p.getUserId()).collect(Collectors.toList());
		/**
		 * 修改机构的人员状态
		 */
		for (SysUser item : sysUserList) {
			item.setDelFlag(wmDaDrugEnt.getEnableFlag());
			sysUserMapper.updateByPrimaryKeySelective(item);
		}

		return R.ok(wmDaDrugEntService.updateById(wmDaDrugEnt));
	}

	/**
	 * 通过id删除档案-药企
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id删除档案-药企", notes = "通过id删除档案-药企")
	@SysLog("通过id删除档案-药企")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('admin_wmdadrugent_del')")
	public R removeById(@PathVariable Integer id) {
		return R.ok(wmDaDrugEntService.removeById(id));
	}


	/**
	 * 获取药企列表
	 *
	 * @return 角色列表
	 */
	@GetMapping("/list")
	public R listDrugEnt(WmDaDrugEnt wmDaDrugEnt) {
		wmDaDrugEnt.setDelFlag("0");
		wmDaDrugEnt.setEnableFlag("0");
		if (null != wmDaDrugEnt.getEntname()) {
			String entname = wmDaDrugEnt.getEntname();
			wmDaDrugEnt.setEntname(null);
			return R.ok(wmDaDrugEntService.list(Wrappers.query(wmDaDrugEnt).lambda().like(WmDaDrugEnt::getEntname, entname)));
		} else {
			return R.ok(wmDaDrugEntService.list(Wrappers.query(wmDaDrugEnt)));
		}
	}

	/**
	 * 获取药企列表
	 *
	 * @return 角色列表
	 */
	@GetMapping("/listScope")
	public R listScope(WmDaDrugEnt wmDaDrugEnt) {
		wmDaDrugEnt.setDelFlag("0");
		wmDaDrugEnt.setEnableFlag("0");

		if (null != wmDaDrugEnt.getEntname()) {
			String entname = wmDaDrugEnt.getEntname();
			wmDaDrugEnt.setEntname(null);
			return R.ok(wmDaDrugEntService.selectByScope(Wrappers.query(wmDaDrugEnt).lambda().like(WmDaDrugEnt::getEntname, entname)));
		} else {
			return R.ok(wmDaDrugEntService.selectByScope(Wrappers.query(wmDaDrugEnt)));
		}
	}

	/**
	 * 获取药企列表
	 *
	 * @return 角色列表
	 */
	@GetMapping("/listBySel")
	public R listBySel(WmDaDrugEnt wmDaDrugEnt) {
		wmDaDrugEnt.setDelFlag("0");
		wmDaDrugEnt.setEnableFlag("0");
		if (!SecurityUtils.getRoles().contains(1) && !SecurityUtils.getRoles().contains(2)) {
			wmDaDrugEnt.setId(SecurityUtils.getUser().getDrugEntId());
			return R.ok(wmDaDrugEntService.list(Wrappers.query(wmDaDrugEnt)));
		} else {
			return R.ok(wmDaDrugEntService.list(Wrappers.query(wmDaDrugEnt)));
		}
	}


	private boolean isZbOrDbUsers(Integer[] roles) {
		if (null == roles) {
			return false;
		}

		if (Arrays.asList(roles).contains(1) || Arrays.asList(roles).contains(2) || Arrays.asList(roles).contains(3) || Arrays.asList(roles).contains(4)) {
			return true;
		}
		return false;
	}

	/**
	 * 通过ID查询
	 *
	 * @param username
	 * @return SysDept
	 */
	@GetMapping("/getDrugListByUsername")
	public R getDrugListByUsername(String username) {

		List<SysUser> userList = userService.list(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, username).eq(SysUser::getDelFlag, "0"));
		List<Integer> list = new ArrayList<>();
		if (userList.size() > 0) {
			for (SysUser s : userList
			) {
				if (null != s.getDrugEntId() && !"null".equals(s.getDrugEntId()) && !"".equals(s.getDrugEntId())) {
					UserInfo userInfo = userService.findUserInfo(s);
					if (isZbOrDbUsers(userInfo.getRoles())) {
						list.add(Integer.parseInt(s.getDrugEntId()));
					}
				}
			}
		}
		if (list.size() > 0) {
			return R.ok(wmDaDrugEntService.listByIds(list));
		} else {
			return R.ok();
		}
	}


	/**
	 * 通过ID查询
	 *
	 * @return SysDept
	 */
	@GetMapping("/getDrugListByAgentServiceEnt")
	public R getDrugListByAgentServiceEnt() {

		List<String> stringList = new ArrayList<>();

		SysDept sysDept = sysDeptService.getById(SecurityUtils.getUser().getDeptId());
		if (null != sysDept) {
			String levelId = "";
			if (sysDept.getLevel() == 3) {
				levelId = sysDept.getLevel2Id() + "";
			} else {
				levelId = sysDept.getLevel3Id() + "";
			}
			WmDaAgent wmDaAgent = wmDaAgentService.getById(levelId);
			if (null != wmDaAgent && null != wmDaAgent.getExtDrugEnt() && !"".equals(wmDaAgent.getExtDrugEnt())) {
				String extDrugEnt = wmDaAgent.getExtDrugEnt();
				String ext[] = extDrugEnt.split(",");
				for (String args : ext) {
					if (!(sysDept.getLevel1Id() + "").equals(args)) {
						stringList.add(args);
					}
				}
			}
		}
		stringList.add(SecurityUtils.getUser().getDrugEntId());

		if (stringList.size() > 0) {
			return R.ok(wmDaDrugEntService.listByIds(stringList));
		}

		return R.ok();

	}


}
