<?php
/**
 * 用户账户管理
 */

namespace app\Admin\controller;

use think\Db;

class Account extends Base
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @param status
     * @param username
     * @param mobile
     * @param nickname
     * @param page
     * @param size
     */
    public function List()
    {
        $page = isset($this->post['page']) && $this->post['page'] != "" ? intval($this->post['page']) : 1;
        $size = isset($this->post['size']) && $this->post['size'] != "" ? intval($this->post['size']) : 10;
        $status = isset($this->post['status']) && $this->post['status'] !== "" ? intval($this->post['status']) : "";
        $where = ['a.is_del'=>0];
        if ($status !== "") {
            $where['a.status'] = $status;
        }
        $username = isset($this->post['username']) && $this->post['username'] !== "" ? trim($this->post['username']) : "";
        if ($username != "") {
            $where['username'] = ["like", "%{$username}%"];
        }
        $nickname = isset($this->post['nickname']) && $this->post['nickname'] !== "" ? trim($this->post['nickname']) : "";
        if ($nickname != "") {
            $where['nickname'] = ["like" => "%{$nickname}%"];
        }
        $mobile = isset($this->post['mobile']) && $this->post['mobile'] !== "" ? trim($this->post['mobile']) : "";
        if ($mobile != "") {
            $where['c.mobile'] = ["like" => "%{$mobile}%"];
        }
        $count = Db::name("account")->alias('a')
            ->join("fc_rela_account b", "a.id = b.accountid", "left")
            ->join("fc_account_info c", "b.account_info= c.id", "left")
            ->where($where)->count();
        $total = ceil($count / $size);
        $page = $page >= $total ? $total : $page;

        $list = Db::name("account")->alias('a')->where($where)->page($page, $size)
            ->join("fc_rela_account b", "a.id = b.accountid", "left")
            ->join("fc_account_info c", "b.account_info= c.id", "left")
            ->field("`a`.`id` AS `id`,
	                      `a`.`username` AS `username`,
	                      `a`.`password` AS `password`,
	                      `a`.`salt` AS `salt`,
	                      `a`.`status` AS `status`,
                          `a`.`is_del` AS `is_del`,
                          `a`.`type` AS `type`,
                          `a`.`starttime` AS `starttime`,
                          `a`.`expiretime` AS `expiretime`,
                          `a`.`activetime` AS `activetime`,
                          `a`.`addtime` AS `addtime`,
                           `c`.`nickname` AS `nickname`,
                           `c`.`avatar` AS `avatar`,
                           `c`.`mobile` AS `mobile`,
                           `c`.`remark` AS `remark`,
                           `c`.`sex` AS `sex`")
            ->order("a.id desc")->select();
        $i = [];
        foreach ($list as $vus) {
            $vi = Db::name('rela_video')->join('fc_video a', 'a.id=fc_rela_video.video_id', 'left')->field('a.video_sn,a.video_name,a.video_url,a.video_img')->where(['accountid' => $vus['id'], 'a.is_del' => 0,])->select();
            if (empty($vi)) {
                $vi = [];
            }
            $vus['info'] = $vi;
            $i[] = $vus;
        }
        return app_show(0, "获取成功", ["list" => $i, "count" => $count]);
    }

    /**
     * @param username
     * @param password
     * @param starttime
     * @param expiretime
     * @param nickname
     * @param remark
     * @param video
     */
    public function Create()
    {
        $username = isset($this->post['username']) && $this->post['username'] !== "" ? trim($this->post['username']) : "";
        if ($username == "") {
            return error_show(1004, "参数username 不能为空");
        }
        if (!checkAccount($username)) {
            return error_show(1004, "账户格式不正确");
        }
        $isT = Db::name("account")->where(["is_del" => 0, "username" => $username])->find();
        if ($isT) {
            return error_show(1004, "账户名已存在");
        }
        $pasword = isset($this->post['password']) && $this->post['password'] !== "" ? trim($this->post['password']) : "";
        if ($pasword == "") {
            return error_show(1004, "参数password 不能为空");
        }
        if (!checkPasswd($pasword)) {
            return error_show(1004, "密码格式不正确");
        }
        $starttime = isset($this->post['starttime']) && $this->post['starttime'] !== "" ? $this->post['starttime'] : "";
        if ($starttime == "") {
            return error_show(1004, "参数starttime 不能为空");
        }
        $expiretime = isset($this->post['expiretime']) && $this->post['expiretime'] !== "" ? $this->post['expiretime'] : "";
        if ($expiretime == "") {
            return error_show(1004, "参数expiretime 不能为空");
        }
        $nickname = isset($this->post['nickname']) && $this->post['nickname'] !== "" ? trim($this->post['nickname']) : "";
//        if($nickname==""){
//            return error_show(1004,"参数nickname 不能为空");
//        }
        $mobile = isset($this->post['mobile']) && $this->post['mobile'] !== "" ? trim($this->post['mobile']) : "";
//        if($mobile==""){
//            return error_show(1004,"参数mobile 不能为空");
//        }
        $remark = isset($this->post['remark']) && $this->post['remark'] !== "" ? trim($this->post['remark']) : "";
        $video = isset($this->post['video']) && $this->post['video'] !== "" ? $this->post['video'] : "";
        if ($video == "") {
            return error_show(1004, "参数video 不能为空");
        }
        Db::startTrans();
        try {
            $salt = makeSalt();
            $pas = sha1($pasword . $salt);
            $data = [
                "username" => $username,
                "password" => $pas,
                "pwd" => $pasword,
                "salt" => $salt,
                "status" => 0,
                "is_del" => 0,
                "starttime" => $starttime,
                "expiretime" => $expiretime,
                "addtime" => date("Y-m-d H:i:s"),
                "updatetime" => date("Y-m-d H:i:s")
            ];
            $acccount = Db::name("account")->insert($data, false, true);
            if ($acccount > 0) {
                $user = [
                    "nickname" => $nickname,
                    "mobile" => $mobile,
                    "avatar" => "",
                    "remark" => $remark,
                    "sex" => "",
                    "addtime" => date("Y-m-d H:i:s"),
                    "updatetime" => date("Y-m-d H:i:s")
                ];
                $info = Db::name("account_info")->insert($user, false, true);
                if ($info > 0) {
                    $rela = ["accountid" => $acccount, "account_info" => $info];
                    $rela_acc = Db::name("rela_account")->insert($rela);

                    // $rele = [["video_id"=>$video,"accountid"=>$video,"addtime"=>$video]];
                    $l = [];
                    foreach ($video as $value) {

                        $temp = ["video_id" => $value, "accountid" => $acccount, "addtime" => date("Y-m-d H:i:s")];
                        $l[] = $temp;
                    }

                    $rele_a = Db::name("rela_video")->insertAll($l);
                    if ($rele_a == false) {
                        Db::rollback();
                        return error_show(1002, "绑定失败");
                    } else {
                        write_log("视频绑定成功", $this->userinfo, "account", "add");
                    }
                    if ($rela_acc) {
                        write_log("账户{$username}新建成功", $this->userinfo, "account", "add");
                        Db::commit();
                        return app_show(0, "账户新建成功");
                    }

                }
            }
            Db::rollback();
            return error_show(1005, "账户新建失败");
        } catch (\Exception $e) {
            Db::rollback();
            return error_show(1003, $e->getMessage());
        }
    }

    /**@param id 账户id
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function Read()
    {
        $id = isset($this->post['id']) && $this->post["id"] != "" ? intval($this->post['id']) : "";
        if ($id == "") {
            return error_show(1004, "参数id 不能为空");
        }
        $info = Db::name("account")->alias('a')->where(["a.id" => $id,'a.is_del'=>0])
            ->join("fc_rela_account b", "a.id = b.accountid", "left")
            ->join("fc_account_info c", "b.account_info= c.id", "left")
            ->field("`a`.`id` AS `id`,
	                      `a`.`username` AS `username`,
	                      `a`.`password` AS `password`,
	                      `a`.`salt` AS `salt`,
	                      `a`.`status` AS `status`,
                          `a`.`is_del` AS `is_del`,
                          `a`.`type` AS `type`,
                          `a`.`starttime` AS `starttime`,
                          `a`.`expiretime` AS `expiretime`,
                          `a`.`activetime` AS `activetime`,
                          `a`.`addtime` AS `addtime`,
                           `c`.`nickname` AS `nickname`,
                           `c`.`avatar` AS `avatar`,
                           `c`.`mobile` AS `mobile`,
                           `c`.`remark` AS `remark`,
                           `c`.`sex` AS `sex`")
            ->find();
        if (empty($info)) {
            return error_show(1005, "未找到数据");
        }
        if ($info["is_del"] == 1) {
            return error_show(1005, "账户已被删除");
        }
        $info['status_n'] = $info['status'] == 0 ? "未激活" : $info['status'] == 1 ? "已激活" : "已失效";

        $vi = Db::name('rela_video')->join('fc_video a', 'a.id=fc_rela_video.video_id', 'left')
            ->field('a.video_sn,a.video_name,a.video_url,a.video_img,fc_rela_video.video_id,a.status')
            ->where(['accountid' => $id, 'a.is_del' => 0, 'fc_rela_video.is_del' => 0])->select();
        //var_dump(Db::name('rela_video')->getLastSql());
        $info['info'] = $vi;
        return app_show(0, "获取成功", $info);

    }

    /**
     * @param id
     * @param username
     * @param password
     * @param starttime
     * @param expiretime
     * @param nickname
     * @param remark
     * @param video
     */
    public function Save()
    {
        $id = isset($this->post['id']) && $this->post['id'] != "" ? intval($this->post['id']) : "";
        if ($id == "") {
            return error_show(1004, "参数id 不能为空");
        }
        $info = Db::name("account")->where(["is_del" => 0, "id" => $id])->find();
        if (empty($info)) {
            return error_show(1004, "未找到数据");
        }
        $username = isset($this->post['username']) && $this->post['username'] !== "" ? trim($this->post['username']) : "";
        if ($username != "") {
            $isT = Db::name("account")->where(["is_del" => 0, "username" => $username, "id" => ["<>", $id]])->find();
            if ($isT) {
                return error_show(1004, "账户名已存在");
            }
            $info['username'] = $username;
        }
//
//       $pasword = isset($this->post['password']) && $this->post['password'] !== "" ? trim($this->post['password']) : "";
//        if ($pasword != "" && $info['password'] != sha1($pasword.$info['salt'])) {
//            $salt = makeSalt();
//            $info['password'] = sha1($pasword . $salt);
//            $info['pwd'] = $pasword;
//        }
        $starttime = isset($this->post['starttime']) && $this->post['starttime'] !== "" ? $this->post['starttime'] : "";
        if ($starttime != "") {
            $info['starttime'] = $starttime;
        }
        $expiretime = isset($this->post['expiretime']) && $this->post['expiretime'] !== "" ? $this->post['expiretime'] : "";
        if ($expiretime != "") {
            $expire = strtotime($expiretime);
            if ($expire > time()) {
                $info['status'] = $info['activetime'] == "" ? 0 : 1;
            } else {
                $info['status'] = 2;
            }
            $info['expiretime'] = $expiretime;
        }
        $info['updatetime'] = date("Y-m-d H:i:s");
        $rela = Db::name("account_info")->alias("a")->Join("fc_rela_account b", "b.account_info=a.id", "left")->where(["b.accountid" => $id])->field("a.*")->find();
        $nickname = isset($this->post['nickname']) && $this->post['nickname'] !== "" ? trim($this->post['nickname']) : "";
        $rela['nickname'] = $nickname;
        $mobile = isset($this->post['mobile']) && $this->post['mobile'] !== "" ? trim($this->post['mobile']) : "";
        if ($mobile != "") {
            $rela['mobile'] = $mobile;
        }

        $rela['remark'] = isset($this->post['remark']) && $this->post['remark'] !== "" ? trim($this->post['remark']) : "";
        $video = isset($this->post['video']) && $this->post['video'] !== "" ? $this->post['video'] : "";
        if ($video == "") {
            return error_show(1004, "参数video 不能为空");
        }
        $rela['updatetime'] = date("Y-m-d H:i:s");

        Db::startTrans();
        try {
            $acccount = Db::name("account")->update($info);
            if ($acccount) {
                $infoacc = Db::name("account_info")->update($rela);
                $del = Db::name('rela_video')->where(["is_del" => 0, "accountid" => $id])->select();
                if ($del == true) {
                    $dl = Db::name('rela_video')->where(["is_del" => 0, "accountid" => $id])->update(["addtime" => date("Y-m-d H:i:s"), "is_del" => 1]);
                }
                $k = [];
                $vb = Db::name('video')->where(['status' => 0, 'id' => ["in", $video]])->select();
                if (!empty($vb)) {
                    return error_show(1004, "存在已禁用的视频");
                }
                foreach ($video as $valu) {
                    $temp = ["video_id" => $valu, "accountid" => $id, "addtime" => date("Y-m-d H:i:s")];
                    $k[] = $temp;
                }
                $rele_a = Db::name("rela_video")->insertAll($k);
                if ($rele_a == false) {
                    Db::rollback();
                    return error_show(1002, "绑定失败");
                } else {
                    write_log("视频绑定成功", $this->userinfo, "account", "edit");
                }

                if ($infoacc) {
                    write_log("账户{$username}新建成功", $this->userinfo, "account", "edit");
                    Db::commit();
                    return app_show(0, "账户编辑成功");
                } else {
                    Db::rollback();
                    return error_show(1005, "账户编辑失败");
                }
            }
            Db::rollback();
            return error_show(1005, "账户编辑失败");
        } catch (\Exception $e) {
            Db::rollback();
            return error_show(1003, $e->getMessage());
        }
    }
    public  function  checkPwd(){
       $id=  isset($this->post['id']) && $this->post['id'] !== "" ? intval($this->post['id']) : "";
       if($id===''){
           return error_show(1004, "参数id 不能为空");
       }
        $info = Db::name("account")->where(["is_del" => 0, "id" => $id])->find();
        if (empty($info)) {
            return error_show(1004, "未找到数据");
        }
       $pasword = isset($this->post['password']) && $this->post['password'] !== "" ? trim($this->post['password']) : "";
        if($pasword===''){
            return error_show(1004, "参数password 不能为空");
        }
        if ($info['pwd']==$pasword) {
            return error_show(1004, "新密码不能与原密码相同");
        }
//        if (!checkPasswd($pasword)) {
//            return error_show(1004, "密码格式不正确");
//        }
            $salt = makeSalt();
            $info['password'] = sha1($pasword . $salt);
            $info['pwd'] = $pasword;
            $info['salt'] = $salt;
            $info['updatetime'] = date("Y-m-d H:i:s");
        $acc= Db::name("account")->update($info);
        return $acc ?app_show(0,"账户密码修改成功"): error_show(1005, "账户密码修改失败");
    }
}