<?php
/**
 *
 * @author：llbjj
 * @DateTime：2024/4/8 16:28
 * @Description：
 *
 */

namespace Application\Controller;

use Application\Common\StatusCode;
use Application\Mvc\Controller\BasicController;
use Application\Mvc\Controller\ThirdToolController;
use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\DateHelper;
use Laminas\Cache\Exception\ExceptionInterface;
use Laminas\Stdlib\ArrayUtils;
use Laminas\View\Model\JsonModel;

class SasController extends BasicController
{
    /**
     * @throws ExceptionInterface
     */
    public function exportAction() : JsonModel
    {
        $exportResult = $this->LocalService()->toolSys->exportSas($this->params()->fromPost());

        $extendData = [];
        if (!$exportResult['isValid']) {
            // 获取错误提示信息的表格结构
            $extendData = [
                'FormFileData' => $this->Introduce('ExportSasErr', ['item_id' => $this->params()->fromPost('item_id')])
            ];
        }
        return $this->RenderApiJson()->Success($exportResult, '', $extendData);
    }

    public function editAction(): JsonModel
    {
        $id = $this->params()->fromPost('id', 0);
        $item_id = $this->params()->fromPost('item_id', 0);
        $category = $this->params()->fromPost('category', 0);
        if(empty($item_id)) throw new InvalidArgumentException('请选择项目！');

        $where = ['item_id' => $item_id, 'category' => $category, 'is_del' => 0, 'id' => $id];

        $exportSas = $this->LocalService()->exportSas->fetchOne([
            'where' => $where,
            'columns' => ['item_id', 'itemsig_id', 'export_form_id', 'mode', 'path', 'category', 'status', 'type', 'create_user_id', 'create_time', 'update_user_id', 'update_time', 'date_ym', 'export_create_user_id']
        ]);

        if(empty($exportSas)) {
            $exportSas = [ 'mode' => '0', 'item_id' => $item_id, 'type' => '0', 'category' => $category, 'itemsig_id' => '', 'date_ym' => $date_ym, 'export_form_id' => 'null' ];
        }else {
            $exportSas['applyUserName/dateTime'] = $this->LocalService()->adminUser->getOneFieldVal('realname', ['id' => $exportSas['update_user_id'] ?: $exportSas['create_user_id']]) . '/' . date('Y-m-d H:i:s', $exportSas['update_time'] ?: $exportSas['create_time']);
            $exportSas['itemsig_id'] = !empty($exportSas['itemsig_id']) ? explode(',', $exportSas['itemsig_id']) : [];
            $exportSas['export_form_id'] = !empty($exportSas['export_form_id']) ? explode(',', $exportSas['export_form_id']) : [];
            unset($exportSas['create_user_id']);
            unset($exportSas['create_time']);
            unset($exportSas['update_user_id']);
            unset($exportSas['update_time']);
        }

        $FormFileData = $this->Introduce('ExportSas', ['item_id' => $item_id, 'category' => $category]);

        return $this->RenderApiJson()->Success($exportSas, '', [
            'FormFileData' => array_values($FormFileData)
        ]);
    }

    public function listAction(): JsonModel
    {
        $item_id = $this->params()->fromPost('item_id', 0);
        $category = $this->params()->fromPost('category', 0);
        if(empty($item_id)) throw new InvalidArgumentException('请选择项目！');

        $limit = $this->params()->fromPost('limit', 10);
        $page = $this->params()->fromPost('page', 1);

        $formFileData = $this->Introduce('ExportSas', ['item_id' => $item_id, 'category' => $category]);

        $listWhere = [
            'category' => $category,
            'item_id' => $item_id,
            'is_del' => 0,
        ];

        $exportSasList = $this->LocalService()->exportSas->fetchAll([
            'where' => $listWhere,
            'limit' => $limit,
            'offset' => ($page - 1) * $limit,
            'order' => 'update_time desc'
        ]);

        $formFieldOptions = [];
        array_walk($formFileData, function ($item, $key) use (&$formFieldOptions) {
           if ( in_array ( $item['type'], [ 'Radio', 'SelectUser' ])) {
               $optionsKey = $item['type'] == 'Radio' ? 'radios' : 'options';
               $formFieldOptions[$key] = ArrayHelper::index($item[$optionsKey], 'value');
           }
        });

        $adminUserNameList = $this->LocalService()->adminUser->fetchCol('realname', 'id > 0');

        $result = [];
        array_walk($exportSasList, function (&$item, $index) use($adminUserNameList, $formFileData, &$result, $formFieldOptions) {
            if($item['update_time'] != 0) {
                $oprtUserAndTime = sprintf('%s / %s', $adminUserNameList[$item['update_user_id']], DateHelper::formatTimestamp($item['update_time']));
            }else {
                $oprtUserAndTime = sprintf('%s / %s', $adminUserNameList[$item['create_user_id']], DateHelper::formatTimestamp($item['create_time']));
            }

            $result[$index] = array_fill_keys(array_keys($formFileData), '') ;

            foreach($result[$index] as $k => &$v) {
                $v = $item[$k] == 'null' ? '' : $item[$k];
                if(isset($formFieldOptions[$k])) {
                    if($v !== '') {
                        $v = implode(',', array_column(
                            array_intersect_key($formFieldOptions[$k], array_flip(explode(',', $v))),
                            'label'
                            )
                        );
                    }else {
                        $v = '全部';
                    }
                }

                if($k == 'date_ym' && !$v) {
                    $v = '全量';
                }
            }

            $result[$index] = ArrayUtils::merge($result[$index], [
                'id' => $item['id'],
                'path' => $item['path'],
                'status' => $item['status'],
                'applyUserName/dateTime' => $oprtUserAndTime
            ]);
        });



        return $this->RenderApiJson()->Success(
            $result,
            '',
            [
                'FormFileData' => array_values($formFileData),
                'total' => $this->LocalService()->exportSas->getCount($listWhere)
            ]
        );
    }


    /**
     * Notes:删除导出受试者进度信息
     * @param
     * @return
     * @author haojinhua
     * @date 2025-08-29
     */
    public function deleteAction(){
        $id = $this->params()->fromPost('id',0);//信息ID
        if (empty($id)) return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '参数不正确');
        $exportData = $this->LocalService()->exportSas->fetchOne([
            'where' => [
                'id' => $id,
                'is_del' => 0
            ],
            'columns' => ['id', 'category']
        ]);

        if (empty($exportData)) return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '信息不存在！');

        $save_data = [
            'id'=>$id,
            'is_del'=>1
        ];
        $result = $this->LocalService()->exportSas->save($save_data);
        if($result){
            //日志
            $log_type = 2;
            $log_remark = sprintf("(新版) %s - 删除申请导出信息", $this->LocalService()->exportSas->getCategoryText((int) $exportData['category']));;
            $this->LocalService()->log->saveFileLog($id,'ExportSas',$save_data,$log_type,$log_remark,'',' ',[]);
        }
        return $this->RenderApiJson()->success();
    }
}
