<?php

namespace app\admin\controller\Product;

use app\BaseController;
use app\common\model\Product\ProductType as ModelProductType;
use app\common\arw\adjfut\src\Traverse;
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\UploadFile;
use app\common\exception\Tool;
use think\facade\Db;
use think\facade\Env;


class ProductType extends BaseController
{
    /**
     * 获取产品系列树形列表接口
     *
     * @param Request request
     * @date 2023-03-25
     * @example
     * @author xjh
     * @since 1.0.0
     */
    public function getProductTypeTree(Request $request): array
    {
        $con = Tool::getOptionalQuery(
            ['b.product_delete_time', 'NULL'],
            ['a.product_type_name', 'LIKE']
        );

        $product_type = ModelProductType::field([
            'a.product_type_parent_guid',
            'a.product_type_name',
            'b.product_type_name' => "product_type_parent_name",
            'a.product_type_order',
            'a.product_type_guid',
            'a.product_type_icon',
            'a.product_type_cover',
        ])
            ->alias('a')
            ->leftjoin('product_type b', 'a.product_type_parent_guid = b.product_type_guid')
            ->where($con)
            ->order(['product_type_order' => 'asc'])
            ->select()->toArray();

        $Traverse = new Traverse('product_type_guid', 'product_type_parent_guid');
        $product_type_tree = $Traverse->tree($product_type, '0', function ($v) {
            return [
                'product_type_name' => $v['product_type_name'],
                'product_type_parent_name' => $v['product_type_parent_name'],
                'product_type_guid' => $v['product_type_guid'],
                'product_type_parent_guid' => $v['product_type_parent_guid'],
                'product_type_order' => $v['product_type_order'],
                'product_type_icon' => $v['product_type_icon'],
                'product_type_cover' => $v['product_type_cover'],
            ];
        });

        return msg("获取产品系列列表成功!", $product_type_tree);
    }

    /**
     * 编辑产品系列接口
     *
     * @param Request request
     * @date 2023-03-25
     * @example
     * @author xjh
     * @since 1.0.0
     */
    public function editProductType(Request $request): array
    {
        Db::startTrans();
        try {
            $params = $request->param();
            $this->validate($params, [
                'product_type_name|产品系列名称' => 'require',
                'product_type_icon|产品系列图标' => 'require',
                'product_type_cover|产品系列封面' => 'require',
                'product_type_guid|产品系列guid' => 'require',
                'product_type_order|产品系列排序' => 'require',
            ]);

            $model = ModelProductType::where('product_type_guid', $params['product_type_guid'])->find();
            if (!$model) throwErrorMsg("该产品系列不存在", 1);

            ModelProductType::isDuplicateName($params['product_type_name'], $params['product_type_guid']);

            $params['product_type_ancestors_guid'] = ModelProductType::buildAncestorsGuid($params['product_type_parent_guid']);

            Tool::sortEditProc(
                new ModelProductType,
                ["product_type_order" => $params['product_type_order']],
                ["product_type_guid" => $params['product_type_guid']],
                ["product_type_parent_guid" => $params['product_type_parent_guid']],
            );


            $model->allowField([
                'product_type_update_user_guid',
                'product_type_title',
                'product_type_icon',
                'product_type_cover',
                'product_type_ancestors_guid',
                'product_type_parent_guid',
                'product_type_order',
            ])->save($params);
            Db::commit();
            return msg('编辑成功!');
        } catch (\Throwable $th) {
            Db::rollback();
            throw  $th;
        }
    }


    /**
     * 添加产品系列接口
     *
     * @param Request request
     * @date 2023-03-25
     * @example
     * @author xjh
     * @since 1.0.0
     */
    public function addProductType(Request $request): array
    {
        Db::startTrans();
        try {
            $params = $request->param();
            $this->validate($params, [
                'product_type_name|产品类型名称' => 'require',
                'product_type_icon|产品系列图标' => 'require',
                'product_type_cover|产品系列封面' => 'require',
                'product_type_order|产品系列排序' => 'require'
            ]);

            ModelProductType::isDuplicateName($params['product_type_name']);


            $product_type_parent_where = [];
            if (!empty($params['product_type_parent_guid'])) {
                $params['product_type_ancestors_guid'] = ModelProductType::buildAncestorsGuid($params['product_type_parent_guid']);
                $product_type_parent_where['product_type_parent_guid'] = $params['product_type_parent_guid'];
            }

            Tool::sortInsertProc(
                new ModelProductType,
                ["product_type_order" => $params['product_type_order']],
                $product_type_parent_where,
            );

            ModelProductType::create($params, [
                'product_type_guid',
                'product_type_create_user_guid',
                'product_type_update_user_guid',
                'product_type_parent_guid',
                'product_type_ancestors_guid',
                'product_type_name',
                'product_type_icon',
                'product_type_cover',
                'product_type_order'
            ]);
            Db::commit();
            return msg("添加成功!");
        } catch (\Throwable $th) {
            Db::rollback();
            throw  $th;
        }
    }

    /**
     * 删除产品系列接口接口
     *
     * @param Request request
     * @date 2023-03-25
     * @example
     * @author xjh
     * @since 1.0.0
     */
    public function deleteProductType(Request $request): array
    {
        Db::startTrans();
        try {
            $params = $request->param();
            $this->validate($params, [
                'product_type_guid|产品系列guid' => 'require',
            ]);
            $guids =  explode(',', $params['product_type_guid']);

            Tool::sortDeleteProc(
                new ModelProductType,
                'product_type_order',
                ["product_type_guid" => $guids],
                ["product_type_parent_guid"],
            );
            ModelProductType::where(['product_type_guid' => $guids])->select()->delete();
            Db::commit();
            return msg('删除成功!');
        } catch (\Throwable $th) {
            Db::rollback();
            throw  $th;
        }
    }

    /**
     * 导出Excel接口
     *
     * @param Request request
     * @date 2023-03-25
     * @example
     * @author xjh
     * @since 1.0.0
     */
    public function exportExcel(Request $request)
    {
        $params = $request->param();
        $select = ModelProductType::field([
            'product_type_title',
            'product_type_icon',
            'product_type_cover'
        ])
            ->order('product_type_update_time', 'desc')
            ->select();
        return ModelProductType::exportExcel($select);
    }

    /**
     * 下载导入模板接口
     *
     * @param Request request
     * @date 2023-03-25
     * @example
     * @author xjh
     * @since 1.0.0
     */
    public function downloadTemplate(Request $request)
    {
        $params = $request->param();
        $data = array_values(ModelProductType::EXCELFIELD);
        $excel = (new Excel())->exporTsheet($data);
        $excel->save('产品系列导入模板.xlsx');
    }

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

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