<?php
/**
 * Created by PhpStorm.
 * User: XiaoMing
 * Date: 2020/5/8
 * Time: 10:09
 */

namespace JinDouYun\Model\Manage;

use Jindouyun\Cache\EnterpriseCache;
use JinDouYun\Dao\Enterprise\DEnterprise;
use JinDouYun\Dao\Enterprise\DEnterpriseCategory;
use JinDouYun\Dao\System\DEnterpriseBindTemplate;
use JinDouYun\Dao\System\DSystemTemplate;
use JinDouYun\Model\System\MEnterpriseBindTemplate;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\StatusCode;

/**
 * 微信模版
 * Class MWxTemplate
 * @package JinDouYun\Model\Manage
 */
class MWxTemplate
{
    private $objDEnterpriseBindTemplate;

    private $objDEnterprise;

    private $objDSystemTemplate;

    private $objEnterpriseCache;

    /**
     * MWxTemplate constructor.
     * @throws \Exception
     */
    public function __construct()
    {
        $this->objDEnterpriseBindTemplate = new DEnterpriseBindTemplate();
        $this->objDEnterprise = new DEnterprise('default');
        $this->objDEnterprise->setTable($this->objDEnterprise->get_Table() . '_1');
        $this->objDSystemTemplate = new DSystemTemplate();
        $this->objEnterpriseCache = new EnterpriseCache();
    }

    /**
     * 获取小程序模版
     * @param $selectParams
     * @return ResultWrapper
     */
    public function getAll($selectParams)
    {
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);

        $whereSql = '';
        !empty($selectParams['enterpriseName']) && $whereSql .= ' and e.enterpriseName like "%'.$selectParams["enterpriseName"].'%"';
        !empty($selectParams['isWeChatStatus']) && $whereSql .= ' and b.auditStatus = '.$selectParams["isWeChatStatus"];
        !empty($selectParams['oemId']) && $whereSql .= ' and e.oemId = '.$selectParams["oemId"];
        $countField = ' COUNT(b.id) AS total ';
        $fields = 'b.id,b.templateId,b.enterpriseId,b.enableStatus,b.qrcodeImg,b.createTime,b.auditId,b.auditStatus,b.reason';
        $Sql = 'SELECT  ' . $fields. ' FROM qianniao_enterprise_bind_template AS b 
                LEFT JOIN qianniao_enterprise_1 AS e ON b.enterpriseId = e.id 
                WHERE b.enableStatus = ' . StatusCode::$standard . $whereSql.' ORDER BY ID DESC LIMIT '. $offset . ',' . $limit ;

        $countSql = 'SELECT  ' . $countField. ' FROM qianniao_enterprise_bind_template AS b 
                LEFT JOIN qianniao_enterprise_1 AS e ON b.enterpriseId = e.id 
                WHERE b.enableStatus = ' . StatusCode::$standard . $whereSql ;
        $dbResult = $this->objDEnterpriseBindTemplate->query($Sql);

        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDEnterpriseBindTemplate->error(), ErrorCode::$dberror);
        }
        $total = $this->objDEnterpriseBindTemplate->query($countSql);

        $return = [
            'data'  => self::formatMapping($dbResult),
            'total' => isset($total[0]['total']) ? $total[0]['total'] : 0,
        ];
        return ResultWrapper::success($return);
    }

    /**
     * @param $data
     * @return mixed
     */
    private function formatMapping($data)
    {
        if (empty($data)) return $data;
        //获取企业
        $dbResult = $this->objDEnterprise->select(['id' => array_values(array_unique(array_column($data, 'enterpriseId')))], 'id,enterpriseName,token');
        if ($dbResult === false) {
            $enterprise = [];
        } else {
            $mapping = [];
            foreach ($dbResult as $val) {
                $mapping[$val['id']] = $val;
            }
            $enterprise = $mapping;
        }
        unset($dbResult);
        //获取模版
        $dbResult = $this->objDSystemTemplate->select(['id' => array_values(array_unique(array_column($data, 'templateId')))], 'id,title,weixinTemplateId,type,version');
        if ($dbResult === false) {
            $template = [];
        } else {
            $mapping = [];
            foreach ($dbResult as $val) {
                $mapping[$val['id']] = $val;
            }
            $template = $mapping;
        }
        //mapping
        foreach ($data as &$value) {
            $value['enterpriseName'] = isset($enterprise[$value['enterpriseId']]['enterpriseName']) ? $enterprise[$value['enterpriseId']]['enterpriseName'] : '';//企业名称
            $value['token'] = isset($enterprise[$value['enterpriseId']]['token']) ? $enterprise[$value['enterpriseId']]['token'] : '';//企业token
            $value['title'] = isset($template[$value['templateId']]['title']) ? $template[$value['templateId']]['title'] : '';//模版名称名称
            $value['type'] = isset($template[$value['templateId']]['type']) ? $template[$value['templateId']]['type'] : 1;//模版类型
            $value['typeName'] = $value['type'] == 1 ? '系统模版' : '万能模版';//模版类型名
            $value['weixinTemplateId'] = isset($template[$value['templateId']]['weixinTemplateId']) ? $template[$value['templateId']]['weixinTemplateId'] : 0;//微信模版id
            $value['auditMsg'] = self::auditStatusAttr($value['auditStatus']);//状态描述
            $value['version'] = isset($template[$value['templateId']]['version']) ? $template[$value['templateId']]['version'] : '';//模版版本
            if(!empty($value['reason'])){
                $value['reason'] = json_decode($value['reason'],true);
            }else{
                $value['reason'] = (object)[];
            }
        }
        return $data;
    }

    /**
     * @param $value
     * @return mixed|string
     */
    public static function auditStatusAttr($value)
    {
        $auditStatus = [
            '0' => '审核成功',
            '1' => '审核拒绝',
            '2' => '审核中',
            '3' => '已撤回',
            '4' => '延后',
            '5' => '提交审核',
            '6' => '提交代码',
            '7' => '正在使用'
        ];
        return isset($auditStatus[$value]) ? $auditStatus[$value] : '未知';
    }

    /**
     * 提交代码&&提交审核
     * @param $params
     * @param $token
     * @return ResultWrapper
     */
    public function submitCodeAndAudit($params)
    {
        foreach ($params as $value) {
            $objMEnterpriseBindTemplate = new MEnterpriseBindTemplate(null, $value['enterpriseId']);
            //提交代码
            $dbResult = $objMEnterpriseBindTemplate->submitCode(
                [
                    'weixinTemplateId' => $value['weixinTemplateId'],//微信模版id
                    'templateId'       => $value['templateId'],//模版id
                    'enableStatus'     => StatusCode::$standard,//启用
                    'enterpriseId'     => $value['enterpriseId'],//企业id
                    'version'          => $value['version'],//版本号
                ],
                $value['token']);
            if (!$dbResult->isSuccess()) {
                return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode());
            }
            //缓存
            $this->objEnterpriseCache->EnterpriseDataCache($value['enterpriseId'], 'weixinTemplateId', $value['enterpriseId']);
            $this->objEnterpriseCache->EnterpriseDataCache($value['enterpriseId'], 'templateId', $value['templateId']);

            //提交审核
            $dbResult = $objMEnterpriseBindTemplate->submitAudit([
                'templateId'   => $value['templateId'],//模版id,
                'enterpriseId' => $value['enterpriseId'],//企业id
            ]);
            if (!$dbResult->isSuccess()) {
                return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode());
            }
        }
        return ResultWrapper::success('已提交审核');
    }

    /**
     * 发布已审核小程序
     * @param $params
     * @return ResultWrapper
     */
    public function release($params)
    {
        foreach ($params as $value){
            $objMEnterpriseBindTemplate = new MEnterpriseBindTemplate(null, $value['enterpriseId']);
            $dbResult = $objMEnterpriseBindTemplate->release([
                'templateId' => $value['templateId'],
                'enterpriseId' => $value['enterpriseId'],
            ]);
            if (!$dbResult->isSuccess()) {
                return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode());
            }
        }
        return ResultWrapper::success('发布成功');
    }

    /**
     * 撤销审核
     * @param $params
     * @return ResultWrapper
     */
    public function revoke($params)
    {
        foreach ($params as $value){
            $objMEnterpriseBindTemplate = new MEnterpriseBindTemplate(null, $value['enterpriseId']);
            $dbResult = $objMEnterpriseBindTemplate->revoke([
                'templateId' => $value['templateId'],
                'enterpriseId' => $value['enterpriseId'],
            ]);
            if (!$dbResult->isSuccess()) {
                return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode());
            }
        }
        return ResultWrapper::success('撤销成功');
    }
}