package com.fs.hisStore.controller;

import cn.hutool.core.bean.BeanUtil;
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.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.framework.web.service.TokenService;
import com.fs.his.domain.FsUser;
import com.fs.his.service.IFsUserService;
import com.fs.hisStore.domain.FsStoreAfterSalesItemScrm;
import com.fs.hisStore.domain.FsStoreAfterSalesScrm;
import com.fs.hisStore.domain.FsStoreAfterSalesStatusScrm;
import com.fs.hisStore.domain.FsStoreOrderScrm;
import com.fs.hisStore.param.FsStoreAfterSalesAudit1Param;
import com.fs.hisStore.param.FsStoreAfterSalesAudit2Param;
import com.fs.hisStore.param.FsStoreAfterSalesCancelParam;
import com.fs.hisStore.param.FsStoreAfterSalesRefundParam;
import com.fs.hisStore.service.IFsStoreAfterSalesItemScrmService;
import com.fs.hisStore.service.IFsStoreAfterSalesScrmService;
import com.fs.hisStore.service.IFsStoreAfterSalesStatusScrmService;
import com.fs.hisStore.service.IFsStoreOrderScrmService;
import com.fs.hisStore.vo.FsStoreAfterSalesVO;
import com.fs.hisStore.vo.FsStoreOrderItemExportRefundZMVO;
import com.fs.hisStore.vo.FsStoreOrderItemExportZMVO;
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.math.BigDecimal;
import java.text.ParseException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 售后记录Controller
 *
 * @author fs
 * @date 2022-03-15
 */
@RestController
@RequestMapping("/store/store/storeAfterSales")
public class FsStoreAfterSalesScrmController extends BaseController
{
    @Autowired
    private IFsStoreOrderScrmService fsStoreOrderService;
    @Autowired
    private IFsUserService userService;
    @Autowired
    private IFsStoreAfterSalesScrmService fsStoreAfterSalesService;
    @Autowired
    private IFsStoreAfterSalesItemScrmService fsStoreAfterSalesItemService;
    @Autowired
    private IFsStoreAfterSalesStatusScrmService storeAfterSalesStatusService;

    @Autowired
    private TokenService tokenService;

    @Value("${cloud_host.company_name}")
    private String signProjectName;

    /**
     * 查询售后记录列表
     */
    @PreAuthorize("@ss.hasPermi('store:storeAfterSales:list')")
    @GetMapping("/list")
    public TableDataInfo list(FsStoreAfterSalesScrm fsStoreAfterSales)
    {
        startPage();
        List<FsStoreAfterSalesVO> list = fsStoreAfterSalesService.selectFsStoreAfterSalesListVO(fsStoreAfterSales);
        for (FsStoreAfterSalesVO vo : list){
            vo.setUserPhone(ParseUtils.parsePhone(vo.getUserPhone()));
        }
        return getDataTable(list);
    }

    /**
     * 导出售后记录列表
     */
    @PreAuthorize("@ss.hasPermi('store:storeAfterSales:export')")
    @Log(title = "售后记录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FsStoreAfterSalesScrm fsStoreAfterSales)
    {
        if (StringUtils.isNotEmpty(fsStoreAfterSales.getBeginTime()) && StringUtils.isNotEmpty(fsStoreAfterSales.getEndTime())){
            fsStoreAfterSales.setBeginTime(null);
            fsStoreAfterSales.setEndTime(null);
        }
//        Boolean a = fsStoreAfterSalesService.isEntityNull(fsStoreAfterSales);
        if (fsStoreAfterSalesService.isEntityNull(fsStoreAfterSales) && Objects.isNull(fsStoreAfterSales.getParams())){
            return AjaxResult.error("请筛选数据导出");
        }

        List<FsStoreAfterSalesVO> list = fsStoreAfterSalesService.selectFsStoreAfterSalesListVOExport(fsStoreAfterSales);
        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.getOrderCreateTime());
                            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 (FsStoreAfterSalesVO vo : list){
            vo.setUserPhone(ParseUtils.parsePhone(vo.getUserPhone()));
        }
        ExcelUtil<FsStoreAfterSalesVO> util = new ExcelUtil<FsStoreAfterSalesVO>(FsStoreAfterSalesVO.class);
        return util.exportExcel(list, "退款订单导出");
    }
    /**
     * 获取售后记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('store:storeAfterSales:query')")
    @GetMapping(value = "/{id}")
    public R getInfo(@PathVariable("id") Long id)
    {
        FsStoreAfterSalesScrm afterSales=fsStoreAfterSalesService.selectFsStoreAfterSalesById(id);
        FsStoreAfterSalesItemScrm map=new FsStoreAfterSalesItemScrm();
        map.setStoreAfterSalesId(id);
        List<FsStoreAfterSalesItemScrm> items=fsStoreAfterSalesItemService.selectFsStoreAfterSalesItemList(map);
        FsStoreAfterSalesStatusScrm statusMap=new FsStoreAfterSalesStatusScrm();
        statusMap.setStoreAfterSalesId(id);
        List<FsStoreAfterSalesStatusScrm> logs=storeAfterSalesStatusService.selectFsStoreAfterSalesStatusList(statusMap);
        FsUser user=userService.selectFsUserById(afterSales.getUserId());
        if (user != null){
            user.setPhone(ParseUtils.parsePhone(user.getPhone()));
        }
        FsStoreOrderScrm order=fsStoreOrderService.selectFsStoreOrderByOrderCode(afterSales.getOrderCode());
        return R.ok().put("afterSales",afterSales).put("items",items).put("logs",logs).put("user",user).put("order",order);
    }

    /**
     * 新增售后记录
     */
    @PreAuthorize("@ss.hasPermi('store:storeAfterSales:add')")
    @Log(title = "售后记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsStoreAfterSalesScrm fsStoreAfterSales)
    {
        return toAjax(fsStoreAfterSalesService.insertFsStoreAfterSales(fsStoreAfterSales));
    }

    /**
     * 修改售后记录
     */
    @PreAuthorize("@ss.hasPermi('store:storeAfterSales:edit')")
    @Log(title = "售后记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsStoreAfterSalesScrm fsStoreAfterSales)
    {
        if ((!"".equals(fsStoreAfterSales.getDeliveryName()) && !"".equals(fsStoreAfterSales.getDeliverySn())) || (fsStoreAfterSales.getDeliveryName() == null && fsStoreAfterSales.getDeliverySn() == null)){
            fsStoreAfterSales.setStatus(2);
        }
        return toAjax(fsStoreAfterSalesService.updateDelivery(fsStoreAfterSales));
    }

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


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

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

    @GetMapping("/getStoreAfterSales")
    public R getStoreAfterSales(@RequestParam("orderCode") String orderCode)
    {
        List<FsStoreAfterSalesVO> vo = fsStoreAfterSalesService.selectFsStoreAfterSalesVOByOrderCode(orderCode);
        return R.ok().put("data",vo);
    }

}
