<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\admin\controller;

use app\admin\common\AdminController;
use think\facade\Db;

/**
 * Description of Policy
 *
 * @author sgq
 */
class Policy extends AdminController {

    protected $companyId;

    public function __construct(\think\App $app) {
        parent::__construct($app);
        $this->companyId = $this->user["companyId"];
        echo "政策录入已经结束";
        exit();
    }

    public function index() {
        $company = \app\common\api\CompanyApi::getOne($this->companyId);
        $tmps = Db::table("new_policy_tmp")->where("companyId", "=", $this->companyId)->column("files", "policyId");
        $policyIds = array_keys($tmps);
        $policys = Db::table("new_policy")->order("level asc")->select()->toArray();
        foreach ($policys as $key => $policy) {
            if (in_array($policy["id"], $policyIds)) {
                $policys[$key]["checked"] = true;
            }
            $policys[$key]["files"] = $tmps[$policy["id"]];
        }
        return view("", ["company" => $company, "policys" => $policys]);
    }

    public function submit() {
        if ($this->request->isPost()) {
            $datas = $this->request["data"];
            $success = 0;
            $error = 0;
            foreach ($datas as $key => $data) {
                $policyId = $data["id"];
                $uniqueId = sprintf("%s_%s", $policyId, $this->companyId);
                $record = Db::table("new_policy_tmp")->where("id", "=", $uniqueId)->findOrEmpty();
                if ($data["checked"] == 1) {
                    //需要本单位审核
                    $save["id"] = $uniqueId;
                    $save["companyId"] = $this->companyId;
                    $save["policyId"] = $policyId;
                    $save["files"] = $data["files"];
                    if ($record) {
                        $save["updateUser"] = $this->user["uid"];
                        $save["updateTime"] = date("Y-m-d H:i:s");
                        if (Db::table("new_policy_tmp")->update($save)) {
                            $success++;
                        } else {
                            $error++;
                        }
                    } else {
                        $save["createUser"] = $this->user["uid"];
                        $save["createTime"] = date("Y-m-d H:i:s");
                        if (Db::table("new_policy_tmp")->insert($save)) {
                            $success++;
                        } else {
                            $error++;
                        }
                    }
                } else {
                    //取消本单位审核
                    if ($record) {
                        if (Db::table("new_policy_tmp")->delete($uniqueId)) {
                            $success++;
                        } else {
                            $error++;
                        }
                    } else {
                        $success++;
                    }
                }
            }
            return json(["msg" => sprintf("共处理{%d}条审核单位设置，成功{%d}条，失败{%d}条", count($datas), $success, $error)]);
        }
    }

    public function checked() {
        if ($this->request->isPost()) {
            $policyId = $this->request->param("id");
            $uniqueId = sprintf("%s_%s", $policyId, $this->companyId);
            $checked = $this->request->param("checked") ?: 1;
            $lockFileName = sprintf("storage/policy_logs/%s.lock", $uniqueId);
            if (!file_exists("storage/policy_logs")) {
                mkdir("storage/policy_logs");
            }
            $lockFile = fopen($lockFileName, "a");
            if (flock($lockFile, LOCK_EX | LOCK_NB)) {//文件锁（独占）
                try {
                    $record = Db::table("new_policy_tmp")->where("id", "=", $uniqueId)->findOrEmpty();
                    if ($checked == 1) {
                        //需要本单位审核
                        if ($record) {
                            $log = sprintf("[%s][account:%s][ERR]Already checked!", date("Y-m-d H:i:s"), $this->user["account"]);
                            fwrite($lockFile, $log . "\n");
                            return json(["msg" => "已经添加审核，不需要重复添加"]);
                        } else {
                            $data["id"] = $uniqueId;
                            $data["companyId"] = $this->companyId;
                            $data["policyId"] = $policyId;
                            $data["createUser"] = $this->user["uid"];
                            $data["createTime"] = date("Y-m-d H:i:s");
                            if (Db::table("new_policy_tmp")->insert($data)) {
                                $log = sprintf("[%s][account:%s][INFO]Checked!", date("Y-m-d H:i:s"), $this->user["account"]);
                                fwrite($lockFile, $log . "\n");
                                return json(["msg" => "添加审核成功", "code" => 200]);
                            } else {
                                $log = sprintf("[%s][account:%s][ERR]Check failure!", date("Y-m-d H:i:s"), $this->user["account"]);
                                fwrite($lockFile, $log . "\n");
                                return json(["msg" => "添加审核失败"]);
                            }
                        }
                    } else {
                        //取消本单位审核
                        if ($record) {
                            if (Db::table("new_policy_tmp")->delete($uniqueId)) {
                                $log = sprintf("[%s][account:%s][INFO]Deleted!", date("Y-m-d H:i:s"), $this->user["account"]);
                                fwrite($lockFile, $log . "\n");
                                return json(["msg" => "取消审核成功", "code" => 200]);
                            } else {
                                $log = sprintf("[%s][account:%s][ERR]Delete failure!", date("Y-m-d H:i:s"), $this->user["account"]);
                                fwrite($lockFile, $log . "\n");
                                return json(["msg" => "取消审核失败"]);
                            }
                        } else {
                            $log = sprintf("[%s][account:%s][ERR]Already deleted!", date("Y-m-d H:i:s"), $this->user["account"]);
                            fwrite($lockFile, $log . "\n");
                            return json(["msg" => "已经取消审核，不需要重复取消"]);
                        }
                    }
                } catch (\Exception $e) {
                    $log = sprintf("[%s][account:%s][ERR]%s", date("Y-m-d H:i:s"), $this->user["account"], $e->getMessage());
                    fwrite($lockFile, $log . "\n");
                    return json(["msg" => $e->getMessage()]);
                } finally {
                    flock($lockFile, LOCK_UN);
                }
            } else {
                return json(["msg" => "已经有同单位的人员在操作同一条记录，请稍候片刻"]);
            }
        }
    }

}
