<?php
/**
 * +----------------------------------------------------------------------
 * 用例-UI-编辑
 * +----------------------------------------------------------------------
 * 官网：https://www.sw-x.cn
 * +----------------------------------------------------------------------
 * 作者：小黄牛 <1731223728@qq.com>
 * +----------------------------------------------------------------------
 * 开源协议：http://www.apache.org/licenses/LICENSE-2.0
 * +----------------------------------------------------------------------
*/

namespace app\controller\admin\test;
use app\controller\SuperClass\Admin;

class Ui_update extends Admin
{

    /**
     * @AopBefore(class="app\aop\AdminLogin", function="before")
     * @RequestMapping(route="/admin/test/ui_update", method="GET|POST", title="用例-UI-编辑")
    */
    public function run() {
        if (\x\Request::is_ajax()) {
            return $this->_update();
        }
        return $this->display();
    }

    // 主表处理
    private function _update_table($param) {
        $Db = new \x\Db();
        $id = $Db->name('test_ui')->where('id', $param['id'])->update([
            'test_title' => $param['test_title'],
        ]);
        if (!$id) {
            $Db->return();
            return $this->returnJson('01', '修改失败，数据库写入异常');
        }
        
        $Db->return();
        return $this->returnJson('00', '修改成功！');
    }

    // Ajax处理
    private function _update() {
        $param = \x\Request::post();
        if (!empty($param['model'])) {
            return $this->_update_table($param);
        }

        $Db = new \x\Db();

        if (!empty($param['user'])) {
            $id = 0;
            foreach ($param['user'] as $v) {
                if (!empty($v['id'])) {
                    $id .= ','.$v['id'];
                }
            }
            // 删除
            if ($id) {
                $Db->name('test_ui_data')->where('pid', $param['ui_id'])->whereNotIn('id', '('.$id.')')->delete();
            }

            foreach ($param['user'] as $v) {
                $data = [
                    'pid' => $param['ui_id'],
                    'ui_title' => $v['ui_title'],
                    'level_id' => $v['level_id'],
                    'front_ask' => $v['front_ask'],
                    'action' => $v['action'],
                    'expect' => $v['expect'],
                    'test_result' => $v['test_result'],
                    'env_result' => $v['env_result'],
                    'remark' => $v['remark'],
                    'bug' => $v['bug'],
                ];
                if (!empty($v['id'])) {
                    $Db->name('test_ui_data')->where('id', $v['id'])->update($data);
                } else {
                    $Db->name('test_ui_data')->insert($data);
                }
                
            }
        } else {
            $Db->name('test_ui_data')->where('pid', $param['ui_id'])->delete();
        }
        $Db->return();

        return $this->returnJson('00', '编辑成功！');
    }

}

