package com.fs.company.controller.store;

import com.fs.common.annotation.DataScope;
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.ParseUtils;
import com.fs.common.utils.StringUtils;
import com.fs.framework.security.LoginUser;
import com.fs.framework.security.SecurityUtils;
import com.fs.his.domain.FsExportTask;
import com.fs.his.domain.FsPackageOrder;
import com.fs.his.param.FsPackageOrderAddParam;
import com.fs.his.param.FsPackageOrderParam;
import com.fs.his.service.IFsExportTaskService;
import com.fs.his.service.IFsPackageOrderService;
import com.fs.his.utils.PhoneUtil;
import com.fs.his.vo.FsPackageOrderListVO;
import com.fs.his.vo.FsPackageOrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;
import java.util.Date;
import java.util.List;

/**
 * 套餐订单Controller
 *
 * @author fs
 * @date 2023-08-25
 */
@RestController
@RequestMapping("/store/packageOrder")
public class FsPackageOrderController extends BaseController
{
    @Autowired
    private IFsPackageOrderService fsPackageOrderService;
    @Autowired
    private IFsExportTaskService exportTaskService;
    /**
     * 查询套餐订单列表
     */
    @PreAuthorize("@ss.hasPermi('store:packageOrder:list')")
    @GetMapping("/list")
    @DataScope(deptAlias = "cu",userAlias = "cu")
    public TableDataInfo list(FsPackageOrderParam  fsPackageOrder)
    {
        startPage();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        fsPackageOrder.setCompanyId(loginUser.getCompany().getCompanyId());
        List<FsPackageOrderListVO> list = fsPackageOrderService.selectFsPackageOrderListVO(fsPackageOrder);
        return getDataTable(list);
    }

    /**
     * 导出套餐订单列表
     */
    @PreAuthorize("@ss.hasPermi('store:packageOrder:export')")
    @Log(title = "套餐订单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FsPackageOrderParam fsPackageOrder)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        fsPackageOrder.setCompanyId(loginUser.getCompany().getCompanyId());
        Long userId = loginUser.getUser().getUserId();
        logger.info("导出套餐订单:"+ userId);
        if (fsPackageOrderService.isEntityNull(fsPackageOrder)){
            return AjaxResult.error("请筛选数据导出");
        }
        Integer exportType1 = exportTaskService.isExportType2(userId);
        if (exportType1>0){
            return AjaxResult.error("你已经有正在导出的任务");
        }
        Long count =fsPackageOrderService.selectFsPackageOrderExcelListVOCount(fsPackageOrder);
        if (count>30000){
            return AjaxResult.error("导出数据不可超过3w条");
        }
        FsExportTask task=new FsExportTask();
        task.setTaskType(2);
        task.setStatus(0);
        task.setStartTime(new Date());
        task.setRemark("药品订单导出");
        task.setSysType(2);
        task.setCompanyUserId(userId);
        exportTaskService.insertFsExportTask(task);
        fsPackageOrder.setTaskId(task.getTaskId());
        fsPackageOrderService.exportData(fsPackageOrder);
        return new AjaxResult(200,"后台正在导出,请等待...任务ID:"+task.getTaskId(),task.getTaskId());

    }


    /**
     * 查询套餐订单列表
     */
    @PreAuthorize("@ss.hasPermi('store:packageOrder:myList')")
    @GetMapping("/myList")
    public TableDataInfo myList(FsPackageOrderParam  fsPackageOrder)
    {
        startPage();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        fsPackageOrder.setCompanyId(loginUser.getCompany().getCompanyId());
        fsPackageOrder.setCompanyUserId(loginUser.getUser().getUserId());
        List<FsPackageOrderListVO> list = fsPackageOrderService.selectFsPackageOrderListVO(fsPackageOrder);
        return getDataTable(list);
    }

    /**
     * 导出套餐订单列表
     */
    @PreAuthorize("@ss.hasPermi('store:packageOrder:myExport')")
    @Log(title = "套餐订单", businessType = BusinessType.EXPORT)
    @GetMapping("/myExport")
    public AjaxResult myExport(FsPackageOrderParam fsPackageOrder)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        fsPackageOrder.setCompanyId(loginUser.getCompany().getCompanyId());
        Long userId = loginUser.getUser().getUserId();
        fsPackageOrder.setCompanyUserId(userId);
        logger.info("导出订单:"+ userId);
        if (fsPackageOrderService.isEntityNull(fsPackageOrder)){
            return AjaxResult.error("请筛选数据导出");
        }
        Integer exportType1 = exportTaskService.isExportType2(userId);
        if (exportType1>0){
            return AjaxResult.error("你已经有正在导出的任务");
        }
        Long count =fsPackageOrderService.selectFsPackageOrderExcelListVOCount(fsPackageOrder);
        if (count>30000){
            return AjaxResult.error("导出数据不可超过3w条");
        }
        FsExportTask task=new FsExportTask();
        task.setTaskType(2);
        task.setStatus(0);
        task.setStartTime(new Date());
        task.setRemark("药品订单导出");
        task.setSysType(2);
        task.setCompanyUserId(userId);
        exportTaskService.insertFsExportTask(task);
        fsPackageOrder.setTaskId(task.getTaskId());
        fsPackageOrderService.exportData(fsPackageOrder);
        return new AjaxResult(200,"后台正在导出,请等待...任务ID:"+task.getTaskId(),task.getTaskId());

    }



    /**
     * 获取套餐订单详细信息
     */
    @GetMapping(value = "/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") Long orderId)
    {
        FsPackageOrderVO fsPackageOrderVO = fsPackageOrderService.selectFsPackageOrderByOrderIdVO(orderId);
        if(StringUtils.isNotBlank(fsPackageOrderVO.getPhone()) && fsPackageOrderVO.getPhone().trim().length() > 11) {
            fsPackageOrderVO.setPhone(PhoneUtil.decryptPhoneMk(fsPackageOrderVO.getPhone()));
        }else if (StringUtils.isNotBlank(fsPackageOrderVO.getPhone()) && fsPackageOrderVO.getPhone().trim().length() == 11){
            fsPackageOrderVO.setPhone(ParseUtils.parsePhone(fsPackageOrderVO.getPhone()));
        }

        return AjaxResult.success(fsPackageOrderVO);
    }

    @GetMapping(value = "/queryPhone/{orderId}")
    @PreAuthorize("@ss.hasPermi('store:packageOrder:queryPhone')")
    @Log(title = "查看套餐电话", businessType = BusinessType.GRANT)
    public R getPhone(@PathVariable("orderId") Long orderId)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser.getUser().getUserType().equals("00")){
            FsPackageOrderVO order = fsPackageOrderService.selectFsPackageOrderByOrderIdVO(orderId);
            String userPhone = order.getPhone();
            if (StringUtils.isNotBlank(userPhone) && userPhone.trim().length() > 11) {
                userPhone = PhoneUtil.decryptPhone(userPhone);
            }
            return R.ok().put("userPhone",userPhone);
        }
        return R.error("无权查看");
    }

    /**
     * 新增套餐订单
     */
    @PreAuthorize("@ss.hasPermi('store:packageOrder:add')")
    @Log(title = "套餐订单", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody FsPackageOrderAddParam fsPackageOrder)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        fsPackageOrder.setCompanyId(loginUser.getCompany().getCompanyId());
        fsPackageOrder.setCompanyUserId(loginUser.getUser().getUserId());
        return fsPackageOrderService.addPackageOrder(fsPackageOrder);
    }

    /**
     * 修改套餐订单
     */
    @PreAuthorize("@ss.hasPermi('store:packageOrder:edit')")
    @Log(title = "套餐订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsPackageOrder fsPackageOrder)
    {
        return toAjax(fsPackageOrderService.updateFsPackageOrder(fsPackageOrder));
    }
    @GetMapping("/payment/{orderId}")
    public AjaxResult getPayInfo(@PathVariable("orderId") Long orderId)
    {
        return AjaxResult.success(fsPackageOrderService.selectFsPackagePaymentByOrderId(orderId));
    }
    /**
     * 删除套餐订单
     */
    @PreAuthorize("@ss.hasPermi('store:packageOrder:remove')")
    @Log(title = "套餐订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{orderIds}")
    public AjaxResult remove(@PathVariable Long[] orderIds)
    {
        return toAjax(fsPackageOrderService.deleteFsPackageOrderByOrderIds(orderIds));
    }


    @PreAuthorize("@ss.hasPermi('his:packageOrder:refund')")
    @GetMapping("inquiryRefund/{orderId}")
    public AjaxResult inquiryRefund(@PathVariable("orderId") Long orderId)
    {
        return AjaxResult.success(fsPackageOrderService.PackageInquiryOrderRefund(orderId));
    }

    @PreAuthorize("@ss.hasPermi('his:packageOrder:refund')")
    @GetMapping("storeRefund/{orderId}")
    public AjaxResult storeRefund(@PathVariable("orderId") Long orderId)
    {
        return AjaxResult.success(fsPackageOrderService.PackageStoreOrderRefund(orderId));
    }


    @GetMapping("/getWxaCodeUnLimit/{orderId}")
    public AjaxResult getWxaCodeUnLimit(@PathVariable("orderId") Long orderId)
    {

        byte[] bytes = fsPackageOrderService.getWxaCodeUnLimit(orderId);
        String base64 = Base64.getEncoder().encodeToString(bytes);
        return AjaxResult.success("成功",base64);
    }
}
