<?php


namespace JinDouYun\Controller\Common;


use JinDouYun\Controller\BaseController;
use JinDouYun\Dao\Order\DOrder;
use JinDouYun\Dao\Order\DOrderGoods;
use JinDouYun\Dao\Order\DOrderReceive;
use JinDouYun\Dao\System\DReceiptTemplate;
use JinDouYun\Model\Order\MOrderReturn;
use JinDouYun\Model\Shop\MShop;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\StatusCode;

class EasyTest extends BaseController
{

    public function __construct()
    {
        parent::__construct(false, false, false, true);
    }

    public function testSub()
    {
        print_r($this->areaCode);die;
        $objMOrderReturn = new MOrderReturn(64,4);
        $result = $objMOrderReturn->getSubRetMoneyToday();
        if (!$result->isSuccess()){
            parent::sendOutput($result->getData(),$result->getErrorCode());
        }
        parent::sendOutput($result->getData());
    }

    /**
     * Doc: (des="编辑销售单模版")
     * User: XMing
     * Date: 2020/11/26
     * Time: 11:22 上午
     */
    public function orderReceipt()
    {
        $params = $this->request->getRawJson();

        if (!isset($params['type']) || empty($params['type'])){
            echo 'type参数错误' . PHP_EOL;
            die;
        }
        $type = $params['type'];
        if (!isset($params['key']) || empty($params['key'])) {
            echo 'key参数错误' . PHP_EOL;
            die;
        }
        $key = $params['key'];
        if (!isset($params['action']) || empty($params['action'])) {
            echo 'action参数错误' . PHP_EOL;
            die;
        }
        $action = $params['action'];
        if (!isset($params['row']) || empty($params['row'])) {
            echo 'row参数错误' . PHP_EOL;
            die;
        }
        $group = $params['row'];

        $alias = isset($group['alias']) ? $group['alias'] : '';
        $objDReceiptTemplate = new DReceiptTemplate();
        $lists = $objDReceiptTemplate->select(['receiptType' => $type]);
        if ($lists === false) {
            echo 'sql:' . $objDReceiptTemplate->error() . PHP_EOL;
            die;
        }
        $i = 0;
        foreach ($lists as $list) {
            $fieldsData = json_decode($list['fieldsData'], true);
            if (!isset($fieldsData['templateInfo'][$key])) {
                echo $list['enterpriseId'] . '数据配置错误' . PHP_EOL;
                die;
            }
            $id = $list['id'];
            $rows = $fieldsData['templateInfo'][$key];
            switch ($action) {
                case 'add':
                    $hasAlias = [];
                    foreach ($rows as $index => $row) {
                        $hasAlias[] = $row['alias'];
                    }
                    if (!in_array($alias, $hasAlias)) {
                        $rows[] = $group;
                    }
                    break;
                case 'del':
                    foreach ($rows as $index => $row) {
                        if ($row['alias'] == $alias) {
                            unset($rows[$index]);
                        }
                    }
                    break;
            }

            $fieldsData['templateInfo'][$key] = array_values($rows);
            $nowFieldsData = json_encode($fieldsData);
            $update = $objDReceiptTemplate->update(['fieldsData' => $nowFieldsData], $id);
            if ($update === false) {
                echo 'sql-update-error:' . $objDReceiptTemplate->error() . PHP_EOL;
            }
            $i++;
        }
        echo '共计更新' . $i . '条数据';
    }


    public function test()
    {
        $objDReceiptTemplate = new DReceiptTemplate();
        $lists = $objDReceiptTemplate->select(['receiptType' => 5]);
        if ($lists === false) {
            echo 'sql:' . $objDReceiptTemplate->error() . PHP_EOL;
            die;
        }

        foreach ($lists as $list) {
            $id = $list['id'];
            $fieldsData = json_decode($list['fieldsData'], true);
            if (empty($fieldsData)) {
                continue;
            }
            $insertBasic = [
                [
                    "alias"  => "operatorName",
                    "fields" => "制单人",
                    "isShow" => 4
                ],
                [
                    "alias"  => "receivedName",
                    "fields" => "收货人",
                    "isShow" => 4
                ]
            ];
            /*$insertFiance = [
                [
                    "alias"  => "orderPreferential",
                    "fields" => "优惠",
                    "isShow" => 4
                ]
            ];*/
            $insertOther = [
                [
                    "alias"  => "receivedMobile",
                    "fields" => "收货电话",
                    "isShow" => 4
                ],
            ];
            $fieldsData['templateInfo']['basic'] = array_merge($fieldsData['templateInfo']['basic'], $insertBasic);
            //$fieldsData['templateInfo']['fiance'] = array_merge($fieldsData['templateInfo']['fiance'],$insertFiance);
            $fieldsData['templateInfo']['other'] = array_merge($fieldsData['templateInfo']['other'], $insertOther);
            $nowFieldsData = json_encode($fieldsData);
            $update = $objDReceiptTemplate->update(['fieldsData' => $nowFieldsData], $id);
            if ($update === false) {
                echo 'sql-update-error:' . $objDReceiptTemplate->error() . PHP_EOL;
            }
        }
        echo '共计更新' . count($lists) . '条数据';
    }


    /**
     * Doc: (des="")
     * User: XMing
     * Date: 2020/11/18
     * Time: 3:47 下午
     * @throws \Exception
     */
    public function syncOrderEs()
    {
        $enterId = 4;
        $objDOrder = new DOrder();
        $objDOrder->setSearchIndex('order_search')->setType('order');
        $objDOrderGoods = new DOrderGoods();
        $objDOrderReceive = new DOrderReceive();
        $objDOrder->setTable('qianniao_order_' . $enterId . '_1');
        $objDOrderGoods->setTable('qianniao_order_goods_' . $enterId . '_1');
        $objDOrderReceive->setTable('qianniao_order_receive_' . $enterId . '_1');
        $orderLists = $objDOrder->select();
        if ($orderLists === false) {
            echo 'sql-error: ' . $objDOrder->error() . PHP_EOL;
            die;
        }
        $orderGoodsLists = $objDOrderGoods->select();
        if ($orderGoodsLists === false) {
            echo 'sql-error: ' . $objDOrderGoods->error() . PHP_EOL;
            die;
        }
        $orderReceiveLists = $objDOrderReceive->select();
        if ($orderReceiveLists === false) {
            echo 'sql-error: ' . $objDOrderReceive->error() . PHP_EOL;
            die;
        }
        $mapGoods = [];
        $mapGoodsNames = [];
        foreach ($orderGoodsLists as $orderGoods) {
            $mapGoods[$orderGoods['orderId']][] = $orderGoods;
            !isset($mapGoodsNames[$orderGoods['orderId']]) && $mapGoodsNames[$orderGoods['orderId']] = '';
            $mapGoodsNames[$orderGoods['orderId']] .= $orderGoods['goodsName'] . ' ';
        }
        unset($orderGoodsLists);
        $mapReceive = [];
        foreach ($orderReceiveLists as $orderReceive) {
            $mapReceive[$orderReceive['orderId']] = $orderReceive;
        }
        unset($orderReceiveLists);

        $i = 0;
        foreach ($orderLists as $list) {
            $_id = self::createEsDocumentId($list['id'], $enterId);
            $list['goodsName'] = isset($mapGoodsNames[$list['id']]) ? $mapGoodsNames[$list['id']] : '';
            $buildData = self::buildData($list, $enterId, isset($mapReceive[$list['id']]) ? $mapReceive[$list['id']] : []);

            $result = $objDOrder->addUpSearchIndexDocument($buildData, $_id);
            if (isset($result['_shards']) && isset($result['_shards']['successful']) && $result['_shards']['successful'] == 1) {
                //echo "es操作成功";
                //return;
                echo ' ' . $_id . ' ';
                $i++;
            } else {
                echo "es操作失败" . PHP_EOL;
            }
        }

        echo '共写入' . $i . '条数据' . PHP_EOL;
    }

    public static function buildData($params, $enterId, $addressData)
    {
        return [
            'id'                => isset($params['id']) ? $params['id'] : 0,//订单编号,
            'no'                => isset($params['no']) ? $params['no'] : '',//订单编号,
            'outerTradeNo'      => '',//'外部流水号(支付宝/微信返回的流水号)'
            'shopId'            => isset($params['shopId']) ? $params['shopId'] : 0,
            'shopName'          => isset($params['shopName']) ? $params['shopName'] : '',
            'enterpriseId'      => $enterId,
            'userCenterId'      => isset($params['userCenterId']) ? $params['userCenterId'] : 0,
            'totalMoney'        => isset($params['totalMoney']) ? $params['totalMoney'] : 0,
            'payAmount'         => isset($params['payAmount']) ? $params['payAmount'] : 0,
            'buyTotal'          => isset($params['buyTotal']) ? $params['buyTotal'] : 0,
            'customerName'      => isset($params['customerName']) ? $params['customerName'] : '',//客户姓名
            'customerId'        => isset($params['customerId']) ? $params['customerId'] : 0,//客户id
            'customerType'      => isset($params['customerType']) ? $params['customerType'] : 0,//客户类型
            'payStatus'         => isset($params['payStatus']) ? $params['payStatus'] : 0,//'支付状态  默认4 未支付 5已支付'
            'orderStatus'       => isset($params['orderStatus']) ? $params['orderStatus'] : StatusCode::$orderStatus['waitPay'],//订单状态 默认1 创建 2待支付 3代发货 4待收货 5已完成 6已关闭
            'payType'           => isset($params['payType']) ? $params['payType'] : 0,//'支付方式 1微信 2支付宝 3货到付款 4上门自提'
            'deliveryType'      => isset($params['deliveryType']) ? $params['deliveryType'] : 0,//'配送方式 1商品配送 2上门自提'
            'source'            => isset($params['source']) ? $params['source'] : 1,//订单来源 默认1 ios 2android 3小程序 4后台创建
            'remark'            => isset($params['remark']) ? $params['remark'] : '',//订单备注
            'auditStatus'       => isset($params['auditStatus']) ? $params['auditStatus'] : 1,// '审核状态 默认1 待审 2审核通过 3 审核未通过 4 审核中'
            //'payTime'      => '',//'付款时间'
            'createTime'        => isset($params['createTime']) ? $params['createTime'] : 0,//'创建时间'
            'updateTime'        => isset($params['updateTime']) ? $params['updateTime'] : 0,//'修改时间',
            'salesManId'        => isset($params['salesManId']) ? $params['salesManId'] : 0,
            'salesManName'      => isset($params['salesManName']) ? $params['salesManName'] : '',
            'returnStatus'      => isset($params['notReturn']) ? $params['notReturn'] : StatusCode::$orderReturn['notReturn'],
            'outStatus'         => isset($params['outStatus']) ? $params['outStatus'] : StatusCode::$delete,
            'verifyCode'        => isset($params['verifyCode']) ? $params['verifyCode'] : '',//核销码

            /*收货人信息*/
            'realName'          => isset($addressData['realName']) ? $addressData['realName'] : '',//收货人姓名
            'mobile'            => isset($addressData['mobile']) ? $addressData['mobile'] : '',//收货人电话
            'address'           => isset($addressData['address']) ? $addressData['address'] : '',//收货详细地址
            'provinceCode'      => isset($addressData['provinceCode']) ? $addressData['provinceCode'] : '',//收货人省份编码
            'cityCode'          => isset($addressData['cityCode']) ? $addressData['cityCode'] : '',//收货人城市编码
            'districtCode'      => isset($addressData['districtCode']) ? $addressData['districtCode'] : '',//收货人区编码

            /*优惠信息*/
            'preferential'      => isset($params['preferential']) ? $params['preferential'] : 0,//优惠券优惠金额
            'vipDiscount'       => isset($params['vipDiscount']) ? $params['vipDiscount'] : 0,//会员卡优惠金额
            'vipDoubleDiscount' => isset($params['vipDoubleDiscount']) ? $params['vipDoubleDiscount'] : 0,//会员卡折上折优惠金额

            /*商品信息*/
            'goodsName'         => $params['goodsName'] ? $params['goodsName'] : '',
            'orderType'         => isset($params['orderType']) ? $params['orderType'] : StatusCode::$orderType['salesSlip'],
        ];
    }

    /**
     * 创建文档id
     *
     * @param $orderId
     * @param $onlineEnterpriseId
     * @return string
     */
    private function createEsDocumentId($orderId, $onlineEnterpriseId)
    {
        return 'EnterpriseId_' . $onlineEnterpriseId . '_OrderId_' . intval($orderId);
    }

}