package com.fs.live.controller;

import cn.hutool.core.date.DateTime;
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.domain.model.LoginUser;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.ParseUtils;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.framework.web.service.TokenService;
import com.fs.his.domain.FsStoreAfterSalesLogs;
import com.fs.his.domain.FsUser;
import com.fs.his.enums.FsStoreAfterSalesStatusEnum;
import com.fs.his.service.IFsUserService;
import com.fs.hisStore.vo.FsStoreOrderItemExportRefundZMVO;
import com.fs.live.domain.LiveAfterSales;
import com.fs.live.domain.LiveAfterSalesItem;
import com.fs.live.domain.LiveAfterSalesLogs;
import com.fs.live.domain.LiveOrder;
import com.fs.live.param.LiveAfterSalesAudit1Param;
import com.fs.live.param.LiveAfterSalesAudit2Param;
import com.fs.live.param.LiveAfterSalesCancelParam;
import com.fs.live.param.LiveAfterSalesRefundParam;
import com.fs.live.service.ILiveAfterSalesItemService;
import com.fs.live.service.ILiveAfterSalesLogsService;
import com.fs.live.service.ILiveAfterSalesService;
import com.fs.live.service.ILiveOrderService;
import com.fs.live.vo.LiveAfterSalesVo;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 售后记录Controller
 *
 * @author fs
 * @date 2025-07-08
 */
@RestController
@RequestMapping("/live/liveAfterSales")
public class LiveAfterSalesController extends BaseController
{
    @Autowired
    private ILiveAfterSalesService liveAfterSalesService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ILiveAfterSalesItemService liveAfterSalesItemService;
    @Autowired
    private ILiveAfterSalesLogsService liveAfterSalesLogsService;
    @Autowired
    private IFsUserService userService;
    @Autowired
    private ILiveOrderService orderService;
    @Value("${cloud_host.company_name}")
    private String signProjectName;


    /**
     * 获取售后记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('live:liveAfterSales:query')")
    @GetMapping(value = "/{id}")
    public R getInfo(@PathVariable("id") Long id)
    {
        LiveAfterSales liveAfterSales = liveAfterSalesService.selectLiveAfterSalesById(id);
        if(liveAfterSales==null) return R.error("售后记录不存在");
        List<LiveAfterSalesItem> list = liveAfterSalesItemService.selectLiveAfterSalesItemByAfterId(id);
        List<LiveAfterSalesLogs> logList = liveAfterSalesLogsService.selectLiveAfterSalesLogsByAfterId(id);
        FsUser user=userService.selectFsUserById(liveAfterSales.getUserId());
        if (user != null) {
            user.setPhone(ParseUtils.parsePhone(user.getPhone()));
        }
        LiveOrder liveOrder = orderService.selectLiveOrderByOrderId(String.valueOf(liveAfterSales.getOrderId()));
        return R.ok().put("afterSales",liveAfterSales).put("items",list).put("logs",logList).put("user",user).put("order",liveOrder);

    }

    /**
     * 查询售后记录列表
     */
    @PreAuthorize("@ss.hasPermi('live:liveAfterSales:list')")
    @GetMapping("/list")
    public TableDataInfo list(LiveAfterSalesVo liveAfterSales)
    {
        startPage();
        // 将productName映射到productNameQuery用于查询
        if (liveAfterSales.getProductName() != null && !liveAfterSales.getProductName().isEmpty()) {
            liveAfterSales.setProductNameQuery(liveAfterSales.getProductName());
        }
        List<LiveAfterSalesVo> list = liveAfterSalesService.selectLiveAfterSalesVoList(liveAfterSales);
        for (LiveAfterSalesVo liveAfterSalesVo : list) {
            liveAfterSalesVo.setUserPhone(ParseUtils.parsePhone(liveAfterSalesVo.getUserPhone()));
        }
        return getDataTable(list);
    }

    /**
     * 导出售后记录列表
     */
    @PreAuthorize("@ss.hasPermi('live:liveAfterSales:export')")
    @Log(title = "售后记录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(LiveAfterSalesVo liveAfterSales)
    {
        PageHelper.clearPage();
        PageHelper.startPage(1, 10000, "");
        List<LiveAfterSalesVo> list = liveAfterSalesService.selectLiveAfterSalesVoListExport(liveAfterSales);
        if("北京卓美".equals(signProjectName)){
            List<FsStoreOrderItemExportRefundZMVO> zmvoList = list.stream()
                    .map(vo -> {
                        FsStoreOrderItemExportRefundZMVO zmvo = new FsStoreOrderItemExportRefundZMVO();
                        try {
                            zmvo.setPayCode(vo.getPayCode());
                            zmvo.setOrderCode(vo.getOrderCode());
                            zmvo.setStatus(vo.getOrderStatus().toString());
                            zmvo.setUserId(vo.getUserId());
                            zmvo.setProductName(vo.getProductName());
                            zmvo.setBarCode(vo.getProductBarCode());
                            zmvo.setSku(vo.getSku());
                            zmvo.setNum(vo.getNum());
                            zmvo.setPrice(vo.getPrice());
                            zmvo.setCost(vo.getCost());
//                            zmvo.setFPrice("");
                            zmvo.setPayMoney(vo.getPayMoney());
                            zmvo.setPayPostage(vo.getTotalPostage());
                            zmvo.setCateName(vo.getCateName());
                            zmvo.setRealName(vo.getUserName());
                            zmvo.setUserPhone(vo.getUserPhone());
                            zmvo.setUserAddress(vo.getUserAddress());
                            zmvo.setCreateTime(vo.getCreateTime());
                            zmvo.setPayTime(vo.getOrderPayTime());
                            zmvo.setDeliverySn(vo.getOrderDeliverySn());
                            zmvo.setDeliveryName(vo.getOrderDeliveryName());
                            zmvo.setDeliveryId(vo.getOrderDeliveryId());
                            zmvo.setCompanyName(vo.getCompanyName());
                            zmvo.setCompanyUserNickName(vo.getCompanyUserNickName());
                            zmvo.setRefundTime(vo.getCreateTime());
//                            zmvo.setAfterSalesNumber
                            zmvo.setRefundMoney(vo.getRefundAmount());
                            zmvo.setBankTransactionId(vo.getBankTransactionId());
                            zmvo.setReasons(vo.getReasons());
                            zmvo.setExplains(vo.getExplains());
                        } catch (Exception e) {
                            // 处理异常
                            e.printStackTrace();
                        }
                        return zmvo;
                    })
                    .collect(Collectors.toList());
            for (FsStoreOrderItemExportRefundZMVO vo : zmvoList){
                vo.setUserPhone(ParseUtils.parsePhone(vo.getUserPhone()));
            }
            ExcelUtil<FsStoreOrderItemExportRefundZMVO> util = new ExcelUtil<FsStoreOrderItemExportRefundZMVO>(FsStoreOrderItemExportRefundZMVO.class);
            return util.exportExcel(zmvoList, "退款订单导出");
        }
        for (LiveAfterSalesVo liveAfterSalesVo : list) {
            liveAfterSalesVo.setUserPhone(liveAfterSalesVo.getUserPhone() == null ? "" : liveAfterSalesVo.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
            liveAfterSalesVo.setPhoneNumber(liveAfterSalesVo.getPhoneNumber() == null ? "" : liveAfterSalesVo.getPhoneNumber().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
        }
        ExcelUtil<LiveAfterSalesVo> util = new ExcelUtil<LiveAfterSalesVo>(LiveAfterSalesVo.class);
        return util.exportExcel(list, "销售直播退款订单数据");
    }


    /**
     * 新增售后记录
     */
    @PreAuthorize("@ss.hasPermi('live:liveAfterSales:add')")
    @Log(title = "售后记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LiveAfterSales liveAfterSales)
    {
        return toAjax(liveAfterSalesService.insertLiveAfterSales(liveAfterSales));
    }

    /**
     * 修改售后记录
     */
    @PreAuthorize("@ss.hasPermi('live:liveAfterSales:edit')")
    @Log(title = "售后记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LiveAfterSales liveAfterSales)
    {

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        //操作记录
        LiveAfterSalesLogs logs = new LiveAfterSalesLogs();
        logs.setChangeTime(new DateTime());
        logs.setChangeType(2);
        logs.setOperator(loginUser.getUser().getNickName());
        logs.setStoreAfterSalesId(liveAfterSales.getId());
        logs.setChangeMessage(FsStoreAfterSalesStatusEnum.STATUS_2.getDesc());
        liveAfterSales.setStatus(FsStoreAfterSalesStatusEnum.STATUS_2.getValue());
        liveAfterSalesLogsService.insertLiveAfterSalesLogs(logs);
        return toAjax(liveAfterSalesService.updateLiveAfterSales(liveAfterSales));
    }

    /**
     * 删除售后记录
     */
    @PreAuthorize("@ss.hasPermi('live:liveAfterSales:remove')")
    @Log(title = "售后记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(liveAfterSalesService.deleteLiveAfterSalesByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('store:storeAfterSales:audit1')")
    @PostMapping("/audit1")
    //平台审核
    public R audit1(@RequestBody LiveAfterSalesAudit1Param param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setOperator(loginUser.getUser().getNickName());
        return liveAfterSalesService.audit1(param);
    }

    @PreAuthorize("@ss.hasPermi('store:storeAfterSales:audit2')")
    @PostMapping("/audit2")
    //仓库审核
    public R audit2(@RequestBody LiveAfterSalesAudit2Param param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setOperator(loginUser.getUser().getNickName());
        return liveAfterSalesService.audit2(param);
    }
    //财务审核
    @PreAuthorize("@ss.hasPermi('store:storeAfterSales:refund')")
    @PostMapping("/refund")
    public R refund(@RequestBody LiveAfterSalesRefundParam param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setOperator(loginUser.getUser().getNickName());
        return liveAfterSalesService.refundMoney(param);
    }
    //平台撤销
    @PreAuthorize("@ss.hasPermi('store:storeAfterSales:cancel')")
    @PostMapping("/cancel")
    public R cancel(@RequestBody LiveAfterSalesCancelParam param) throws ParseException {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setOperator(loginUser.getUser().getNickName());
        return liveAfterSalesService.cancel(param);
    }

    @PreAuthorize("@ss.hasPermi('store:storeAfterSales:refund')")
    @PostMapping("/handleImmediatelyRefund")
    public R handleImmediatelyRefund(@RequestBody LiveAfterSalesRefundParam param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setOperator(loginUser.getUser().getNickName());
        return liveAfterSalesService.handleImmediatelyRefund(param.getOrderId());
    }

}
