<?php

namespace App\Http\Controllers\Open;

use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Models\ProductAttribute;
use App\Traits\JsonResponseTrait;
use App\Http\Controllers\Controller;
use App\Models\TranslateContent;
use App\Models\TranslateLog;
use App\Models\ProductIntroduction;

class TranslateController extends Controller
{

    use JsonResponseTrait;

    public function __construct()
    {
        $this->middleware('token');
    }

    /**
     * 一键翻译
     */
    public function index(Request $request)
    {
        // 获取语言版本 Lang
        // $data['langs']  = config('translateLang');
        // $data['langs']  = Lang::where('buy', 1)->where('slug', '!=', 'en')->get()->pluck('slug')->toArray();
        $models = $request->input('models', []);
        $data = [];
        // 推送产品ids
        if (empty($models) || isset($models['product'])) {
            $query = config('translate.models')['product']::select('id', 'product_id')->where('lang', config('setting.lang'));
            if (!empty($models['product']) && is_array($models['product'])) {
                $query->whereIn(config('translate.idType.product'), $models['product']);
            }
            $productData = $query->get();
            if (count($product = $productData->pluck('id')) > 0) {
                $data['ids']['product'] = $product;
                if (count($attrs = ProductAttribute::select('id')->whereIn('product_id', $productData->pluck('product_id'))->where('lang', config('setting.lang'))->get()->pluck('id')) > 0) {
                    $data['ids']['productAttr'] = $attrs;
                }
                if (count($intros = ProductIntroduction::select('id')->whereIn('product_id', $productData->pluck('product_id'))->where('lang', config('setting.lang'))->get()->pluck('id')) > 0) {
                    $data['ids']['productIntro'] = $intros;
                }
            }
        }

        // 推送产品分类
        if (empty($models) || isset($models['productCate'])) {
            $query = config('translate.models')['productCate']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['productCate']) && is_array($models['productCate'])) {
                $query->whereIn(config('translate.idType.productCate'), $models['productCate']);
            }
            if (count($productCate = $query->get()->pluck('id')) > 0) {
                $data['ids']['productCate'] = $productCate;
            }
        }

        // 推送产品属性
        if (empty($models) || isset($models['attribute'])) {
            $query = config('translate.models')['attribute']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['attribute']) && is_array($models['attribute'])) {
                $query->whereIn(config('translate.idType.attribute'), $models['attribute']);
            }
            if (count($attribute = $query->get()->pluck('id')) > 0) {
                $data['ids']['attribute'] = $attribute;
            }
        }

        // 推送新闻ids
        if (empty($models) || isset($models['news'])) {
            $query = config('translate.models')['news']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['news']) && is_array($models['news'])) {
                $query->whereIn(config('translate.idType.news'), $models['news']);
            }
            if (count($news = $query->get()->pluck('id')) > 0) {
                $data['ids']['news'] = $news;
            }
        }

        if (empty($models) || isset($models['newsCate'])) {
            $query = config('translate.models')['newsCate']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['newsCate']) && is_array($models['newsCate'])) {
                $query->whereIn(config('translate.idType.newsCate'), $models['newsCate']);
            }
            if (count($newsCate = $query->get()->pluck('id')) > 0) {
                $data['ids']['newsCate'] = $newsCate;
            }
        }

        // 推送案例ids
        if (empty($models) || isset($models['case'])) {
            $query = config('translate.models')['case']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['case']) && is_array($models['case'])) {
                $query->whereIn(config('translate.idType.case'), $models['case']);
            }
            if (count($case = $query->get()->pluck('id')) > 0) {
                $data['ids']['case'] = $case;
            }
        }

        if (empty($models) || isset($models['caseCate'])) {
            $query = config('translate.models')['caseCate']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['caseCate']) && is_array($models['caseCate'])) {
                $query->whereIn(config('translate.idType.caseCate'), $models['caseCate']);
            }
            if (count($caseCate = $query->get()->pluck('id')) > 0) {
                $data['ids']['caseCate'] = $caseCate;
            }
        }

        // 推送单页ids
        if (empty($models) || isset($models['page'])) {
            $query = config('translate.models')['page']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['page']) && is_array($models['page'])) {
                $query->whereIn(config('translate.idType.page'), $models['page']);
            }
            if (count($page = $query->get()->pluck('id')) > 0) {
                $data['ids']['page'] = $page;
            }
        }

        if (empty($models) || isset($models['pageCate'])) {
            $query = config('translate.models')['pageCate']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['pageCate']) && is_array($models['pageCate'])) {
                $query->whereIn(config('translate.idType.pageCate'), $models['pageCate']);
            }
            if (count($pageCate = $query->get()->pluck('id')) > 0) {
                $data['ids']['pageCate'] = $pageCate;
            }
        }

        // 推送视频ids
        if (empty($models) || isset($models['video'])) {
            $query = config('translate.models')['video']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['video']) && is_array($models['video'])) {
                $query->whereIn(config('translate.idType.video'), $models['video']);
            }
            if (count($video = $query->get()->pluck('id')) > 0) {
                $data['ids']['video'] = $video;
            }
        }

        if (empty($models) || isset($models['videoCate'])) {
            $query = config('translate.models')['videoCate']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['videoCate']) && is_array($models['videoCate'])) {
                $query->whereIn(config('translate.idType.videoCate'), $models['videoCate']);
            }
            if (count($videoCate = $query->get()->pluck('id')) > 0) {
                $data['ids']['videoCate'] = $videoCate;
            }
        }

        // 推送下载ids
        if (empty($models) || isset($models['download'])) {
            $query = config('translate.models')['download']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['download']) && is_array($models['download'])) {
                $query->whereIn(config('translate.idType.download'), $models['download']);
            }
            if (count($download = $query->get()->pluck('id')) > 0) {
                $data['ids']['download'] = $download;
            }
        }

        if (empty($models) || isset($models['downloadCate'])) {
            $query = config('translate.models')['downloadCate']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['downloadCate']) && is_array($models['downloadCate'])) {
                $query->whereIn(config('translate.idType.downloadCate'), $models['downloadCate']);
            }
            if (count($downloadCate = $query->get()->pluck('id')) > 0) {
                $data['ids']['downloadCate'] = $downloadCate;
            }
        }

        // 推送招聘ids
        if (empty($models) || isset($models['job'])) {
            $query = config('translate.models')['job']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['job']) && is_array($models['job'])) {
                $query->whereIn(config('translate.idType.job'), $models['job']);
            }
            if (count($job = $query->get()->pluck('id')) > 0) {
                $data['ids']['job'] = $job;
            }
        }

        if (empty($models) || isset($models['jobCate'])) {
            $query = config('translate.models')['jobCate']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['jobCate']) && is_array($models['jobCate'])) {
                $query->whereIn(config('translate.idType.jobCate'), $models['jobCate']);
            }
            if (count($jobCate = $query->get()->pluck('id')) > 0) {
                $data['ids']['jobCate'] = $jobCate;
            }
        }

        // 推送导航ids
        if (empty($models) || isset($models['nav'])) {
            $query = config('translate.models')['nav']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['nav']) && is_array($models['nav'])) {
                $query->whereIn(config('translate.idType.nav'), $models['nav']);
            }
            if (count($nav = $query->get()->pluck('id')) > 0) {
                $data['ids']['nav'] = $nav;
            }
        }

        // 推送标签ids
        if (empty($models) || isset($models['tag'])) {
            $query = config('translate.models')['tag']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['tag']) && is_array($models['tag'])) {
                $query->whereIn(config('translate.idType.tag'), $models['tag']);
            }
            if (count($tag = $query->get()->pluck('id')) > 0) {
                $data['ids']['tag'] = $tag;
            }
        }

        // 推送自定义分页
        if (empty($models) || isset($models['block'])) {
            $query = config('translate.models')['block']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['block']) && is_array($models['block'])) {
                $query->whereIn(config('translate.idType.block'), $models['block']);
            }
            if (count($block = $query->get()->pluck('id')) > 0) {
                $data['ids']['block'] = $block;
            }
        }

        // 推送广告
        if (empty($models) || isset($models['ad'])) {
            $query = config('translate.models')['ad']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['ad']) && is_array($models['ad'])) {
                $query->whereIn(config('translate.idType.ad'), $models['ad']);
            }
            if (count($ad = $query->get()->pluck('id')) > 0) {
                $data['ids']['ad'] = $ad;
            }
        }

        // 推送配置
        if (empty($models) || isset($models['setting'])) {
            $query = config('translate.models')['setting']::select('id', 'name')->where('lang', config('setting.lang'));
            if (!empty($models['setting']) && is_array($models['setting'])) {
                $query->whereIn(config('translate.idType.setting'), array_values(array_intersect(config('translate.settingFields'), $models['setting'])));
            } else {
                $query->whereIn(config('translate.idType.setting'), config('translate.settingFields'));
            }
            if (count($setting = $query->get()->pluck('name')) > 0) {
                $data['ids']['setting'] = $setting;
            }
        }

        // 图文管理
        if (empty($models) || isset($models['photoGroup'])) {
            $query = config('translate.models')['photoGroup']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['photoGroup']) && is_array($models['photoGroup'])) {
                $query->whereIn(config('translate.idType.photoGroup'), $models['photoGroup']);
            }
            if (count($photoGroup = $query->get()->pluck('id')) > 0) {
                $data['ids']['photoGroup'] = $photoGroup;
            }
        }

        // 推送相册ids
        if (empty($models) || isset($models['album'])) {
            $query = config('translate.models')['album']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['album']) && is_array($models['album'])) {
                $query->whereIn(config('translate.idType.album'), $models['album']);
            }
            if (count($album = $query->get()->pluck('id')) > 0) {
                $data['ids']['album'] = $album;
            }
        }

        if (empty($models) || isset($models['albumCate'])) {
            $query = config('translate.models')['albumCate']::select('id')->where('lang', config('setting.lang'));
            if (!empty($models['albumCate']) && is_array($models['albumCate'])) {
                $query->whereIn(config('translate.idType.albumCate'), $models['albumCate']);
            }
            if (count($albumCate = $query->get()->pluck('id')) > 0) {
                $data['ids']['albumCate'] = $albumCate;
            }
        }

        return $this->success($data);
        
    }
    
    public function getContent(Request $request)
    {
        $type  = $request->input('type');
        $id    = $request->input('id');
        $model = config('translate.models')[$type];
        $lang      = $request->input('lang');

        //  如果主语言与翻译语言一致，跳过
        if ($lang == config('setting.lang')) {
            return $this->success([]);
        }

        if ($type == 'setting') {
            $data  = $model::where('lang', config('setting.lang'))->where('name', $id)->first();
        } else {
            $data  = $model::find($id);
        }

        // 跳过翻译
        if ($data && $request->input('status') == 2) {
            $idType    = config('translate.idType')[$type];
            $name      = config('translate.nameField')[$type];
            $modelId = $type == 'setting' ? $id : $data[$idType];
            if (in_array($type, ['ad', 'productIntro']) && isset($data['code'])) {
                $translateData = $model::where($idType, $modelId)->where('lang', $lang)->where('code', $data['code'])->first();
            } else {
                $translateData = $model::where($idType, $modelId)->where('lang', $lang)->first();
            }
            if ($translateData && isset($translateData[$name]) && $translateData[$name]) {

                $transContent = TranslateContent::where('translate_id', $id)->orderBy('log_id', 'DESC')->where('type', $type)->where('lang', $lang)->whereIn('status', [0, 2])->first();

                if ($transContent) {
                    $transContent->update(['status' => 1]);
                    if (count(TranslateContent::where('log_id', $transContent->log_id)->whereIn('status', [0, 2])->get()->pluck('id')) < 1) {
                        TranslateLog::where('id', $transContent->log_id)->update([
                            'status' => 1,
                            'end_at' => Carbon::now()
                        ]);
                    }
                }

                return $this->success([]);
            }
        }

        return $this->success($data);
    }
    
    public function putContent(Request $request)
    {
        $status    = $request->input('status');    // 1为覆盖  2为跳过
        $lang      = $request->input('lang');
        $type      = $request->input('type');
        $idType    = config('translate.idType')[$type];
        $model     = config('translate.models')[$type];
        $name      = config('translate.nameField')[$type];
        $id        = $request->input($idType);
        $data      = $request->except(['type', 'status']);

        if (isset($data['imgs'])) {
            $data['imgs'] = json_encode($data['imgs']);
        }

        if (in_array($type, ['ad', 'productIntro']) && isset($data['code'])) {
            $exists    = $model::where($idType, $id)->where('lang', $lang)->where('code', $data['code'])->exists();
        } elseif ($type == 'productAttr') {
            $exists    = $model::where($idType, $id)->where('lang', $lang)->where('attribute_id', $data['attribute_id'])->exists();
        } else {
            $exists    = $model::where($idType, $id)->where('lang', $lang)->exists();
        }

        if ($status == 1) { 
            if ($exists) {
                if (in_array($type, ['ad', 'productIntro']) && isset($data['code'])) {
                    $result = $model::where($idType, $id)->where('lang', $lang)->where('code', $data['code'])->update($data);
                } elseif ($type == 'productAttr') {
                    $result = $model::where($idType, $id)->where('lang', $lang)->where('attribute_id', $data['attribute_id'])->update($data);
                } else {
                    $result = $model::where($idType, $id)->where('lang', $lang)->update($data);
                }
            } else {
                $result = $model::insert($data);
            }
        } else {
            if (in_array($type, ['ad', 'productIntro']) && isset($data['code'])) {
                $isNull = $model::where($idType, $id)->where('lang', $lang)->where($name, '=', '')->where('code', $data['code'])->exists();
            } elseif ($type == 'productAttr') {
                $isNull = $model::where($idType, $id)->where('lang', $lang)->where($name, '=', '')->where('attribute_id', $data['attribute_id'])->exists();
            } else {
                $isNull = $model::where($idType, $id)->where('lang', $lang)->where($name, '=', '')->exists();
            }
            if ($exists && $isNull) {
                if (in_array($type, ['ad', 'productIntro']) && isset($data['code'])) {
                    $result = $model::where($idType, $id)->where('lang', $lang)->where('code', $data['code'])->update($data);
                } elseif ($type == 'productAttr') {
                    $result = $model::where($idType, $id)->where('lang', $lang)->where('attribute_id', $data['attribute_id'])->update($data);
                }  else {
                    $result = $model::where($idType, $id)->where('lang', $lang)->update($data);
                }
            } elseif (!$exists) {
                $result = $model::insert($data);
            }
        }

        $translate_id = $request->header('translate-id');
        $translate_number = $request->header('translate-number');
        $exception = $request->header('exception');

        $transContent = TranslateContent::where('translate_id', $translate_id)->orderBy('log_id', 'DESC')->where('type', $type)->where('lang', $lang)->whereIn('status', [0, 2])->first();

        if ($transContent) {
            if ($exception) {
                $transContent->update([
                    'status' => 2,
                    'exception' => $exception
                ]);
            } else {
                $transContent->update([
                    'status' => 1,
                    'translate_number' => $translate_number ?: 0
                ]);
            }

            if (count(TranslateContent::where('log_id', $transContent->log_id)->whereIn('status', [0, 2])->get()->pluck('id')) < 1) {
                TranslateLog::where('id', $transContent->log_id)->update([
                    'status' => 1,
                    'end_at' => Carbon::now(),
                    'exception' => $exception ?: ''
                ]);
            }
        }

        return $this->success();
    }
    
}
