package com.fs.company.controller.company;

import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.company.domain.CompanyTcmReport;
import com.fs.company.domain.CompanyTcmSchedule;
import com.fs.company.param.CompanyTcmReportListQueryParam;
import com.fs.company.service.ICompanyTcmReportService;
import com.fs.company.service.ICompanyTcmScheduleService;
import com.fs.company.vo.CompanyReportExportVO;
import com.fs.company.vo.CompanyTcmReportListVO;
import com.fs.company.vo.CompanyTcmStatisticsExportVO;
import com.fs.framework.security.LoginUser;
import com.fs.framework.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * 中医档期业绩报表Controller
 *
 * @author fs
 * @date 2023-09-05
 */
@RestController
@RequestMapping("/company/tcmScheduleReport")
public class CompanyTcmReportController extends BaseController
{
    @Autowired
    private ICompanyTcmReportService companyTcmReportService;

    @Autowired
    private ICompanyTcmScheduleService companyTcmScheduleService;

    @Autowired
    private TokenService tokenService;

    @PreAuthorize("@ss.hasPermi('company:tcmScheduleReport:list')")
    @GetMapping("/list")
    public TableDataInfo list(CompanyTcmReportListQueryParam param)
    {
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId().toString());
        if(!loginUser.getUser().isAdmin()){
            param.setCompanyUserId(loginUser.getUser().getUserId());
        }
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDateRange())){
            param.setStartTimeList(param.getDateRange().split("--"));
        }
        List<CompanyTcmReportListVO> list = companyTcmReportService.selectCompanyTcmReportListVOList(param);
        return getDataTable(list);
    }

    /**
     * 导出中医档期业绩报表列表
     */
    @PreAuthorize("@ss.hasPermi('company:tcmScheduleReport:export')")
    @Log(title = "中医档期业绩报表", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(CompanyTcmReportListQueryParam param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId().toString());
        if(!loginUser.getUser().isAdmin()){
            param.setCompanyUserId(loginUser.getUser().getUserId());
        }
        List<CompanyReportExportVO> list = companyTcmReportService.selectCompanyReportExportVOList(param);
        for(CompanyReportExportVO item:list){
            item.setRegisterRate(String.format("%.3f", item.getRegisterNum().doubleValue()/item.getTotalNum().doubleValue()*100.0).toString()+"%");
            item.setOnlineRate(String.format("%.3f", item.getOnlineNum().doubleValue()/item.getRegisterNum().doubleValue()*100.0).toString()+"%");
            item.setFinishRate(String.format("%.3f", item.getFinishNum().doubleValue()/item.getRegisterNum().doubleValue()*100.0).toString()+"%");
            if(item.getTargetMoney()!=null){
                item.setTargetRate(String.format("%.3f", item.getTotalMoney().doubleValue()/item.getTargetMoney().doubleValue()*100.0).toString()+"%");
            }else{
                item.setTargetRate("0%");
            }
            if(item.getRound1Order()!=null){
                item.setRound1Rate(getRoundRate(item.getRound1Order(),item.getTotalNum()));
                item.setRound1Unit(new BigDecimal(getRoundUnit(item.getRound1Money(),item.getRound1Order())).setScale(3, RoundingMode.HALF_UP));
            }
            if(item.getRound2Order()!=null){
                item.setRound2Rate(getRoundRate(item.getRound2Order(),item.getTotalNum()));
                item.setRound2Unit(new BigDecimal(getRoundUnit(item.getRound2Money(),item.getRound2Order())).setScale(3, RoundingMode.HALF_UP));
            }
            if(item.getRound3Order()!=null){
                item.setRound3Rate(getRoundRate(item.getRound3Order(),item.getTotalNum()));
                item.setRound3Unit(new BigDecimal(getRoundUnit(item.getRound3Money(),item.getRound3Order())).setScale(3, RoundingMode.HALF_UP));
            }
            if(item.getRound4Order()!=null){
                item.setRound4Rate(getRoundRate(item.getRound4Order(),item.getTotalNum()));
                item.setRound4Unit(new BigDecimal(getRoundUnit(item.getRound4Money(),item.getRound4Order())).setScale(3, RoundingMode.HALF_UP));
            }
            if(item.getRound5Order()!=null){
                item.setRound5Rate(getRoundRate(item.getRound5Order(),item.getTotalNum()));
                item.setRound5Unit(new BigDecimal(getRoundUnit(item.getRound5Money(),item.getRound5Order())).setScale(3, RoundingMode.HALF_UP));
            }
            if(item.getRound6Order()!=null){
                item.setRound6Rate(getRoundRate(item.getRound6Order(),item.getTotalNum()));
                item.setRound6Unit(new BigDecimal(getRoundUnit(item.getRound6Money(),item.getRound6Order())).setScale(3, RoundingMode.HALF_UP));
            }
            if(item.getRound7Order()!=null) {
                item.setRound7Rate(getRoundRate(item.getRound7Order(), item.getTotalNum()));
                item.setRound7Unit(new BigDecimal(getRoundUnit(item.getRound7Money(), item.getRound7Order())).setScale(3, RoundingMode.HALF_UP));
            }
            if (item.getRound8Order() != null) {
                item.setRound8Rate(getRoundRate(item.getRound8Order(), item.getTotalNum()));
                item.setRound8Unit(new BigDecimal(getRoundUnit(item.getRound8Money(), item.getRound8Order())).setScale(3, RoundingMode.HALF_UP));
            }
            if (item.getRound9Order() != null) {
                item.setRound9Rate(getRoundRate(item.getRound9Order(), item.getTotalNum()));
                item.setRound9Unit(new BigDecimal(getRoundUnit(item.getRound9Money(), item.getRound9Order())).setScale(3, RoundingMode.HALF_UP));
                //item.setRound9Rate(String.format("%.3f", item.getRound9Order().doubleValue()/item.getTotalNum()*100.0).toString()+"%");
                //item.setRound9Unit(new BigDecimal(item.getRound9Money().doubleValue()/item.getRound9Order()*1.0).setScale(3, RoundingMode.HALF_UP));
            }
        }
        ExcelUtil<CompanyReportExportVO> util = new ExcelUtil<CompanyReportExportVO>(CompanyReportExportVO.class);
        return util.exportExcel(list, "statisticsScheduleReport");
    }



    @PreAuthorize("@ss.hasPermi('company:tcmScheduleReport:statistics')")
    @GetMapping("/statisticsList")
    public TableDataInfo statisticsList(CompanyTcmReportListQueryParam param)
    {
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId().toString());
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(param.getDeptId()!=null){
            param.setDeptIdStr(param.getDeptId().toString());
        }
        List<CompanyTcmReportListVO> list = companyTcmReportService.selectCompanyTcmReportStatisticsVOList(param);
        return getDataTable(list);
    }


    /**
     * 导出中医公司报表统计
     */
    @PreAuthorize("@ss.hasPermi('company:tcmScheduleReport:export')")
    @Log(title = "中医档期业绩报表", businessType = BusinessType.EXPORT)
    @GetMapping("/exportCompany")
    public AjaxResult exportCompany(CompanyTcmReportListQueryParam param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId().toString());
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        List<CompanyTcmStatisticsExportVO> list = companyTcmReportService.selectCompanyTcmStatisticsExportVOList(param);
        for(CompanyTcmStatisticsExportVO item:list){
            if(item.getTotalNum()!=null && item.getTotalNum().doubleValue()>0){
                item.setRegisterRate(String.format("%.3f",getLongRate(item.getRegisterNum().doubleValue(),item.getTotalNum())*100.0).toString()+"%");
                item.setOnlineRate(String.format("%.3f",getLongRate(item.getOnlineNum().doubleValue(),item.getTotalNum())*100.0).toString()+"%");
                item.setFinishRate(String.format("%.3f", getLongRate(item.getFinishNum().doubleValue(),item.getTotalNum())*100.0).toString()+"%");
                item.setRLine(new BigDecimal(getLongRate(item.getTotalMoney().doubleValue(),item.getTotalNum())*1.0).setScale(3, RoundingMode.HALF_UP));

            }else{
                item.setRegisterRate("0%");
                item.setOnlineRate("0%");
                item.setFinishRate("0%");
                item.setRLine(new BigDecimal(0.0));
            }
            if(item.getCuCount()!=null && item.getCuCount().doubleValue()>0){
                item.setPersonMoney(String.format("%.3f",getLongRate(item.getTotalMoney().doubleValue(),Long.valueOf(item.getCuCount()))*1.0).toString());
            }else{
                item.setCuCount(0);
            }
            if(item.getTargetMoney()!=null && item.getTargetMoney().doubleValue()>0){
                item.setTargetRate(String.format("%.3f", item.getTotalMoney().doubleValue()/item.getTargetMoney().doubleValue()*100.0).toString()+"%");
            }else{
                item.setTargetRate("0%");
            }
            if(item.getMoney()!=null && item.getMoney().doubleValue()>0){
                item.setZroi(new BigDecimal(item.getTotalMoney().doubleValue()/item.getMoney().doubleValue()*1.0).setScale(3, RoundingMode.HALF_UP));
            }else{
                item.setZroi(new BigDecimal(0.0));
            }
            if(item.getRound1Order()!=null){
                item.setRound1Rate(getRoundRate(item.getRound1Order(),item.getTotalNum()));
                item.setRound1Unit(new BigDecimal(getRoundUnit(item.getRound1Money(),item.getRound1Order())).setScale(3, RoundingMode.HALF_UP));
            }
            if(item.getRound2Order()!=null){
                item.setRound2Rate(getRoundRate(item.getRound2Order(),item.getTotalNum()));
                item.setRound2Unit(new BigDecimal(getRoundUnit(item.getRound2Money(),item.getRound2Order())).setScale(3, RoundingMode.HALF_UP));
            }
            if(item.getRound3Order()!=null){
                item.setRound3Rate(getRoundRate(item.getRound3Order(),item.getTotalNum()));
                item.setRound3Unit(new BigDecimal(getRoundUnit(item.getRound3Money(),item.getRound3Order())).setScale(3, RoundingMode.HALF_UP));
            }
            if(item.getRound4Order()!=null){
                item.setRound4Rate(getRoundRate(item.getRound4Order(),item.getTotalNum()));
                item.setRound4Unit(new BigDecimal(getRoundUnit(item.getRound4Money(),item.getRound4Order())).setScale(3, RoundingMode.HALF_UP));
            }
            if(item.getRound5Order()!=null){
                item.setRound5Rate(getRoundRate(item.getRound5Order(),item.getTotalNum()));
                item.setRound5Unit(new BigDecimal(getRoundUnit(item.getRound5Money(),item.getRound5Order())).setScale(3, RoundingMode.HALF_UP));
            }
            if(item.getRound6Order()!=null){
                item.setRound6Rate(getRoundRate(item.getRound6Order(),item.getTotalNum()));
                item.setRound6Unit(new BigDecimal(getRoundUnit(item.getRound6Money(),item.getRound6Order())).setScale(3, RoundingMode.HALF_UP));
            }
            if(item.getRound7Order()!=null) {
                item.setRound7Rate(getRoundRate(item.getRound7Order(), item.getTotalNum()));
                item.setRound7Unit(new BigDecimal(getRoundUnit(item.getRound7Money(), item.getRound7Order())).setScale(3, RoundingMode.HALF_UP));
            }
            if (item.getRound8Order() != null) {
                item.setRound8Rate(getRoundRate(item.getRound8Order(), item.getTotalNum()));
                item.setRound8Unit(new BigDecimal(getRoundUnit(item.getRound8Money(), item.getRound8Order())).setScale(3, RoundingMode.HALF_UP));
            }
            if (item.getRound9Order() != null) {
                item.setRound9Rate(getRoundRate(item.getRound9Order(), item.getTotalNum()));
                item.setRound9Unit(new BigDecimal(getRoundUnit(item.getRound9Money(), item.getRound9Order())).setScale(3, RoundingMode.HALF_UP));
            }

        }
        ExcelUtil<CompanyTcmStatisticsExportVO> util = new ExcelUtil<CompanyTcmStatisticsExportVO>(CompanyTcmStatisticsExportVO.class);
        return util.exportExcel(list, "statisticsScheduleReport");
    }



    /**
     * 获取中医档期业绩报表详细信息
     */
    @PreAuthorize("@ss.hasPermi('company:tcmScheduleReport:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(companyTcmReportService.selectCompanyTcmReportById(id));
    }

    /**
     * 新增中医档期业绩报表
     */
    @PreAuthorize("@ss.hasPermi('company:tcmScheduleReport:add')")
    @Log(title = "中医档期业绩报表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CompanyTcmReport companyTcmReport)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        companyTcmReport.setCompanyId(loginUser.getCompany().getCompanyId());
        companyTcmReport.setCompanyUserId(loginUser.getUser().getUserId());
        int isOk=companyTcmReportService.insertCompanyTcmReport(companyTcmReport);
        if(isOk>0){
            return AjaxResult.success(companyTcmReport);
        }else{
            return  AjaxResult.error();
        }
    }

    /**
     * 修改中医档期业绩报表
     */
    @PreAuthorize("@ss.hasPermi('company:tcmScheduleReport:edit')")
    @Log(title = "中医档期业绩报表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CompanyTcmReport companyTcmReport)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        companyTcmReport.setCompanyId(loginUser.getCompany().getCompanyId());
        companyTcmReport.setUpdateUserId(loginUser.getUser().getUserId());
        return toAjax(companyTcmReportService.updateCompanyTcmReport(companyTcmReport));
    }



    /**
     * 查询中医档期列表
     */
    @GetMapping("/getScheduleList")
    public TableDataInfo getScheduleList()
    {
        startPage();
        List<CompanyTcmSchedule> list = companyTcmScheduleService.selectUseableScheduleList();
        return getDataTable(list);
    }

    /**
     * 查询中医档期列表
     */
    @GetMapping("/getAllScheduleList")
    public TableDataInfo getAllScheduleList()
    {
        startPage();
        List<CompanyTcmSchedule> list = companyTcmScheduleService.selectCompanyTcmScheduleList(new CompanyTcmSchedule());
        return getDataTable(list);
    }

    @GetMapping("/getTcmScheduleList")
    public R getCompanyTcmScheduleList()
    {
        CompanyTcmSchedule map = new CompanyTcmSchedule();
        map.setStatus(1L);
        List<CompanyTcmSchedule> list = companyTcmScheduleService.selectCompanyTcmScheduleList(map);
        return R.ok().put("data",list);
    }


    /**
     * 删除中医档期业绩报表
     */
    @PreAuthorize("@ss.hasPermi('company:tcmScheduleReport:remove')")
    @Log(title = "中医档期业绩报表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(companyTcmReportService.deleteCompanyTcmReportByIds(ids));
    }

    public String getRoundRate(Long roundOrder,Long totalNum){
        String sorStr="0%";
        if(totalNum.longValue()>0){
            sorStr=String.format("%.3f", roundOrder.doubleValue()/totalNum*100.0).toString()+"%";
        }
        return sorStr;
    }

    public double getRoundUnit(BigDecimal roundMoney,Long roundOrder){
        double sorNum=0;
        if(roundOrder.longValue()>0){
            sorNum=roundMoney.doubleValue()/roundOrder*1.0;
        }
        return sorNum;
    }

    public double getLongRate(double num1,Long num2){
        double sorNum=0;
        if(num2.longValue()>0){
            sorNum=num1/num2*1.0;
        }
        return sorNum;
    }

}
