package com.malk.diwei.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.malk.diwei.entity.Color;
import com.malk.diwei.entity.Employee;
import com.malk.diwei.entity.SalesOrder;
import com.malk.diwei.entity.Size;
import com.malk.diwei.mapper.ColorMapper;
import com.malk.diwei.mapper.EmployeeMapper;
import com.malk.diwei.mapper.SalesOrderMapper;
import com.malk.diwei.mapper.SizeMapper;
import com.malk.diwei.service.SalesOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McR;
import com.malk.service.aliwork.YDClient;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author WZY
 * @since 2025-03-28
 */
@Service
public class SalesOrderServiceImpl extends ServiceImpl<SalesOrderMapper, SalesOrder> implements SalesOrderService {
    @Autowired
    private YDClient ydClient;

    @Autowired
    private ColorMapper colorMapper;

    @Autowired
    private SizeMapper sizeMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private SalesOrderMapper salesOrderMapper;

    @Override
    public McR addSaleOrder(Map map) {
        if (Objects.isNull(map.get("formInstId"))){
            return McR.errorParam("实例id为空！");
        }
        String formInstId = map.get("formInstId").toString();

        Map formData = ydClient.queryData(YDParam.builder()
                .formInstId(formInstId)
                .build(), YDConf.FORM_QUERY.retrieve_id).getFormData();

        Map salesOrder = new HashMap();
        //将时间戳转化为字符串 年月日格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        LambdaQueryWrapper<SalesOrder> salesOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        salesOrderLambdaQueryWrapper.ge(SalesOrder::getSalesOrderCreateDatetime, DateUtil.beginOfDay(new Date()))
                .orderByDesc(SalesOrder::getSalesOrderID);
        List<SalesOrder> salesOrderList = salesOrderMapper.selectList(salesOrderLambdaQueryWrapper);
        String newSalesOrderCode = "";
        if (Objects.nonNull(salesOrderList) && !salesOrderList.isEmpty()){
            String salesOrderCode = salesOrderList.get(0).getSalesOrderCode();//格式：SO-yyyyMMdd-0001

            //salesOrderCode累加
            String[] split = salesOrderCode.split("-");
            int i = Integer.parseInt(split[2]) + 1;

            newSalesOrderCode = "SO-"+split[1]+"-"+String.format("%04d",i);
        }else {
            newSalesOrderCode = "SO-"+sdf.format(new Date())+"-0001";
        }

        salesOrder.put("SalesOrderCode",newSalesOrderCode);//订单编号
        salesOrder.put("SalesOrderDate",sdf.format(new Date((long) formData.get("dateField_m8mpzwsh"))));//销售订单日期
        salesOrder.put("ClientName",formData.get("textField_m8s4mqfv"));//客户名称
        salesOrder.put("ClientLinkMan",formData.get("textField_m8mpzwst"));//联系记录
        salesOrder.put("ClientLinkMob",formData.get("textField_m8mpzwsu"));//联系手机
        salesOrder.put("ClientLinkTel",formData.get("textField_m8mpzwsv"));//联系电话
        salesOrder.put("SalesOrderDeptName",formData.get("textField_m8mv98nf"));//部门
        salesOrder.put("SalesOrderContractNo",formData.get("textField_m8mpzwt1"));//合同号
        //订单性质
        if (Objects.nonNull(formData.get("selectField_m8mpzwt2"))){
            switch (formData.get("selectField_m8mpzwt2").toString()){
                case "销售样":
                    salesOrder.put("SalesOrderProperty",1);
                    break;
                case "大货订单":
                    salesOrder.put("SalesOrderProperty",2);
                    break;
            }
        }
        salesOrder.put("SalesOrderDZPercent",formData.get("numberField_m8mpzwt7"));//短装数
        salesOrder.put("SalesOrderYZPercent",formData.get("numberField_m8mpzwt8"));//溢装数
        salesOrder.put("SalesOrderDeliveryDate",sdf.format(new Date((long) formData.get("dateField_m8mpzwso"))));//交货日期
        salesOrder.put("SalesOrderDeliveryAddress",formData.get("textareaField_m8mpzwtj"));//交货地址
        salesOrder.put("SalesmanName",formData.get("textField_m8s4mqg0"));//业务员

        String creator = formData.get("textField_m8mpzwt0").toString();
        LambdaQueryWrapper<Employee> employeeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        employeeLambdaQueryWrapper.eq(Employee::getEmpName,creator)
                .or().eq(Employee::getEmpGamUserID,creator);
        Employee employee = employeeMapper.selectOne(employeeLambdaQueryWrapper);
        if (Objects.nonNull(employee)){
            salesOrder.put("SalesOrderCreatEmp",creator);//制单人
        }else {
            salesOrder.put("SalesOrderCreatEmp","蒂维");//制单人
        }

        salesOrder.put("SalesOrderFollowEmp",formData.get("textField_m8s4mqg0"));//业务跟单
        salesOrder.put("SalesOrderQCFollowEmp",formData.get("textField_m8s4mqg2"));//QC跟单
        salesOrder.put("SalesOrderDescription",formData.get("textareaField_m8mpzwti"));//单据备注
        salesOrder.put("SalesOrderOrgName","总部");//组织机构

        List<Map> billItems = new ArrayList<>();
        List<Map> details = (List<Map>) formData.get("tableField_m8mpzwtk");
        for (Map detail : details) {
            Map billItem = new HashMap();
            billItem.put("GoodsCode",formData.get("textField_m8mpzwtl"));//款号

            billItem.put("ColorName",detail.get("selectField_m8nxpzya"));//颜色
            billItem.put("SizeName",detail.get("selectField_m8nxpzy8"));//尺码
            billItem.put("SalesOrderItemPrice",detail.get("numberField_m8mpzwtu"));//销售单价
            billItem.put("SalesOrderItemQty",detail.get("numberField_m8mpzwts"));//订单件数
            billItem.put("SalesOrderItemAmount",detail.get("numberField_m8mpzwtv"));//订单金额
            billItem.put("SalesOrderItemIsGift",detail.get("radioField_m8mpzwtw").toString().equals("是"));//是否赠品
            billItem.put("SalesOrderItemDescription",detail.get("textareaField_m8mpzwtt"));//明细备注

            billItems.add(billItem);
        }

        salesOrder.put("BillItems",billItems);

        String s = UtilHttp.doPost("http://47.98.200.166/EpiErp5_DiWei_2023/rest/SyncSalesOrder_DW", null, null, salesOrder);

        Map parse = (Map) JSONObject.parse(s);

        if (!parse.get("errcode").toString().equals("0")){
            return McR.errorUnknown("新增失败！失败原因："+parse.get("errmsg").toString());
        }else {
            ydClient.operateData(YDParam.builder()
                    .formInstId(formInstId)
                    .updateFormDataJson(JSONObject.toJSONString(UtilMap.map("textField_m9cgygm3",newSalesOrderCode)))
                    .build(), YDConf.FORM_OPERATION.update);
        }

        return McR.success();
    }
}
