<?php

namespace app\api\controller;

use think\facade\View;
use think\facade\Lang;

/**
 * ============================================================================
 * 
 * ============================================================================
 * 版权所有 2014-2028 浙江惠利玛产业互联网有限公司，并保留所有权利。
 * 网站地址: https://www.valimart.net/
 * ----------------------------------------------------------------------------
 * 
 * ============================================================================
 * 卖家消息控制器
 */
class Sellermsg extends MobileSeller {

    public function initialize() {
        parent::initialize(); // TODO: Change the autogenerated stub
        Lang::load(base_path() . 'home/lang/' . config('lang.default_lang') . '/sellermsg.lang.php');
    }

    /**
     * @api {POST} api/Sellermsg/get_list 消息列表
     * @apiVersion 1.0.0
     * @apiGroup Sellermsg
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     * 
     * @apiParam {Int} page 页码
     * @apiParam {Int} per_page 每页数量
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Object[]} result.notice_list  消息列表 （返回字段参考storemsg表）
     * @apiSuccess {String} result.notice_list.storemt_name  商家消息模板名称
     * @apiSuccess {Int[]} result.notice_list.storemsg_readids  已读消息ID
     * @apiSuccess {Int} result.page_total  总页数
     * @apiSuccess {Boolean} result.hasmore  是否有更多 true是false否
     */
    public function get_list() {
        $where = array();
        $where[] = array('store_id', '=', $this->store_info['store_id']);
        if (!$this->seller_info['is_admin']) {
            $where[] = array('storemt_code', 'in', $this->seller_group_info['smt_limits']);
        }
        $storemsg_model = model('storemsg');
        $msg_list = $storemsg_model->getStoremsgList($where, '*', 10);

        // 整理数据
        if (!empty($msg_list)) {
            $storemsgtpl_model = model('storemsgtpl');
            $storemsgtpl_array = array();
            foreach ($msg_list as $key => $val) {
                if (!isset($storemsgtpl_array[$val['storemt_code']])) {
                    $storemsgtpl_info = $storemsgtpl_model->getStoremsgtplInfo(array('storemt_code' => $val['storemt_code']));
                    $storemsgtpl_array[$val['storemt_code']] = $storemsgtpl_info['storemt_name'];
                }
                $msg_list[$key]['storemt_name'] = $storemsgtpl_array[$val['storemt_code']];
                $msg_list[$key]['storemsg_readids'] = explode(',', $val['storemsg_readids']);
            }
        }



        ds_json_encode(10000, '', array_merge(array('notice_list' => $msg_list), mobile_page($storemsg_model->page_info)));
    }

    /**
     * 消息详细
     */
    public function msg_info() {
        $storemsg_id = intval(input('param.storemsg_id'));
        if ($storemsg_id <= 0) {
            $this->error(lang('param_error'));
        }
        $storemsg_model = model('storemsg');
        $where = array();
        $where[] = array('storemsg_id', '=', $storemsg_id);
        if ($this->seller_group_info['smt_limits'] !== false) {
            $where[] = array('storemt_code', 'in', $this->seller_group_info['smt_limits']);
        }
        $msg_info = $storemsg_model->getStoremsgInfo($where);
        if (empty($msg_info)) {
            $this->error(lang('param_error'));
        }
        View::assign('msg_list', $msg_info);

        // 验证时候已读
        $storemsg_readids = explode(',', $msg_info['storemsg_readids']);
        if (!in_array($this->seller_info['seller_id'], $storemsg_readids)) {
            // 消息阅读表插入数据
            $condition = array();
            $condition[] = array('seller_id','=',$this->seller_info['seller_id']);
            $condition[] = array('storemsg_id','=',$storemsg_id);
            model('storemsgread')->addStoremsgread($condition);

            $update = array();
            $storemsg_readids[] = $this->seller_info['seller_id'];
            $update['storemsg_readids'] = implode(',', $storemsg_readids) . ',';
            $storemsg_model->editStoremsg(array('storemsg_id' => $storemsg_id), $update);
        }
        return View::fetch($this->template_dir . 'msg_info');
    }

    /**
     * AJAX标记为已读
     */
    public function mark_as_read() {
        $smids = input('param.smids');
        if (!preg_match('/^[\d,]+$/i', $smids)) {
            ds_json_encode(10001, lang('param_error'));
        }

        $smids = explode(',', $smids);
        $storemsgread_model = model('storemsgread');
        $storemsg_model = model('storemsg');
        foreach ($smids as $val) {
            $condition = array();
            $condition[] = array('seller_id','=',$this->seller_info['seller_id']);
            $condition[] = array('storemsg_id','=',$val);
            $read_info = $storemsgread_model->getStoremsgreadInfo($condition);
            if (empty($read_info)) {
                // 消息阅读表插入数据
                $storemsgread_model->addStoremsgread($condition);

                // 更新店铺消息表
                $storemsg_info = $storemsg_model->getStoremsgInfo(array('storemsg_id' => $val));
                $storemsg_readids = explode(',', $storemsg_info['storemsg_readids']);
                $storemsg_readids[] = $this->seller_info['seller_id'];
                $storemsg_readids = array_unique($storemsg_readids);
                $update = array();
                $update['storemsg_readids'] = implode(',', $storemsg_readids) . ',';
                $storemsg_model->editStoremsg(array('storemsg_id' => $val), $update);
            }
        }
        ds_json_encode(10000, lang('ds_common_op_succ'));
    }

    /**
     * AJAX删除消息
     */
    public function del_msg() {
        // 验证参数
        $smids = input('param.smids');
        if (!preg_match('/^[\d,]+$/i', $smids)) {
            ds_json_encode(10001, lang('param_error'));
        }
        $smid_array = explode(',', $smids);

        // 验证是否为管理员
        if (!$this->checkIsAdmin()) {
            ds_json_encode(10001, lang('param_error'));
        }

        $where = array();
        $where[] = array('store_id', '=', $this->store_info['store_id']);
        $where[] = array('storemsg_id', 'in', $smid_array);
        // 删除消息记录
        model('storemsg')->delStoremsg($where);
        // 删除阅读记录
        $where = array();
        $where[] = array('storemsg_id', 'in', $smid_array);
        model('storemsgread')->delStoremsgread($where);
        ds_json_encode(10000, lang('ds_common_op_succ'));
    }

    /**
     * 消息接收设置
     */
    public function msg_setting() {
        // 验证是否为管理员
        if (!$this->checkIsAdmin()) {
            $this->error(lang('param_error'));
        }

        // 店铺消息模板列表
        $smt_list = model('storemsgtpl')->getStoremsgtplList(array(), 'storemt_code,storemt_name,storemt_message_switch,storemt_message_forced,storemt_short_switch,smt_short_forced,storemt_mail_switch,storemt_mail_forced');

        // 店铺接收设置
        $setting_list = model('storemsgsetting')->getStoremsgsettingList(array('store_id' => $this->store_info['store_id']), '*', 'storemt_code');

        if (!empty($smt_list)) {
            foreach ($smt_list as $key => $val) {
                // 站内信消息模板是否开启
                if ($val['storemt_message_switch']) {
                    // 是否强制接收，强制接收必须开启
                    $smt_list[$key]['storems_message_switch'] = $val['storemt_message_forced'] ? 1 : intval($setting_list[$val['storemt_code']]['storems_message_switch']);

                    // 已开启接收模板
                    if ($smt_list[$key]['storems_message_switch']) {
                        $smt_list[$key]['is_opened'][] = lang('business_alert');
                    }
                }
                // 短消息模板是否开启
                if ($val['storemt_short_switch']) {
                    // 是否强制接收，强制接收必须开启
                    $smt_list[$key]['storems_short_switch'] = $val['smt_short_forced'] ? 1 : intval($setting_list[$val['storemt_code']]['storems_short_switch']);

                    // 已开启接收模板
                    if ($smt_list[$key]['storems_short_switch']) {
                        $smt_list[$key]['is_opened'][] = lang('sms_alerts');
                    }
                }
                // 邮件模板是否开启
                if ($val['storemt_mail_switch']) {
                    // 是否强制接收，强制接收必须开启
                    $smt_list[$key]['storems_mail_switch'] = $val['storemt_mail_forced'] ? 1 : intval($setting_list[$val['storemt_code']]['storems_mail_switch']);

                    // 已开启接收模板
                    if ($smt_list[$key]['storems_mail_switch']) {
                        $smt_list[$key]['is_opened'][] = lang('email_alerts');
                    }
                }

                if (is_array($smt_list[$key]['is_opened'])) {
                    $smt_list[$key]['is_opened'] = implode('&nbsp;|&nbsp;&nbsp;', $smt_list[$key]['is_opened']);
                }
            }
        }
        View::assign('smt_list', $smt_list);

        $this->setSellerCurMenu('Sellermsg');
        $this->setSellerCurItem('msg_setting');
        return View::fetch($this->template_dir . 'msg_setting');
    }

    /**
     * 编辑店铺消息接收设置
     */
    public function edit_msg_setting() {
        // 验证是否为管理员
        if (!$this->checkIsAdmin()) {
            $this->error(lang('param_error'));
        }
        $code = trim(input('param.code'));
        if ($code == '') {
            return false;
        }
        // 店铺消息模板
        $smt_info = model('storemsgtpl')->getStoremsgtplInfo(array('storemt_code' => $code), 'storemt_code,storemt_name,storemt_message_switch,storemt_message_forced,storemt_short_switch,smt_short_forced,storemt_mail_switch,storemt_mail_forced');
        if (empty($smt_info)) {
            return false;
        }

        // 店铺消息接收设置
        $setting_info = model('storemsgsetting')->getStoremsgsettingInfo(array(
            'storemt_code' => $code,
            'store_id' => $this->store_info['store_id']
        ));
        View::assign('smt_info', $smt_info);
        View::assign('smsetting_info', $setting_info);
        return View::fetch($this->template_dir . 'setting_edit');
    }

    /**
     * 保存店铺接收设置
     */
    public function save_msg_setting() {
        // 验证是否为管理员
        if (!$this->checkIsAdmin()) {
            ds_json_encode(10001, lang('param_error'));
        }
        $code = trim(input('post.code'));
        if ($code == '') {
            ds_json_encode(10001, lang('param_error'));
        }

        $data = [
            'storems_short_number' => input('post.storems_short_number'),
            'storems_mail_number' => input('post.storems_mail_number'),
        ];
        $sellermsg_validate = ds_validate('sellermsg');
        if (!$sellermsg_validate->scene('save_msg_setting')->check($data)) {
            ds_json_encode(10001, $sellermsg_validate->getError());
        }

        $smt_info = model('storemsgtpl')->getStoremsgtplInfo(array('storemt_code' => $code), 'storemt_code,storemt_name,storemt_message_switch,storemt_message_forced,storemt_short_switch,smt_short_forced,storemt_mail_switch,storemt_mail_forced');

        // 保存
        $data = array();
        $data['storemt_code'] = $smt_info['storemt_code'];
        $data['store_id'] = $this->store_info['store_id'];
        // 验证站内信是否开启
        if ($smt_info['storemt_message_switch']) {
            $data['storems_message_switch'] = $smt_info['storemt_message_forced'] ? 1 : intval(input('post.message_forced'));
        } else {
            $data['storems_message_switch'] = 0;
        }
        // 验证短消息是否开启
        if ($smt_info['storemt_short_switch']) {
            $data['storems_short_switch'] = $smt_info['smt_short_forced'] ? 1 : intval(input('post.short_forced'));
        } else {
            $data['storems_short_switch'] = 0;
        }
        $data['storems_short_number'] = input('post.storems_short_number', '');
        // 验证邮件是否开启
        if ($smt_info['storemt_mail_switch']) {
            $data['storems_mail_switch'] = $smt_info['storemt_mail_forced'] ? 1 : intval(input('post.mail_forced'));
        } else {
            $data['storems_mail_switch'] = 0;
        }
        $data['storems_mail_number'] = input('post.storems_mail_number', '');
        $conditiion = array();
        $conditiion['storemt_code'] = $smt_info['storemt_code'];
        $storemsgsetting_info = model('storemsgsetting')->getStoremsgsettingInfo($conditiion);
        // 插入数据
        if (empty($storemsgsetting_info)) {
            $result = model('storemsgsetting')->addStoremsgsetting($data);
        } else {
            $result = model('storemsgsetting')->editStoremsgsetting($data, $conditiion);
        }
        if ($result) {
            ds_json_encode(10000, lang('ds_common_op_succ'));
        } else {
            ds_json_encode(10001, lang('ds_common_op_fail'));
        }
    }

    private function checkIsAdmin() {
        return $this->seller_info['is_admin'] ? true : false;
    }

}
