<?php

namespace app\admin\controller;

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

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

    /**
     * @auth {{/identifyCondition}}
     * @return type
     */
    function index() {
        return view();
    }

    /**
     * @auth {{/identifyCondition/list}}
     * @return type
     */
    function list() {
        $result = TalentConditionApi::getListByCondition($this->request->param());
        return json($result);
    }

    /**
     * @auth {{/identifyCondition/add}}
     * @return type
     */
    function add() {
        if ($this->request->isPost()) {
            $params = $this->request->param();
            $res = $this->myValid($params);
            if ($res !== true)
                return $res;
            if (TalentConditionApi::edit($params))
                return json(["code" => 200, "msg" => "添加认定条件成功"]);
            return json(["msg" => "添加认定条件失败"]);
        }
        return view("", ["type" => $this->user["type"]]);
    }

    /**
     * @auth {{/identifyCondition/update}}
     * @return type
     */
    function edit() {
        if ($this->request->isPost()) {
            $params = $this->request->param();
            $res = $this->myValid($params);
            if ($res !== true)
                return $res;
            if (TalentConditionApi::edit($params))
                return json(["code" => 200, "msg" => "编辑认定条件成功"]);
            return json(["msg" => "编辑认定条件失败"]);
        }
        $id = $this->request->param("id");
        $info = TalentConditionApi::getOne($id);
        return view("", ["info" => $info]);
    }

    private function myValid($params) {
        if (!$params["type"] || !in_array($params["type"], [1, 2, 5, 6]))
            return json(["msg" => "请选择人才类别"]);
        if (!$params["talentLevel"] || !in_array($params["talentLevel"], [1, 2, 3, 4, 5, 6, 7]))
            return json(["msg" => "请选择人才层次"]);
        if (!$params["talentLevelCat"] && in_array($params["type"], [1, 6]))
            return json(["msg" => "请选择人才条款"]);
        if (!$params["name"])
            return json(["msg" => "请填写名称"]);
        /* if (!$params["companyIds"]) {
          return json(["msg" => "没有设置审核单位"]);
          } */
        if ($params["companyIds"]) {
            if (!$params["bindFileTypes"]) {
                return json(["msg" => "没有设置审核附件"]);
            }

            $companyIds = array_filter(explode(",", $params["companyIds"]));
            $_total = count($companyIds);
            $_tmp = [];

            $bindFileTypes = array_filter(explode(",", $params["bindFileTypes"]));
            $total = count($bindFileTypes);
            $tmp = [];
            foreach ($params["relation"] as $_companyId => $_relation) {
                $_relations = explode(",", $_relation);
                for ($i = 0; $i < count($_relations); $i++) {
                    if (in_array($_relations[$i], $bindFileTypes))
                        $tmp[] = $_relations[$i];
                }
                if (in_array($_companyId, $companyIds))
                    $_tmp[] = $_companyId;
            }
            $_valid_count = count(array_unique($_tmp));
            if ($_valid_count != $_total) {
                return json(["msg" => "存在审核单位没有成功关联附件"]);
            }


            $valid_count = count(array_unique($tmp));
            if ($valid_count != $total) {
                return json(["msg" => "选择了审核单位及审核附件后,每个附件必须与其中一个审核单位关联"]);
            }
        }
        return true;
    }

    /**
     * @auth {{/identifyCondition/delete}}
     * @return type
     */
    function delete() {
        $id = $this->request->param("id");
        TalentConditionApi::delete($id);
        return json(["code" => 200, "msg" => "删除成功"]);
    }

    /**
     * @auth {{/identifyCondition/import}}
     */
    function import() {
        ignore_user_abort(true);
        set_time_limit(0);
        if (!$this->request->file())
            return json(["msg" => "没有选择文件"]);
        $excel = $this->request->file("file");

        if (!isExcelFile($excel->getMime()))
            return json(["msg" => "不是正确的Excel文件"]);
        $mapping = [
            0 => "type",
            1 => "talentLevel",
            2 => "name",
            3 => "activeYear",
            4 => "description"
        ];

        $path = $excel->getRealPath();
        $datas = getExcelDatas($path);
        $datas = array_slice($datas, 1); //去标题
        $inserts = [];
        while ($row = array_shift($datas)) {
            $cols = count($row);
            $companyIds = [];
            $new = [];
            for ($i = 0; $i < $cols; $i++) {
                if ($i < count($mapping)) {
                    $new[$mapping[$i]] = $row[$i];
                } else {
                    $companyIds[] = $row[$i];
                }
            }
            $new["companyIds"] = $companyIds ? implode(",", $companyIds) : null;
            $new["createTime"] = date("Y-m-d H:i:s");
            $inserts[] = $new;
        }
        $chunks = array_chunk($inserts, 200);
        foreach ($chunks as $chunk) {
            Db::table("new_talent_condition")->insertAll($chunk);
        }
        $data = ["code" => 200, "msg" => "导入成功"];
        echo sprintf('<script>parent.IdentifyCondition.callBack(%s);</script>', json_encode($data));
    }

    public function import1() {
        $datas = getExcelDatas("test.xls");
        $datas = array_slice($datas, 1); //去标题
        foreach ($datas as $k => $v) {
            $item = [];
            if ($v[4] != null) {
                switch ($v[1]) {
                    case '第一层次':
                        $item['talentLevel'] = 1;
                        break;
                    case '第二层次':
                        $item['talentLevel'] = 2;
                        break;
                    case '第三层次':
                        $item['talentLevel'] = 3;
                        break;
                    case '第四层次':
                        $item['talentLevel'] = 4;
                        break;
                    case '第五层次':
                        $item['talentLevel'] = 5;
                        break;
                    case '第六层次':
                        $item['talentLevel'] = 6;
                        break;
                    case '第七层次':
                        $item['talentLevel'] = 7;
                        break;
                }
                $item['talentLevelCat'] = $v[2];
                $item['type'] = 1;
                $item['name'] = $v[3];
                $item['active'] = 1;
                $item['companyIds'] = $v[4];
                if ($v['5'] == null) {
                    $item['bindFileTypes'] = 104;
                } else {
                    $item['bindFileTypes'] = $v[5];
                }
                $item['companyWithFileType'] = $item['companyIds'] . ':' . $item['bindFileTypes'];
                if (strpos($item['name'], "年薪")) {
                    $item['isSalary'] = 1;
                } else {
                    $item['isSalary'] = 0;
                }
                Db::table("new_talent_condition")->insert($item);
            }
        }
        //dd($datas);
    }

}