<?php

namespace app\command;

use app\common\model\user\User;
use app\common\repositories\movie\CinemaRepository;
use app\common\repositories\movie\CinemaSchedRepository;
use app\common\repositories\movie\FilmRepository;
use app\common\repositories\movie\MovieRepository;
use crmeb\services\ApiResponseService;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

class CinemaSchedCommand extends Command
{
    private $page = 1;
    private $limit = 1000000;

    protected function configure()
    {
        // 指令配置
        $this->setName('cinema_film_sched')->setDescription('电影-影院场次列表');
    }

    protected function execute(Input $input, Output $output)
    {
        $date = strtotime(date('Y-m-d'));
        try {
            /** @var CinemaRepository $cinema */
            $cinema = app()->make(CinemaRepository::class);
            // 获取影院列表
            $result = $cinema->getLocalCinema($this->page, $this->limit, '', '', [], [], 0);
            $cinema_sign_list = $cinemainfo = [];
            foreach ($result['cinema_list'] as $subKey => $cinema) {
                $cinema_sign_list[] = $cinema['cinema_sign'];
                $cinemainfo[$cinema['cinema_sign']] = $cinema;
            }

            /** @var FilmRepository $filmRepository */
            $filmRepository = app()->make(FilmRepository::class);
            // 获取{2个月内}已上映影片列表
            $filmResult = $filmRepository->getFilmByStartEndDate($this->page, $this->limit, strtotime('-2 month', $date), $date);
            if ($filmResult && $cinema_sign_list) {
                foreach ($filmResult as $key => $film) {
                    // 获取排片影院
//                    $scheduledCinema = Db::name('movie_cinema_sched')
//                        ->where('film_sign', $film['film_sign'])->where('show_date', '>=', $date)
//                        ->whereIn('cinema_sign', $cinema_sign_list)
//                        ->field('film_sign,cinema_sign')->group('cinema_sign')->select();
//                    $diffUnscheduledCinema = !empty($scheduledCinema) ?
//                        array_diff($cinema_sign_list, array_column($scheduledCinema->toArray(), 'cinema_sign', 'cinema_sign')) : $cinema_sign_list;
//                    $this->batchInsertUnscheduledCinema($film, $cinemainfo, $diffUnscheduledCinema);

                    $diffUnscheduledCinema = [];
                    // 获取是否存在未排片影院记录 @todo 影院未排片，不请求第三方接口获取排片场次
                    $unscheduledCinema = Db::name('movie_cinema_unsched')->where('film_sign', $film['film_sign'])->whereIn('cinema_sign', $cinema_sign_list)
                        ->field('film_sign,cinema_sign')->select();
                    // 从总的影院、未排片影院中取出差异数据，得到排片影院
                    $diffScheduledCinema = !empty($unscheduledCinema) ? array_diff($cinema_sign_list, array_column($unscheduledCinema->toArray(), 'cinema_sign')) : $cinema_sign_list;
                    // 将{影片和排片影院}调用第三方获取排片场次
                    foreach ($diffScheduledCinema as $cinemaKey => $cinemaSignValue) {
                        $res = $this->doCinemaSched($film, $cinemainfo[$cinemaSignValue]);
                        if (!$res) {
                            $diffUnscheduledCinema[] = $cinemaSignValue;
                        }
                    }
                    // 未排片影院批量插入
                    if ($diffUnscheduledCinema) $this->batchInsertUnscheduledCinema($film, $cinemainfo, $diffUnscheduledCinema);
                }
            }
        } catch (\Exception $exception) {
            var_dump($exception->getMessage(), $exception->getFile(), $exception->getLine());
        }
    }

    /**
     * 批量插入未排片影院
     *
     * @param $film
     * @param $cinemainfo
     * @param $diffUnscheduledCinema
     * @return void
     */
    private function batchInsertUnscheduledCinema($film, $cinemainfo, $diffUnscheduledCinema)
    {
        $data = [];

        foreach ($diffUnscheduledCinema as $key => $value) {
            $data[] = [
                'film_sign' => $film['film_sign'],
                'film_name' => $film['film_name'],
                'cinema_sign' => $cinemainfo[$value]['cinema_sign'],
                'cinema_name' => $cinemainfo[$value]['cinema_name'],
                'create_time' => time()
            ];
        }
        if ($data) Db::name('movie_cinema_unsched')->insertAll($data);
    }

    /**
     *  电影-获取影院场次列表
     *
     * @param $film
     * @param $cinema
     * @return array|mixed|string
     * @throws \think\db\exception\DbException
     */
    private function doCinemaSched($film, $cinema)
    {
        /** @var MovieRepository $cinema_filmRepository */
        $cinema_filmRepository = app()->make(MovieRepository::class);
        // 获取排片场次
        $cinema_sched = $cinema_filmRepository->getCinemaSched($film['film_sign'], $cinema['cinema_sign']);
        if (!empty($cinema_sched)) {
            // 写入排片场次数据
            $this->createCinemaSched($cinema_sched, $cinema);
        }

        return $cinema_sched;
    }

    /**
     * 写入排片场次数据
     *
     * @param $list
     * @param $cinema
     * @return void
     * @throws \think\db\exception\DbException
     */
    private function createCinemaSched($list, $cinema)
    {
        foreach ($list as $key => $sched) {
            foreach ($sched as $subKey => $value) {
                $params = [
                    'relation_id' => $value['relation_id'],
                    'sched_sign' => $value['sched_sign'],
                    'film_sign' => $value['film_sign'],
                    'film_name' => $value['film_name'],
                    'show_date' => strtotime(date('Y') . '-' . $value['show_date']),
                    'show_time' => trim($value['show_time']),
                    'cinema_sign' => $cinema['cinema_sign'],
                    'cinema_name' => $cinema['cinema_name'],
                    'address' => $cinema['address'],
                    'longitude' => $cinema['longitude'],
                    'latitude' => $cinema['latitude'],
                    'hall_sign' => $value['hall_sign'],
                    'hall_name' => $value['hall_name'],
                    'stop_sell_time' => strtotime($value['stop_sell_time']),
                    'price' => $value['price'], // 销售价
                    'cost_price' => $value['cost_price'], // 原价
                    'channel_price' => json_encode($value['channel_price'], JSON_FORCE_OBJECT)
                ];
                $where = [
                    'relation_id' => $value['relation_id'], 'sched_sign' => $value['sched_sign'], 'film_sign' => $value['film_sign'], 'cinema_sign' => $params['cinema_sign']
                ];
                $model = Db::name('movie_cinema_sched')->where($where)->find();
                if (empty($model)) {
                    $params['create_time'] = time();
                    Db::name('movie_cinema_sched')->insert($params);
                } else {
                    $params['update_time'] = time();
                    Db::name('movie_cinema_sched')->where('id', $model['id'])->update($params);
                }
            }
        }
    }
}