<?php

namespace app\admin\controller\member;

use app\admin\validate\life\CinemaIlkValidate;
use app\admin\validate\member\WellnessRecordValidate;
use app\common\File;
use app\controller\Curd;
use app\model\CinemaIlk as CinemaIlkModel;
use app\model\Content;
use app\model\SysField;
use app\model\SysUpload;
use app\model\WellnessRecord;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Tinywan\Jwt\JwtToken;

class WellnessRecordController extends Curd
{

    public function __construct()
    {
        $this->model = new WellnessRecord();
        $this->validate = true;
        $this->validateClass = new WellnessRecordValidate();
    }

    public function info(Request $request): Response
    {
        $primaryKey = $this->model->getKeyName();
        $validateArr = [
            $primaryKey => $request->get('id')
        ];

        if ($this->validate && !$this->validateClass->scene('info')->check($validateArr)) {
            return json_fail($this->validateClass->getError());
        }

        $data = $this->model->where($primaryKey, $request->get('id'))->first();
        if ($data['wellness_record_category'] == 'Examine') {
            $data->wellness_record_status = 'ACTIVED';
            $data->save();
        }

        if (method_exists($this, "afterInfoQuery")) {
            $data = call_user_func([$this, "afterInfoQuery"], $data);
        }

        return json_success('', $data);
    }

    public function insert(Request $request): Response
    {
        if ($this->validate && !$this->validateClass->scene('add')->check($request->post())) {
            return json_fail($this->validateClass->getError());
        }

        try {
            $data = $this->insertInput($request);
            if ($data['wellness_record_category'] == 'Examine' && !empty($data['wellness_record_file_json'])) {
                $recordJson = json_decode($data['wellness_record_file_json'], true);
                foreach ($recordJson as $file) {
                    unset($data['wellness_record_file_json']);
                    $data['wellness_record_file_json'] = json_encode($file);
                    $this->doInsert($data);
                }
            } else {
                $this->doInsert($data);
            }

        } catch (BusinessException $customException) {
            return json_fail($customException->getMessage());
        } catch (\Exception $e) {
            dump($e->getMessage(), $e->getFile(), $e->getLine());
            return json_fail('数据写入失败');
        }
        return json_success('success');
    }

    /**
     * @Desc 我的档案
     * @Author Gorden
     * @Date 2024/4/1 10:54
     *
     * @param $memberId
     * @return mixed
     */
    public function my($memberId)
    {
        $query = $this->model->where('wellness_record_category', 'Archives')
            ->where('join_wellness_record_member_id', $memberId);
        $paginator = $query->paginate(20);
        $total = $paginator->total();
        $items = $paginator->items();
        $itemsNew = [];
        foreach ($items as $item) {
            $itemNew = [
                'wellness_record_id' => $item->wellness_record_id,
                'join_wellness_record_member_id' => $item->join_wellness_record_member_id,
                'wellness_record_status' => $item->wellness_record_status,
                'wellness_record_name' => $item->wellness_record_name,
                'wellness_record_datetime' => $item->wellness_record_datetime,
                'wellness_record_json' => $item->wellness_record_json,
                'wellness_record_content' => $item->wellness_record_content,
                'wellness_record_remark' => $item->wellness_record_remark,
                'wellness_record_extend_json' => $item->wellness_record_extend_json,
                'wellness_record_addtimes' => date('Y-m-d H:i:s', $item->wellness_record_addtimes),
            ];
            if (!empty($item->wellness_record_file_json)) {
                $item->wellness_record_file_json = json_decode($item->wellness_record_file_json, true);
                $upload = SysUpload::whereIn('upload_file_path', $item->wellness_record_file_json)->get();
                foreach ($upload as $value) {
                    $itemNew['wellness_record_file_json'][] = [
                        'url' => getenv('STORAGE_DOMAIN') . $value->upload_file_path,
                        'name' => $value->upload_name
                    ];
                }
            }

            $itemsNew[] = $itemNew;
        }

        $data = [
            'total' => $total,
            'rows' => $itemsNew
        ];
        return json(['code' => 200, 'msg' => 'success', 'data' => $data]);
    }

    /**
     * @Desc 我的医嘱
     * @Author Gorden
     * @Date 2024/4/2 8:44
     *
     * @param $memberId
     * @return Response
     */
    public function advice(Request $request)
    {
        $memberId = $request->get('member_id');
        $query = $this->model->where('wellness_record_category', 'Advice')
            ->where('join_wellness_record_member_id', $memberId)
            ->orderBy('wellness_record_addtimes', 'desc');
        $paginator = $query->paginate(20);
        $total = $paginator->total();
        $items = $paginator->items();
        $itemsNew = [];
        foreach ($items as $item) {
            $itemNew = [
                'wellness_record_id' => $item->wellness_record_id,
                'join_wellness_record_member_id' => $item->join_wellness_record_member_id,
                'wellness_record_status' => $item->wellness_record_status,
                'wellness_record_name' => $item->wellness_record_name,
                'wellness_record_datetime' => $item->wellness_record_datetime,
                'wellness_record_content' => $item->wellness_record_content,
                'wellness_record_remark' => $item->wellness_record_remark,
                'wellness_record_extend_json' => $item->wellness_record_extend_json,
                'wellness_record_addtimes' => $item->wellness_record_addtimes,
                'wellness_record_file_json' => json_decode($item->wellness_record_file_json),
                'wellness_record_json' => json_decode($item->wellness_record_json, true),
            ];
            if (!empty($itemNew['wellness_record_json'])) {
                foreach ($itemNew['wellness_record_json'] as $key => $item) {
                    if (empty($item['entry'])) {
                        $itemNew['wellness_record_json'][$key]['entry'] = 'none';
                    }
                }
            }

            $itemsNew[] = $itemNew;
        }

        $data = [
            'total' => $total,
            'rows' => $itemsNew
        ];
        return json(['code' => 200, 'msg' => 'success', 'data' => $data]);
    }

    /**
     * @Desc 添加医嘱
     * @Author Gorden
     * @Date 2024/11/29 11:27
     *
     * @param Request $request
     * @return Response
     */
    public function insertAdvice(Request $request): Response
    {
        try {
            $params = $request->post();
            $params['wellness_record_file_json'] = json_encode($params['wellness_record_file_json']);
            $params['wellness_record_json'] = json_encode($params['wellness_record_json']);
            $data = $this->inputFilter($params);
            $data['wellness_record_datetime'] = date('Y-m-d H:i:s', strtotime($data['wellness_record_datetime']));
            $this->doInsert($data);
        } catch (BusinessException $customException) {
            return json_fail($customException->getMessage());
        } catch (\Exception $e) {
            return json_fail('数据写入失败11');
        }
        return json_success('success');
    }

    /**
     * @Desc 编辑医嘱
     * @Author Gorden
     * @Date 2024/11/29 11:27
     *
     * @param Request $request
     * @return Response
     */
    public function updateAdvice(Request $request): Response
    {
        try {
            [$id, $data] = $this->updateAdviceInput($request);
            $this->doUpdate($id, $data);
        } catch (BusinessException $e) {
            return json_fail($e->getMessage());
        } catch (\Exception $e) {
            dump($e->getMessage());
            return json_fail('数据更新失败');
        }

        return json_success('success');
    }

    /**
     * @Desc 编辑医嘱预处理
     * @Author Gorden
     * @Date 2024/11/29 13:07
     *
     * @param Request $request
     * @return array
     * @throws BusinessException
     */
    protected function updateAdviceInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }
        $params = $request->post();
        $params['wellness_record_file_json'] = json_encode($params['wellness_record_file_json']);
        $params['wellness_record_json'] = json_encode($params['wellness_record_json']);

        $data = $this->inputFilter($params);
        $data['wellness_record_datetime'] = date('Y-m-d H:i:s', strtotime($data['wellness_record_datetime']));

        unset($data[$primary_key]);
        return [$id, $data];
    }

    /**
     * @Desc 我的档案
     * @Author Gorden
     * @Date 2024/4/22 10:46
     *
     * @param $memberId
     * @return Response
     */
    public function archives(Request $request)
    {
        $memberId = $request->get('member_id');
        $archives = $this->model->where('wellness_record_category', 'Archives')
            ->where('join_wellness_record_member_id', $memberId)
            ->first();
        if ($archives) {
            if (!empty($archives->wellness_record_json)) {
//                $recordJson = json_decode($archives->wellness_record_json);
////                $fields = SysField::pluck('field_name', 'field_form_key');
//                $newJson = [];
//                foreach ($recordJson as $key => $item) {
//                    if (isset($fields[$key])) {
//                        $newJson[$fields[$key]] = is_array($item) ? implode(',', $item) : $item;
//                    }
//                }
                $archives->wellness_record_json = json_decode($archives->wellness_record_json);;
            }
            if (!empty($archives->wellness_record_file_json)) {
                $archives->wellness_record_file_json = json_decode($archives->wellness_record_file_json, true);
                $recordFileJson = [];
                foreach ($archives->wellness_record_file_json as $value) {
                    $recordFileJson[] = [
                        'url' => isset($value['url']) ? getenv('STORAGE_DOMAIN') . $value['url'] : '',
                        'name' => isset($value['name']) ? $value['name'] : ''
                    ];
                }

                $archives->wellness_record_file_json = $recordFileJson;
            }
        }

        return json_success('', $archives);
    }

    public function checkup(Request $request)
    {
        $memberId = $request->get('member_id');
        $query = $this->model->where('wellness_record_category', 'Examine')
            ->where('join_wellness_record_member_id', $memberId)
            ->orderBy('wellness_record_addtimes', 'desc');
        $paginator = $query->paginate(20);
        $total = $paginator->total();
        $items = $paginator->items();
        $itemsNew = [];
        foreach ($items as $item) {
            $itemNew = [
                'wellness_record_id' => $item->wellness_record_id,
                'join_wellness_record_member_id' => $item->join_wellness_record_member_id,
                'wellness_record_status' => $item->wellness_record_status,
                'wellness_record_name' => $item->wellness_record_name,
                'wellness_record_datetime' => $item->wellness_record_datetime,
                'wellness_record_json' => $item->wellness_record_json,
                'wellness_record_content' => $item->wellness_record_content,
                'wellness_record_remark' => $item->wellness_record_remark,
                'wellness_record_extend_json' => $item->wellness_record_extend_json,
                'wellness_record_addtimes' => $item->wellness_record_addtimes,
            ];
            if (!empty($item->wellness_record_file_json)) {
                $item->wellness_record_file_json = json_decode($item->wellness_record_file_json, true);
                if (isset($item->wellness_record_file_json['file_filename']) && isset($item->wellness_record_file_json['file_savepath'])) {
                    $itemNew['wellness_record_file_json'][] = [
                        'url' => getenv('APP_IMAGE_DOMAIN') . $item->wellness_record_file_json['file_savepath'] . $item->wellness_record_file_json['file_savename'],
                        'name' => $item->wellness_record_file_json['file_filename']
                    ];
                } else if (isset($item->wellness_record_file_json['url']) && isset($item->wellness_record_file_json['name'])) {
                    $itemNew['wellness_record_file_json'][] = [
                        'url' => getenv('STORAGE_DOMAIN') . $item->wellness_record_file_json['url'],
                        'name' => $item->wellness_record_file_json['name']
                    ];
                } else {
                    foreach ($item->wellness_record_file_json as $value) {
                        $itemNew['wellness_record_file_json'][] = [
                            'url' => isset($value['url']) ? getenv('STORAGE_DOMAIN') . $value['url'] : '',
                            'name' => isset($value['name']) ? $value['name'] : ''
                        ];
                    }
                }
            }

            $itemsNew[] = $itemNew;
        }

        $data = [
            'total' => $total,
            'rows' => $itemsNew
        ];
        return json(['code' => 200, 'msg' => 'success', 'data' => $data]);
    }

    public function visit($memberId)
    {
        $query = $this->model->where('wellness_record_category', 'Visiting')
            ->where('join_wellness_record_member_id', $memberId)
            ->orderBy('wellness_record_addtimes', 'desc');
        $paginator = $query->paginate(20);
        $total = $paginator->total();
        $items = $paginator->items();
        $itemsNew = [];
        foreach ($items as $item) {
            $itemNew = [
                'wellness_record_id' => $item->wellness_record_id,
                'join_wellness_record_member_id' => $item->join_wellness_record_member_id,
                'wellness_record_status' => $item->wellness_record_status,
                'wellness_record_name' => $item->wellness_record_name,
                'wellness_record_datetime' => $item->wellness_record_datetime,
                'wellness_record_json' => $item->wellness_record_json,
                'wellness_record_content' => $item->wellness_record_content,
                'wellness_record_remark' => $item->wellness_record_remark,
                'wellness_record_extend_json' => $item->wellness_record_extend_json,
                'wellness_record_addtimes' => $item->wellness_record_addtimes,
            ];
            if (!empty($item->wellness_record_file_json)) {
                $item->wellness_record_file_json = json_decode($item->wellness_record_file_json, true);
                foreach ($item->wellness_record_file_json as $value) {
                    $itemNew['wellness_record_file_json'][] = [
                        'url' => isset($value['url']) ? getenv('STORAGE_DOMAIN') . $value['url'] : '',
                        'name' => isset($value['name']) ? $value['name'] : ''
                    ];
                }
            }

            $itemsNew[] = $itemNew;
        }

        $data = [
            'total' => $total,
            'rows' => $itemsNew
        ];
        return json(['code' => 200, 'msg' => 'success', 'data' => $data]);
    }

    /**
     * @Desc 查询列表
     * @Author Gorden
     * @Date 2024/3/21 9:58
     *
     * @param Request $request
     * @return Response
     * @throws \support\exception\BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $field = $field ?? 'wellness_record_addtimes';
        $order = $request->get('order', 'desc');
        $where['wellness_record_category'] = 'Archives';
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    protected function doSelect(array $where, string $field = null, string $order = 'desc')
    {
        $model = $this->model->with([
            'member' => function ($query) {
                $query->select('member_id', 'member_mobile');
            },
            'cert' => function ($query) {
                $query->select('join_cert_member_id', 'member_cert_name');
            }
        ]);
        foreach ($where as $column => $value) {
            if (is_array($value)) {
                if ($value[0] === 'like' || $value[0] === 'not like') {
                    $model = $model->where($column, $value[0], "%$value[1]%");
                } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
                    $model = $model->where($column, $value[0], $value[1]);
                } elseif ($value[0] == 'in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereIn($column, $valArr);
                } elseif ($value[0] == 'not in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereNotIn($column, $valArr);
                } elseif ($value[0] == 'null') {
                    $model = $model->whereNull($column);
                } elseif ($value[0] == 'not null') {
                    $model = $model->whereNotNull($column);
                } elseif ($value[0] !== '' || $value[1] !== '') {
                    $model = $model->whereBetween($column, $value);
                }
            } else {
                $model = $model->where($column, $value);
            }
        }
        if ($field) {
            $model = $model->orderBy($field, $order);
        }
        return $model;
    }

    protected function afterQuery($items)
    {
        foreach ($items as &$item) {
            if (!empty($item->wellness_record_file_json)) {
                $item->wellness_record_file_json = json_decode($item->wellness_record_file_json, true);
                $wellnessRecordFileJson = [];
                if (isset($item->wellness_record_file_json['file_filename']) && isset($item->wellness_record_file_json['file_savepath'])) {
                    $wellnessRecordFileJson[] = [
                        'url' => getenv('STORAGE_DOMAIN') . $item->wellness_record_file_json['file_savepath'],
                        'name' => $item->wellness_record_file_json['file_filename']
                    ];
                } else if (isset($item->wellness_record_file_json['url']) && isset($item->wellness_record_file_json['name'])) {
                    $wellnessRecordFileJson[] = [
                        'url' => getenv('STORAGE_DOMAIN') . $item->wellness_record_file_json['url'],
                        'name' => $item->wellness_record_file_json['name']
                    ];
                } else {
                    foreach ($item->wellness_record_file_json as $value) {
                        if (!empty($value['url']) && !empty($value['name'])) {
                            $wellnessRecordFileJson[] = [
                                'url' => getenv('STORAGE_DOMAIN') . $value['url'],
                                'name' => $value['name']
                            ];
                        }
                    }
                }

                $item->wellness_record_file_json = $wellnessRecordFileJson;
            }
        }

        return $items;
    }

    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());
        if (empty($data['wellness_record_datetime'])) {
            $data['wellness_record_datetime'] = date('Y-m-d H:i:s');
        } else {
            $data['wellness_record_datetime'] = date('Y-m-d H:i:s', strtotime($data['wellness_record_datetime']));
        }

        if (!empty($data['wellness_record_file_json'])) {
            $data['wellness_record_file_json'] = json_decode($data['wellness_record_file_json'], true);
            $wellnessRecordFileJson = [];
            foreach ($data['wellness_record_file_json'] as $value) {
                $wellnessRecordFileJson[] = [
                    'url' => str_replace(getenv('STORAGE_DOMAIN'), '', $value['url']),
                    'name' => $value['name']
                ];
            }
            $data['wellness_record_file_json'] = json_encode($wellnessRecordFileJson);
        } else {
            $data['wellness_record_file_json'] = '[]';
        }

        $data['wellness_record_json'] = '[]';
        if (!empty($request->post('records'))) {
            $data['wellness_record_json'] = json_encode($request->post('records'));
        }

        // 记录医生
        $extend = JwtToken::getExtend();
        $data['wellness_record_extend_json'] = json_encode([
            'doctor' => [
                'name' => $extend['name'],
                'header' => '',
                'userid' => $extend['id']
            ]]);

        return $data;
    }

    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }
        $data = $this->inputFilter($request->post());
        if (empty($data['wellness_record_datetime'])) {
            $data['wellness_record_datetime'] = date('Y-m-d H:i:s');
        } else {
            $data['wellness_record_datetime'] = date('Y-m-d H:i:s', strtotime($data['wellness_record_datetime']));
        }
        if (!empty($data['wellness_record_file_json'])) {
            $data['wellness_record_file_json'] = json_decode($data['wellness_record_file_json'], true);
            $wellnessRecordFileJson = [];
            foreach ($data['wellness_record_file_json'] as $value) {
                $wellnessRecordFileJson[] = [
                    'url' => str_replace(getenv('STORAGE_DOMAIN'), '', $value['url']),
                    'name' => $value['name']
                ];
            }
            $data['wellness_record_file_json'] = json_encode($wellnessRecordFileJson);
        } else {
            $data['wellness_record_file_json'] = '[]';
        }
        $data['wellness_record_json'] = '[]';
        if (!empty($request->post('records'))) {
            $data['wellness_record_json'] = json_encode($request->post('records'));
        }
        unset($data[$primary_key]);
        return [$id, $data];
    }

    public function exportArchivePdf(Request $request)
    {
        $memberId = $request->get('member_id');

        $archive = WellnessRecord::where('join_wellness_record_member_id', $memberId)
            ->select('join_wellness_record_member_id', 'wellness_record_status', 'wellness_record_category', 'wellness_record_json', 'wellness_record_datetime')
            ->where('wellness_record_category', 'Archives')
            ->where('wellness_record_status', 'ACTIVED')
            ->first();
        if (empty($archive)) {
            return json_fail('档案不存在');
        }
        $archive = $archive->toArray();
        $wellnessRecordJson = json_decode($archive['wellness_record_json'], true);
        foreach ($wellnessRecordJson as &$recordItem) {
            if (is_array($recordItem)) {
                $recordItem = implode('，', $recordItem);
            }
        }


        $questions = Content::where('content_category', 'WELLNESSQUESTION')
            ->select('content_id', 'content_category', 'content_sort', 'content_config_json', 'content_title')
            ->orderBy('content_sort')
            ->get()
            ->toArray();
        foreach ($questions as &$question) {
            $contentConfig = json_decode($question['content_config_json'], true);
            foreach ($contentConfig as $item) {
                $fields = SysField::whereIn('field_id', $item['field'])
                    ->select('field_id', 'field_name', 'field_form_key', 'field_form_type', 'field_refer_json')
                    ->orderByDesc('field_sort')
                    ->get()
                    ->toArray();
                $fieldData = [];
                foreach ($fields as $field) {
                    $fieldData[] = [
                        'form_type' => $field['field_form_type'],
                        'field_name' => $field['field_name'],
                        'field_value' => $wellnessRecordJson[$field['field_form_key']] ?? ''
                    ];
                }
                $question['list'][] = [
                    'question' => $item['question'],
                    'fields' => $fieldData
                ];
            }
            unset($question['content_config_json']);
        }

        $content = view('member/word', ['questions' => $questions])->rawBody();

        $url = File::exportPdf($content, $memberId.'_'.date('YmdHis') . '.pdf');

        return json_success("success",['url'=>$url]);

//        $pdf->stream('my.pdf', ['Attachment' => 1]);
    }
}