<?php

namespace app\admin\controller\Works;

use app\BaseController;
use app\common\model\Works\WorksType as ModelWorksType;
use app\Request;
use think\Validate;
use think\exception\ValidateException;
use think\facade\Filesystem;
use app\common\arw\adjfut\src\Excel;
use app\common\arw\adjfut\src\Traverse;
use app\common\arw\adjfut\src\UploadFile;
use app\common\exception\Tool;
use think\facade\Db;
use think\facade\Env;


class WorksType extends BaseController
{
    /**
     * 获取作品类型列表接口
     *
     * @param Request request
     * @return array
     * @date 2023-04-17
     * @author xjh
     * @since 1.0.0
     */
    public function getWorksTypeList(Request $request): array
    {
        $con = Tool::getOptionalQuery(['works_type_name', 'LIKE']);
        $con[] = ['works_type_parent_guid', '=', "0"];
        $works_type_guids  = self::pageWrapper(ModelWorksType::where($con))
            ->order('works_type_order')
            ->column('works_type_guid');

        $works_type_tree = [];
        if ($works_type_guids) {
            $works_type  = ModelWorksType::whereOr([
                [["a.works_type_guid", 'in', $works_type_guids]],
                [["a.works_type_ancestors_guid", 'REGEXP', implode('|', $works_type_guids)]],
            ])
                ->where([['b.works_type_delete_time', 'NULL', null]])
                ->field([
                    'a.works_type_id',
                    'a.works_type_guid',
                    'a.works_type_name',
                    'a.works_type_order',
                    'a.works_type_parent_guid',
                    'a.works_type_ancestors_guid',
                    'b.works_type_name' => "works_type_parent_name",
                ])->alias('a')
                ->leftjoin('works_type b', 'a.works_type_parent_guid = b.works_type_guid')
                ->order('works_type_order')
                ->select()
                ->toArray();

            $Traverse = new Traverse('works_type_guid', 'works_type_parent_guid');
            $works_type_tree = $Traverse->tree($works_type, '0', function ($v) {
                return [
                    'works_type_name' => $v['works_type_name'],
                    'works_type_parent_name' => $v['works_type_parent_name'],
                    'works_type_guid' => $v['works_type_guid'],
                    'works_type_parent_guid' => $v['works_type_parent_guid'],
                    'works_type_ancestors_guid' => $v['works_type_ancestors_guid'],
                    'works_type_order' => $v['works_type_order'],
                ];
            });
        }
        return msg(0, "获取作品类型列表成功!", [
            'data' => $works_type_tree,
            'count' => ModelWorksType::where('works_type_parent_guid', '0')->count()
        ]);
    }

    /**
     * 编辑作品类型接口
     *
     * @param Request request
     * @return array
     * @date 2023-04-17
     * @author xjh
     * @since 1.0.0
     */
    public function editWorksType(Request $request): array
    {
        Db::startTrans();
        try {
            $params = $request->param();
            $this->validate($params, [
                'works_type_name|作品类型名称' => 'require',
                'works_type_guid|作品类型guid' => 'require',
                'works_type_order|作品类型排序' => 'require',
                'works_type_parent_guid|作品类型父级guid' => 'require',
                'works_type_ancestors_guid|作品类型祖级guid' => 'require'
            ]);

            $works_type = ModelWorksType::where('works_type_guid', $params['works_type_guid'])->find();
            if (!$works_type) throwErrorMsg("该作品类型不存在", 1);
            $works_type->allowField([
                'works_type_update_user_guid',
                'works_type_name',
                'works_type_order',
                'works_type_parent_guid',
                'works_type_ancestors_guid',
            ])->save($params);
            Db::commit();
            return msg('编辑成功!');
        } catch (\Throwable $th) {
            Db::rollback();
            throw  $th;
        }
    }

    /**
     * 添加作品类型接口
     *
     * @param Request request
     * @return array
     * @date 2023-04-17
     * @author xjh
     * @since 1.0.0
     */
    public function addWorksType(Request $request)
    {
        Db::startTrans();
        try {
            $params = $request->param();
            $this->validate($params, [
                'works_type_name|作品类型名称' => 'require',
                'works_type_order|作品类型排序' => 'require',
                'works_type_parent_guid|作品类型父级guid' => 'require',
            ]);

            ModelWorksType::create($params, [
                'works_type_guid',
                'works_type_create_user_guid',
                'works_type_update_user_guid',
                'works_type_name',
                'works_type_order',
                'works_type_ancestors_guid',
                'works_type_parent_guid'
            ]);
            Db::commit();
            return msg('添加成功!');
        } catch (\Throwable $th) {
            Db::rollback();
            throw  $th;
        }
    }

    /**
     * 删除作品类型接口
     *
     * @param Request request
     * @return array
     * @date 2023-04-17
     * @author xjh
     * @since 1.0.0
     */
    public function deleteWorksType(Request $request): array
    {
        Db::startTrans();
        try {
            $params = $request->param();
            $this->validate($params, [
                'works_type_guid' => 'require',
            ]);
            $works_type = ModelWorksType::where([
                'works_type_guid' => explode(',', $params['works_type_guid'])
            ])->select();
            $works_type->delete();
            Db::commit();
            return msg('删除成功!');
        } catch (\Throwable $th) {
            Db::rollback();
            throw  $th;
        }
    }

    /**
     * 导出Excel接口
     *
     * @param Request request
     * @return array
     * @date 2023-04-17
     * @author xjh
     * @since 1.0.0
     */
    public function exportExcel(Request $request): void
    {
        $params = $request->param();
        $con = [];
        if (isset($params['works_type_guids']) && $params['works_type_guids']) {
            $con['a.works_type_guid'] = explode(',', $params['works_type_guids']);
        }
        $select = ModelWorksType::field([
            'a.works_type_name',
            'a.works_type_order',
            // 'a.works_type_parent_guid',
            // 'b.works_type_name' => 'works_type_parent_name',
        ])
            ->where($con)
            ->alias('a')
            // ->leftjoin('works_type b', 'a.works_type_parent_guid = b.works_type_guid')
            ->order('works_type_order', 'desc')
            ->select()
            ->toArray();

        ModelWorksType::exportExcel($select);
    }

    /**
     * 下载导入模板接口
     *
     * @param Request request
     * @return array
     * @date 2023-04-17
     * @author xjh
     * @since 1.0.0
     */
    public function downloadTemplate(Request $request): void
    {
        $data = [
            array_values(ModelWorksType::IMPORT_EXCEL_FIELD),
            // ['', '素描', '1']
            ['素描', '1']
        ];
        $excel = (new Excel())->exporTsheet($data);
        $excel->save('作品类型导入模板.xlsx');
    }

    /**
     * 导入excel接口
     *
     * @param Request request
     * @return array
     * @date 2023-04-17
     * @author xjh
     * @since 1.0.0
     */
    public function importExcel(Request $request): array
    {
        $file = new UploadFile('uploads', 'fileExt:xlsx');
        $file->putFile('works_type');

        $msg = ModelWorksType::importExcel($file);
        return [
            'code' => 0,
            'msg' => $msg
        ];
    }
}
