<?php

namespace app\api\controller;

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

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 卖家投诉控制器
 */
class Sellercomplain extends MobileSeller {

    //定义投诉状态常量
    const STATE_NEW = 10;
    const STATE_APPEAL = 20;
    const STATE_TALK = 30;
    const STATE_HANDLE = 40;
    const STATE_FINISH = 99;
    const STATE_UNACTIVE = 1;
    const STATE_ACTIVE = 2;

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

    /**
     * @api {POST} api/Sellercomplain/index 被投诉列表
     * @apiVersion 1.0.0
     * @apiGroup Sellercomplain
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {String} add_time_to 开始时间 YYYY-MM-DD
     * @apiParam {String} add_time_from 结束时间 YYYY-MM-DD
     * @apiParam {Int} state 投诉状态 1新投诉 2已关闭
     * @apiParam {String} type 查询字段 accuser_name原告用户名 complain_subject投诉主题
     * @apiParam {String} key 查询关键词
     * @apiParam {Int} page 页码
     * @apiParam {Int} pagesize 每页显示数量
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Object[]} result.complaint_list  投诉列表 （返回字段参考complain表）
     * @apiSuccess {Object} result.goods_list  投诉商品列表，键为订单商品ID
     * @apiSuccess {Int} result.goods_list.buyer_id  买家ID
     * @apiSuccess {Float} result.goods_list.commis_rate  商品分类佣金比例
     * @apiSuccess {Int} result.goods_list.gc_id  分类ID
     * @apiSuccess {Int} result.goods_list.goods_id  商品ID
     * @apiSuccess {String} result.goods_list.goods_image  商品图片名称
     * @apiSuccess {String} result.goods_list.goods_image_url  商品图片完整地址
     * @apiSuccess {String} result.goods_list.goods_name  商品名称
     * @apiSuccess {Int} result.goods_list.goods_num  购买数量
     * @apiSuccess {Float} result.goods_list.goods_pay_price  商品实际支付金额
     * @apiSuccess {Float} result.goods_list.goods_price  商品价格
     * @apiSuccess {Int} result.goods_list.goods_type  商品类型 1默认2抢购商品3限时折扣商品4组合套装5赠品6拼团7会员等级折扣
     * @apiSuccess {Int} result.goods_list.order_id  订单ID
     * @apiSuccess {Int} result.goods_list.promotions_id  促销ID
     * @apiSuccess {Int} result.goods_list.rec_id  订单商品表自增ID
     * @apiSuccess {Int} result.goods_list.store_id  店铺ID
     * @apiSuccess {Int} result.page_total  总页数
     * @apiSuccess {Boolean} result.hasmore  是否有更多 true是false否
     */
    public function index() {
        $complain_model = model('complain');
        $condition = array();
        $condition[] = array('accused_id', '=', $this->store_info['store_id']);

        if ((input('param.add_time_to')) != '' && (input('param.add_time_to')) != '') {
            $add_time_from = strtotime((input('param.add_time_from')));
            $add_time_to = strtotime((input('param.add_time_to')));
            $condition[] = array('complain_datetime', 'between', array($add_time_from, $add_time_to));
        }

        switch (intval(input('param.state'))) {
            case 1:
                $condition[] = array('complain_state', 'between', array(10, 90));
                break;
            case 2:
                $condition[] = array('complain_state', '=', 99);
                break;
            default :
        }
        $condition[] = array('complain_active', '=', 2); //投诉是需要平台审核通过之后 卖家才能看的到
        $complain_list = $complain_model->getComplainList($condition, 10);

        View::assign('show_page', $complain_model->page_info->render());
        $goods_list = $complain_model->getComplainGoodsList($complain_list);
        foreach ($goods_list as $key => $val) {
            $goods_list[$key]['goods_image_url'] = goods_thumb($val, 240);
        }
        $result = array_merge(array('complaint_list' => $complain_list, 'goods_list' => $goods_list), mobile_page($complain_model->page_info));
        ds_json_encode(10000, '', $result);
    }

    /**
     * @api {POST} api/Sellercomplain/complain_show 处理投诉请求
     * @apiVersion 1.0.0
     * @apiGroup Sellercomplain
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} complain_id 投诉ID
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {String[]} result.appeal_pic  申诉凭证图片列表
     * @apiSuccess {String[]} result.complain_pic  投诉凭证图片列表
     * @apiSuccess {Object} result.member  用户信息 （参考字段参考member表）
     * @apiSuccess {Object} result.return_info  退款信息 退款信息（参考字段参考order表）
     * @apiSuccess {Object} result.return_info.extend_order_common 订单其他信息（参考字段参考ordercommon表）
     * @apiSuccess {Object} result.return_info.extend_store 店铺信息（参考字段参考store表）
     * @apiSuccess {Object[]} result.return_info.goods_list 订单商品表格（参考字段参考ordergoods表）
     * @apiSuccess {Object} result.complain_info （参考字段参考complain表）
     * @apiSuccess {String} result.complain_info.complain_state_text 投诉状态描述
     */
    public function complain_show() {
        $complain_id = intval(input('param.complain_id'));
        //获取投诉详细信息
        $complain_info = $this->get_complain_info($complain_id);
        $complain_pic = array();
        $appeal_pic = array();
        for ($i = 1; $i <= 3; $i++) {
            if (!empty($complain_info['complain_pic' . $i])) {
                $complain_pic[] = ds_get_pic(ATTACH_PATH . DIRECTORY_SEPARATOR . 'complain', $complain_info['complain_pic' . $i]);
            }
            if (!empty($complain_info['appeal_pic' . $i])) {
                $appeal_pic[] = ds_get_pic(ATTACH_PATH . DIRECTORY_SEPARATOR . 'complain', $complain_info['appeal_pic' . $i]);
            }
        }
        $member_model = model('member');
        $member = $member_model->getMemberInfoByID($complain_info['accuser_id']);
        $refundreturn_model = model('refundreturn');
        $condition = array();
        $condition[] = array('order_id', '=', $complain_info['order_id']);
        $return_info = $refundreturn_model->getRightOrderList($condition, $complain_info['order_goods_id']);
        ds_json_encode(10000, '', array('member' => $member, 'return_info' => $return_info, 'complain_info' => $complain_info, 'appeal_pic' => $appeal_pic, 'complain_pic' => $complain_pic));
    }

    /**
     * @api {POST} api/Sellercomplain/appeal_save 保存申诉
     * @apiVersion 1.0.0
     * @apiGroup Sellercomplain
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} input_complain_id 投诉ID
     * @apiParam {String} pic_name 投诉凭证 用,分隔多个投诉凭证
     * @apiParam {String} input_appeal_message 申诉内容
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function appeal_save() {
        $complain_id = intval(input('post.input_complain_id'));
        $pic_name = input('post.pic_name/a');
        //获取投诉详细信息
        $complain_info = $this->get_complain_info($complain_id);
        //检查当前是不是投诉状态
        if (intval($complain_info['complain_state']) !== self::STATE_APPEAL) {
            ds_json_encode(10001, lang('param_error'));
        }
        $input = array();
        $input['appeal_message'] = input('post.input_appeal_message');

        $sellercomplain_validate = ds_validate('sellercomplain');
        if (!$sellercomplain_validate->scene('appeal_save')->check($input)) {
            ds_json_encode(10001, $sellercomplain_validate->getError());
        }


        $input['appeal_pic1'] = isset($pic_name[0]) ? $pic_name[0] : '';
        $input['appeal_pic2'] = isset($pic_name[1]) ? $pic_name[1] : '';
        $input['appeal_pic3'] = isset($pic_name[2]) ? $pic_name[2] : '';



        $input['appeal_datetime'] = TIMESTAMP;
        $input['complain_state'] = self::STATE_TALK;
        $condition = array();
        $condition[] = array('complain_id', '=', $complain_id);
        //保存申诉信息
        $complain_model = model('complain');
        $complain_id = $complain_model->editComplain($input, $condition);
        $this->recordSellerlog('投诉申诉处理，投诉编号：' . $complain_id);
        ds_json_encode(10000, lang('appeal_submit_success'));
    }

    /**
     * @api {POST} api/Sellercomplain/upload_pic 上传凭证
     * @apiVersion 1.0.0
     * @apiGroup Sellercomplain
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     *
     * @apiParam {File} complain_pic 投诉凭证
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {String} result.file_name  文件名称
     * @apiSuccess {String} result.pic  文件完整路径
     */
    public function upload_pic() {
        if (!empty($_FILES['complain_pic']['name'])) {
            $file_name = $this->member_info['member_id'] . '_' . date('YmdHis') . rand(10000, 99999) . '.png';
            $res = ds_upload_pic(ATTACH_PATH . DIRECTORY_SEPARATOR . 'complain', 'complain_pic', $file_name);
            if ($res['code']) {
                $file_name = $res['data']['file_name'];
            } else {
                ds_json_encode(10001, $res['msg']);
            }
            $pic = ds_get_pic(ATTACH_PATH . DIRECTORY_SEPARATOR . 'complain', $file_name);
            ds_json_encode(10000, '', array('file_name' => $file_name, 'pic' => $pic));
        } else {
            ds_json_encode(10001, lang('file_empty'));
        }
    }

    /**
     * @api {POST} api/Sellercomplain/apply_handle 申请仲裁
     * @apiVersion 1.0.0
     * @apiGroup Sellercomplain
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} input_complain_id 投诉ID
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function apply_handle() {
        $complain_id = intval(input('post.input_complain_id'));
        //获取投诉详细信息
        $complain_info = $this->get_complain_info($complain_id);
        $complain_state = intval($complain_info['complain_state']);
        //检查当前是不是投诉状态
        if ($complain_state < self::STATE_TALK || $complain_state === 99) {
            ds_json_encode(10001, lang('param_error'));
        }
        $update_array = array();
        $update_array['complain_state'] = self::STATE_HANDLE;
        $condition = array();
        $condition[] = array('complain_id', '=', $complain_id);
        //保存投诉信息
        $complain_model = model('complain');
        $complain_id = $complain_model->editComplain($update_array, $condition);
        $this->recordSellerlog('投诉申请仲裁，投诉编号：' . $complain_id);
        ds_json_encode(10000, lang('handle_submit_success'));
    }

    /**
     * @api {POST} api/Sellercomplain/get_complain_talk 根据投诉id获取投诉对话
     * @apiVersion 1.0.0
     * @apiGroup Sellercomplain
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} input_complain_id 投诉ID
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Object[]} result.talk_list  对话列表
     * @apiSuccess {String} result.talk_list.css  对话类型 admin管理员，accused被告人，accuser原告人
     * @apiSuccess {String} result.talk_list.talk  对话内容
     */
    public function get_complain_talk() {
        $complain_id = intval(input('post.complain_id'));
        $complain_info = $this->get_complain_info($complain_id);
        $complaintalk_model = model('complaintalk');
        $param = array();
        $param['complain_id'] = $complain_id;
        $complain_talk_list = $complaintalk_model->getComplaintalkList($param);
        $talk_list = array();
        $i = 0;
        if (!empty($complain_talk_list)) {
            foreach ($complain_talk_list as $talk) {
                $talk_list[$i]['css'] = $talk['talk_member_type'];
                $talk_list[$i]['talk'] = date("Y-m-d H:i:s", $talk['talk_datetime']);
                switch ($talk['talk_member_type']) {
                    case 'accuser':
                        $talk_list[$i]['talk'] .= lang('complain_accuser');
                        break;
                    case 'accused':
                        $talk_list[$i]['talk'] .= lang('complain_accused');
                        break;
                    case 'admin':
                        $talk_list[$i]['talk'] .= lang('complain_admin');
                        break;
                    default:
                        $talk_list[$i]['talk'] .= lang('complain_unknow');
                }
                if (intval($talk['talk_state']) === 2) {
                    $talk['talk_content'] = lang('talk_forbit_message');
                }
                $talk_list[$i]['talk'] .= '(' . $talk['talk_member_name'] . ')' . lang('complain_text_say') . ':' . $talk['talk_content'];
                $i++;
            }
        }
        ds_json_encode(10000, '', array('talk_list' => $talk_list));
    }

    /**
     * @api {POST} api/Sellercomplain/publish_complain_talk 根据发布投诉对话
     * @apiVersion 1.0.0
     * @apiGroup Sellercomplain
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} input_complain_id 投诉ID
     * @apiParam {String} complain_talk 发言内容
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function publish_complain_talk() {
        $complain_id = intval(input('post.complain_id'));
        $complain_talk = trim(input('post.complain_talk'));
        $talk_len = strlen($complain_talk);
        if ($talk_len > 0 && $talk_len < 255) {
            $complain_info = $this->get_complain_info($complain_id);
            $complain_state = intval($complain_info['complain_state']);
            //检查投诉是否是可发布对话状态
            if ($complain_state > self::STATE_APPEAL && $complain_state < self::STATE_FINISH) {
                $complaintalk_model = model('complaintalk');
                $param = array();
                $param['complain_id'] = $complain_id;
                $param['talk_member_id'] = $complain_info['accused_id'];
                $param['talk_member_name'] = $complain_info['accused_name'];
                $param['talk_member_type'] = $complain_info['member_status'];
                $param['talk_content'] = $complain_talk;
                $param['talk_state'] = 1;
                $param['talk_admin'] = 0;
                $param['talk_datetime'] = TIMESTAMP;
                if ($complaintalk_model->addComplaintalk($param)) {
                    ds_json_encode(10000, ('talk_send_success'));
                } else {
                    ds_json_encode(10001, ('talk_send_fail'));
                }
            } else {
                ds_json_encode(10001, lang('talk_state_error'));
            }
        } else {
            ds_json_encode(10001, lang('talk_null'));
        }
    }

    /*
     * 获取投诉信息
     */

    private function get_complain_info($complain_id) {
        if (empty($complain_id)) {
            ds_json_encode(10001, lang('param_error'));
        }
        $complain_model = model('complain');
        $complain_info = $complain_model->getOneComplain($complain_id);
        if ($complain_info['accused_id'] != $this->store_info['store_id']) {
            ds_json_encode(10001, lang('param_error'));
        }
        $complain_info['member_status'] = 'accused';
        $complain_info['complain_state_text'] = $this->get_complain_state_text($complain_info['complain_state']);
        return $complain_info;
    }

    /*
     * 获得投诉状态文本
     */

    private function get_complain_state_text($complain_state) {
        switch (intval($complain_state)) {
            case self::STATE_NEW:
                return lang('complain_state_new');
                break;
            case self::STATE_APPEAL:
                return lang('complain_state_appeal');
                break;
            case self::STATE_TALK:
                return lang('complain_state_talk');
                break;
            case self::STATE_HANDLE:
                return lang('complain_state_handle');
                break;
            case self::STATE_FINISH:
                return lang('complain_state_finish');
                break;
            default:
                ds_json_encode(10001, lang('param_error'));
        }
    }

}
