package com.fs.his.controller;

import java.util.List;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.model.LoginUser;
import com.fs.common.utils.SecurityUtils;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.company.domain.Company;
import com.fs.company.domain.CompanyDeduct;
import com.fs.company.domain.CompanyRecharge;
import com.fs.company.param.CompanyDeductParam;
import com.fs.company.param.CompanyDivConfigUpdateParam;
import com.fs.company.param.CompanyRechargeParam;
import com.fs.company.service.*;
import com.fs.company.vo.CompanyVO;
import com.fs.core.utils.OrderCodeUtils;
import com.fs.course.config.CourseConfig;
import com.fs.framework.web.service.TokenService;
import com.fs.his.mapper.FsDoctorMapper;
import com.fs.his.vo.OptionsVO;
import com.fs.system.service.ISysConfigService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.enums.BusinessType;
import com.fs.common.core.page.TableDataInfo;

/**
 * 诊所管理Controller
 *
 * @author fs
 * @date 2023-07-12
 */
@RestController
@RequestMapping("/his/company")
public class FsCompanyController extends BaseController {
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private ICompanyUserService userService;

    @Autowired
    private ICompanyRechargeService rechargeService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private FsDoctorMapper fsDoctorMapper;
    @Autowired
    private ICompanyDeductService deductService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ICompanyDivConfigService companyDivConfigService;
    /**
     * 查询销售公司列表
     */
    @PreAuthorize("@ss.hasPermi('his:company:list')")
    @GetMapping("/list")
    public TableDataInfo list(Company company)
    {
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        if(!loginUser.isAdmin() && config.getDept() != null && config.getDept()){
            company.setDeptId(loginUser.getDeptId());
        }
        List<CompanyVO> list = companyService.selectCompanyListVO(company);
        return getDataTable(list);
    }

    @GetMapping("/companyList")
    public R companyList()
    {

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long depId = null;
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        if(!loginUser.isAdmin() && config.getDept() != null && config.getDept()){
            depId = loginUser.getDeptId();
        }
        List<OptionsVO> list = companyService.selectAllCompanyList(depId);
        return R.ok().put("data",list);
    }
    /**
     * 导出诊所管理列表
     */
    @PreAuthorize("@ss.hasPermi('his:company:export')")
    @Log(title = "销售公司", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Company company)
    {
        List<CompanyVO> list = companyService.selectCompanyListVO(company);
        for (CompanyVO companyVO : list) {
            if (companyVO.getFollowDoctorIds()!=null&&companyVO.getFollowDoctorIds()!=""){
                List<Long> ids = JSON.parseArray(companyVO.getFollowDoctorIds(), Long.class);
                String doctorName = "";
                for (Long id : ids) {
                    String doc = fsDoctorMapper.selectFsDoctorNameByDoctorId(id);
                    if (doctorName!=""){
                        doctorName+="," +doc;
                    }else {
                        doctorName=doc;
                    }

                }
                companyVO.setFollowDoctorName(doctorName);
            }
        }
        ExcelUtil<CompanyVO> util = new ExcelUtil<CompanyVO>(CompanyVO.class);
        return util.exportExcel(list, "诊所管理数据");
    }

    /**
     * 获取诊所管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('his:company:query')")
    @GetMapping(value = "/{companyId}")
    public AjaxResult getInfo(@PathVariable("companyId") Long companyId)
    {
        return AjaxResult.success(companyService.selectCompanyById(companyId));
    }

    /**
     * 新增销售公司管理
     */
    @PreAuthorize("@ss.hasPermi('his:company:add')")
    @Log(title = "销售公司", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody Company company)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        if(!loginUser.isAdmin() && config.getDept() != null && config.getDept()){
            company.setDeptId(loginUser.getDeptId());
        }
        return companyService.insertCompany(company);
    }

    /**
     * 修改诊所管理
     */
    @PreAuthorize("@ss.hasPermi('his:company:edit')")
    @Log(title = "销售公司", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Company company)
    {
        company.setMoney(null);
        company.setUpdateMiniApp(true);
        return toAjax(companyService.updateFsCompany(company));
    }

    /**
     * 删除诊所管理
     */
    @PreAuthorize("@ss.hasPermi('his:company:remove')")
    @Log(title = "销售公司", businessType = BusinessType.DELETE)
	@DeleteMapping("/{companyIds}")
    public AjaxResult remove(@PathVariable Long[] companyIds)
    {
        return toAjax(companyService.deleteCompanyByIds(companyIds));
    }


    @PreAuthorize("@ss.hasPermi('his:company:pass')")
    @PostMapping("/resetPwd/{companyId}")
    public AjaxResult resetPwd(@PathVariable Long companyId)
    {
        Company company=companyService.selectCompanyById(companyId);
        return toAjax(userService.resetUserPwdByUserId(company.getUserId(), SecurityUtils.encryptPassword("cq654321!!")));
    }

    @PreAuthorize("@ss.hasPermi('his:company:recharge')")
    @Log(title = "企业转账", businessType = BusinessType.INSERT)
    @PostMapping(value = "/recharge")
    @Transactional
    @RepeatSubmit
    public R recharge(@RequestBody CompanyRechargeParam param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        CompanyRecharge recharge=new CompanyRecharge();
        String orderSn =  OrderCodeUtils.getOrderSn();
        if(StringUtils.isEmpty(orderSn)){
            return R.error("订单生成失败，请重试");
        }
        recharge.setRechargeNo(orderSn);
        recharge.setCompanyId(param.getCompanyId());
        recharge.setMoney(param.getMoney());
        recharge.setCreateUserId(loginUser.getUser().getUserId());
        recharge.setIsAudit(0);
        recharge.setStatus(0);
        recharge.setRemark(param.getRemark());
        recharge.setPayType(3);
        rechargeService.insertCompanyRecharge(recharge);
        return R.ok("提交成功,等待审核");

    }


    /**
     * @Description: 红包充值功能 因公司余额的变动关联的地方太多，现在把充值红包的金额单独提出来 不合计到公司余额中
     * @Param:
     * @Return:
     * @Author xgb
     * @Date 2025/11/3 11:08
     */
    @PreAuthorize("@ss.hasPermi('his:company:redRecharge')")
    @Log(title = "红包充值", businessType = BusinessType.INSERT)
    @PostMapping(value = "/redRecharge")
    @Transactional
    @RepeatSubmit
    public R redRecharge(@RequestBody CompanyRechargeParam param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        CompanyRecharge redRecharge=new CompanyRecharge();
        String orderSn =  OrderCodeUtils.getOrderSn();
        if(StringUtils.isEmpty(orderSn)){
            return R.error("订单生成失败，请重试");
        }
        redRecharge.setRechargeNo(orderSn);
        redRecharge.setCompanyId(param.getCompanyId());
        redRecharge.setMoney(param.getMoney());
        redRecharge.setCreateUserId(loginUser.getUser().getUserId());
        redRecharge.setIsAudit(0);
        redRecharge.setStatus(0);
        redRecharge.setRemark(param.getRemark());
        redRecharge.setPayType(3);
        redRecharge.setBusinessType(1);// 红包充值
        rechargeService.insertCompanyRecharge(redRecharge);
        return R.ok("提交成功,等待审核");

    }

    @PreAuthorize("@ss.hasPermi('his:company:redDeduct')")
    @Log(title = "企业扣款", businessType = BusinessType.INSERT)
    @PostMapping(value = "/redDeduct")
    @Transactional
    @RepeatSubmit
    public R redDeduct(@RequestBody CompanyDeductParam param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        CompanyDeduct deduct=new CompanyDeduct();
        String orderSn =  OrderCodeUtils.getOrderSn();
        if(StringUtils.isEmpty(orderSn)){
            return R.error("订单生成失败，请重试");
        }
        deduct.setDeductNo(orderSn);
        deduct.setCompanyId(param.getCompanyId());
        deduct.setMoney(param.getMoney());
        deduct.setCreateUserId(loginUser.getUser().getUserId());
        deduct.setIsAudit(0);
        deduct.setRemark(param.getRemark());
        deduct.setBusinessType(1); // 红包扣款
        deductService.insertCompanyDeduct(deduct);
        return R.ok("提交成功,等待审核");
    }

    @PreAuthorize("@ss.hasPermi('his:company:deduct')")
    @Log(title = "企业扣款", businessType = BusinessType.INSERT)
    @PostMapping(value = "/deduct")
    @Transactional
    @RepeatSubmit
    public R deduct(@RequestBody CompanyDeductParam param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Company company = companyService.selectCompanyById(param.getCompanyId());
        CompanyDeduct deduct=new CompanyDeduct();
        String orderSn =  OrderCodeUtils.getOrderSn();
        if(StringUtils.isEmpty(orderSn)){
            return R.error("订单生成失败，请重试");
        }
        deduct.setDeductNo(orderSn);
        deduct.setCompanyId(param.getCompanyId());
        deduct.setMoney(param.getMoney());
        deduct.setCreateUserId(loginUser.getUser().getUserId());
        deduct.setIsAudit(0);
        deduct.setBalance(company.getMoney());
        deduct.setRemark(param.getRemark());
        deductService.insertCompanyDeduct(deduct);
        return R.ok("提交成功,等待审核");
    }

    /**
     * 获取公司分账配置详细信息
     */
    @GetMapping(value = "/getDivConfig/{companyId}")
    public AjaxResult getDivConfig(@PathVariable("companyId") Long companyId)
    {
        return AjaxResult.success(companyDivConfigService.selectCompanyDivConfigByCompanyId(companyId));
    }

    /**
     * 公司分账配置
     */
    @PreAuthorize("@ss.hasPermi('his:companyDivConfig:set')")
    @Log(title = "公司分账配置", businessType = BusinessType.UPDATE)
    @PostMapping("/setDiv")
    public R setDiv(@RequestBody CompanyDivConfigUpdateParam param)
    {
        return companyDivConfigService.setDiv(param);
    }

    @PostMapping("/exitMiniProgram")
    @Log(title = "批量修改小程序", businessType = BusinessType.UPDATE)
    public R exitMiniProgram(@RequestBody Company company) {
        // 1. 前置校验：核心参数非空校验
        if (CollectionUtils.isEmpty(company.getIds())) {
            return R.error("请选择需要修改的企业ID");
        }
        if (isNNull(company.getCourseMiniAppId())&&isListNull(company.getMiniAppMaster()) && isListNull(company.getMiniAppServer())) {
            return R.error("请选择要修改的小程序");
        } else {
            for (Long id : company.getIds()) {
                Company c = companyService.selectCompanyById(id);
                c.setMoney(null);
                c.setUpdateMiniApp(true);
                if (company.getCourseMiniAppId()!= null&&!company.getCourseMiniAppId().isEmpty()) c.setCourseMiniAppId(company.getCourseMiniAppId());
                if (company.getMiniAppMaster()!=null&&!company.getMiniAppMaster().isEmpty()) c.setMiniAppMaster(company.getMiniAppMaster());
                if (company.getMiniAppServer()!=null&&!company.getMiniAppServer().isEmpty()) c.setMiniAppServer(company.getMiniAppServer());
                companyService.updateCompany(c);
            }
            return R.ok();
        }
    }
   public boolean isNNull(String value){
        if (value==null)return true;
        if (value.isEmpty())return true;
        return false;
    }
    public boolean isListNull(List<String> value){
        if (value==null)return true;
        if (value.isEmpty())return true;
        return false;
    }
}
