package com.fs.store.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
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.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.core.security.LoginUser;
import com.fs.core.web.service.TokenService;
import com.fs.crm.domain.CrmCustomer;
import com.fs.crm.service.ICrmCustomerService;
import com.fs.store.domain.*;
import com.fs.store.dto.ExpressInfoDTO;
import com.fs.store.dto.StoreOrderProductDTO;
import com.fs.store.enums.OrderLogEnum;
import com.fs.store.enums.ShipperCodeEnum;
import com.fs.store.param.FsStoreOrderBindCustomerParam;
import com.fs.store.param.FsStoreOrderCreateUserParam;
import com.fs.store.param.FsStoreOrderFinishParam;
import com.fs.store.param.FsStoreOrderParam;
import com.fs.store.service.*;
import com.fs.store.vo.FsStoreOrderExportVO;
import com.fs.store.vo.FsStoreOrderItemExportVO;
import com.fs.store.vo.FsStoreOrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 订单Controller
 *
 * @author fs
 * @date 2022-03-15
 */

@RestController
@RequestMapping("/store/storeOrder")
public class FsStoreOrderController extends BaseController
{
    @Autowired
    private IFsExpressService expressService;
    @Autowired
    private IFsStoreOrderService fsStoreOrderService;
    @Autowired
    private IFsStoreOrderItemService orderItemService;

    @Autowired
    private IFsUserService userService;

    @Autowired
    private IFsStoreOrderStatusService orderStatusService;
    @Autowired
    private IFsStorePaymentService fsStorePaymentService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ICrmCustomerService crmCustomerService;
    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('store:storeOrder:list')")
    @GetMapping("/list")
    @DataScope(deptAlias = "cu",userAlias = "cu")
    public TableDataInfo list(FsStoreOrderParam param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        startPage();
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getPayTimeRange())){
            param.setPayTimeList(param.getPayTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
            param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
        }
        List<FsStoreOrderVO> list = fsStoreOrderService.selectFsStoreOrderListVO(param);
        return getDataTable(list);
    }


    @GetMapping("/allList")
    public TableDataInfo allList(FsStoreOrderParam param)
    {
        startPage();
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getPayTimeRange())){
            param.setPayTimeList(param.getPayTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
            param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
        }
        List<FsStoreOrderVO> list = fsStoreOrderService.selectFsStoreOrderAllListVO(param);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('store:storeOrder:myList')")
    @GetMapping("/myList")
    public TableDataInfo myList(FsStoreOrderParam param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        param.setCompanyUserId(loginUser.getUser().getUserId());
        startPage();
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getPayTimeRange())){
            param.setPayTimeList(param.getPayTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
            param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
        }
        List<FsStoreOrderVO> list = fsStoreOrderService.selectFsStoreOrderListVO(param);
        return getDataTable(list);
    }


    @PreAuthorize("@ss.hasPermi('store:storeOrder:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @DataScope(deptAlias = "cu",userAlias = "cu")
    public AjaxResult export (FsStoreOrderParam param)
    {
        if (param.getBeginTime().equals("") && param.getEndTime().equals("")){
            param.setBeginTime(null);
            param.setEndTime(null);
        }
        if (fsStoreOrderService.isEntityNull(param)){
            return AjaxResult.error("请筛选数据导出");
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getPayTimeRange())){
            param.setPayTimeList(param.getPayTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
            param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
        }
        List<FsStoreOrderExportVO> list = fsStoreOrderService.selectFsStoreOrderListVOByExport(param);
        //对手机号脱敏
        if(list!=null){
            for(FsStoreOrderExportVO vo:list){
                if (vo.getPhone() != null) {
                    vo.setPhone(vo.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }
                if (vo.getUserPhone() != null) {
                    vo.setUserPhone(vo.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }
                if (vo.getUserAddress()!=null){
                    vo.setUserAddress(ParseUtils.parseAddress(vo.getUserAddress()));
                }

            }
        }
        ExcelUtil<FsStoreOrderExportVO> util = new ExcelUtil<FsStoreOrderExportVO>(FsStoreOrderExportVO.class);
        return util.exportExcel(list,"订单数据");
    }


    /**
     * 获取订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('store:storeOrder:query')")
    @GetMapping(value = "/{id}")
    public R getInfo(@PathVariable("id") Long id)
    {
        FsStoreOrder order=fsStoreOrderService.selectFsStoreOrderById(id);
        order.setUserPhone(ParseUtils.parsePhone(order.getUserPhone()));
        order.setUserAddress(ParseUtils.parseAddress(order.getUserAddress()));
        FsUser user=userService.selectFsUserById(order.getUserId());
        user.setPhone(ParseUtils.parsePhone(user.getPhone()));
        FsStoreOrderItem itemMap=new FsStoreOrderItem();
        itemMap.setOrderId(order.getId());
        List<FsStoreOrderItem> items=orderItemService.selectFsStoreOrderItemList(itemMap);
        FsStoreOrderStatus statusMap=new FsStoreOrderStatus();
        statusMap.setOrderId(order.getId());
        List<FsStoreOrderStatus> logs=orderStatusService.selectFsStoreOrderStatusList(statusMap);
        List<FsStorePayment> payments=fsStorePaymentService.selectFsStorePaymentByOrderId(order.getId());

        CrmCustomer customer=null;
        if(order.getCustomerId()!=null&&order.getCustomerId()>0){
            customer=crmCustomerService.selectCrmCustomerById(order.getCustomerId());
        }
        return R.ok().put("order", order).put("items", items).put("logs",logs).put("user",user).put("customer",customer).put("payments",payments) ;
    }

    @GetMapping(value = "/queryAddress/{id}")
    @PreAuthorize("@ss.hasPermi('store:storeOrder:queryAddress')")
    public R getAddress(@PathVariable("id") Long id)
    {
        FsStoreOrder order = fsStoreOrderService.selectFsStoreOrderById(id);
        String address = order.getUserAddress();
        return R.ok().put("address",address);
    }

    @GetMapping(value = "/queryPhone/{id}")
    @PreAuthorize("@ss.hasPermi('store:storeOrder:queryPhone')")
    @Log(title = "查看电话", businessType = BusinessType.GRANT)
    public R getPhone(@PathVariable("id") Long id)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser.getUser().getUserType().equals("00")){
            FsStoreOrder order = fsStoreOrderService.selectFsStoreOrderById(id);
            String userPhone = order.getUserPhone();
            return R.ok().put("userPhone",userPhone);
        }
        return R.error("无权查看");
    }

    @PreAuthorize("@ss.hasPermi('store:storeOrder:express')")
    @GetMapping(value = "/getExpress/{id}")
    public R getExpress(@PathVariable("id") Long id)
    {
        FsStoreOrder order=fsStoreOrderService.selectFsStoreOrderById(id);
        ExpressInfoDTO expressInfoDTO=null;
        if(StringUtils.isNotEmpty(order.getDeliveryId())){

            String lastFourNumber = "";
            if (order.getDeliverySn().equals(ShipperCodeEnum.SF.getValue())) {
                lastFourNumber = order.getUserPhone();
                if (lastFourNumber.length() == 11) {
                    lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
                }
            }
            expressInfoDTO=expressService.getExpressInfo(order.getOrderCode(),order.getDeliverySn(),order.getDeliveryId(),lastFourNumber);
        }
        return R.ok().put("data",expressInfoDTO);
    }

    /**
     * 新增订单
     */

    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsStoreOrder fsStoreOrder)
    {
        return toAjax(fsStoreOrderService.insertFsStoreOrder(fsStoreOrder));
    }

    /**
     * 修改订单
     */
    @PreAuthorize("@ss.hasPermi('store:storeOrder:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsStoreOrder fsStoreOrder)
    {
        return toAjax(fsStoreOrderService.updateFsStoreOrder(fsStoreOrder));
    }

    /**
     * 删除订单
     */
    @PreAuthorize("@ss.hasPermi('store:storeOrder:remove')")
    @Log(title = "订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(fsStoreOrderService.deleteFsStoreOrderByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('store:storeOrder:add')")
    @PostMapping("/createUserOrder")
    public R createUserOrder(@Validated @RequestBody FsStoreOrderCreateUserParam param, HttpServletRequest request){

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        param.setCompanyUserId(loginUser.getUser().getUserId());
        return fsStoreOrderService.createUserOrder(param);
    }


    @PreAuthorize("@ss.hasPermi('store:storeOrder:editPayPrice')")
    @PostMapping("/editPayPrice")
    public R editPayPrice(@RequestBody FsStoreOrder fsStoreOrder)
    {

        if(fsStoreOrderService.updateFsStoreOrder(fsStoreOrder)>0){
            //写日志
            orderStatusService.create(fsStoreOrder.getId(), OrderLogEnum.ORDER_EDIT.getValue(),
                    OrderLogEnum.ORDER_EDIT.getDesc());
            return R.ok("操作成功");
        }
        else{
            return R.error("操作失败");
        }

    }

    @PreAuthorize("@ss.hasPermi('store:storeOrder:finishOrder')")
    @PostMapping("/finishOrder")
    public R finishOrder(@Validated @RequestBody FsStoreOrderFinishParam param, HttpServletRequest request){
        return fsStoreOrderService.finishOrder(param.getOrderId());
    }

    @PreAuthorize("@ss.hasPermi('store:storeOrder:exportItems')")
    @Log(title = "订单明细导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exportItems")
    public AjaxResult exportItems(FsStoreOrderParam param)
    {
        if (param.getBeginTime().equals("") && param.getEndTime().equals("")){
            param.setBeginTime(null);
            param.setEndTime(null);
        }
        if (fsStoreOrderService.isEntityNull(param)){
            return AjaxResult.error("请筛选数据导出");
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId());

        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getPayTimeRange())){
            param.setPayTimeList(param.getPayTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
            param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
        }

        List<FsStoreOrderItemExportVO> list=orderItemService.selectFsStoreOrderItemListExportVO(param);
        //对手机号脱敏
        if(list!=null){
            for(FsStoreOrderItemExportVO vo:list){
                if(vo.getUserPhone()!=null){
                    String phone = vo.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{1})", "$1****$2");
                    vo.setUserPhone(phone);
                }
                if (vo.getUserAddress()!=null){
                    vo.setUserAddress(ParseUtils.parseAddress(vo.getUserAddress()));
                }
                if(!StringUtils.isEmpty(vo.getJsonInfo())){
                    try {
                        StoreOrderProductDTO orderProductDTO = JSONObject.parseObject(vo.getJsonInfo(), StoreOrderProductDTO.class);
                        BeanUtil.copyProperties(orderProductDTO,vo);
                    }
                    catch (Exception e){
                    }
                }
            }
        }
        ExcelUtil<FsStoreOrderItemExportVO> util = new ExcelUtil<FsStoreOrderItemExportVO>(FsStoreOrderItemExportVO.class);
        return util.exportExcel(list, "订单明细数据");
    }


    @GetMapping("/getCustomerOrderList")
    public TableDataInfo getCustomerOrderList(FsStoreOrderParam param) {
        startPage();
        List<FsStoreOrderVO> list = fsStoreOrderService.selectFsCustomerStoreOrderListVO(param);
        if (list != null) {
            for (FsStoreOrderVO vo : list) {
                if(vo.getPhone()!=null){
                    vo.setPhone(vo.getPhone().replaceAll("(\\d{3})\\d*(\\d{1})", "$1****$2"));
                    vo.setUserPhone(vo.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{1})", "$1****$2"));
                }

            }
        }
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('store:storeOrder:bindCustomer')")
    @PostMapping("/bindCustomer")
    public R bindCustomer(@RequestBody FsStoreOrderBindCustomerParam param)
    {
        if(param.getCustomerIds().length>1){
            return R.error("只能关联一个客户");
        }
        for(Long customerId:param.getCustomerIds()){
            FsStoreOrder order=new FsStoreOrder();
            order.setId(param.getOrderId());
            order.setCustomerId(customerId);
            fsStoreOrderService.updateFsStoreOrder(order);
            //更新CRM客户订单数
            crmCustomerService.updateBuyCount(customerId);
        }
        return R.ok("操作成功");

    }

    @Log(title = "订单凭证上传", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('store:storeOrder:uploadCredentials')")
    @PostMapping("/uploadCredentials")
    public R UploadCredentials(@RequestBody FsStoreOrder order)
    {
//        String[] imageUrls = order.getCredentials().split(",");
        if (order.getCertificates() == null ){
            return R.error("请选择图片上传");
        }
        fsStoreOrderService.uploadCredentials(order);
        return R.ok();
    }
}
