<?php

namespace app\enterprise\controller;

use app\enterprise\common\EnterpriseController;
use think\facade\Db;
use think\facade\Log;
use app\common\api\EnterpriseApi;
use app\common\api\TalentLogApi;
use think\exception\ValidateException;
use app\common\state\ProjectState;
use app\common\api\BatchApi;
use app\common\api\HouseApi;
use app\common\model\TalentLog;
use app\common\api\DictApi;
use app\common\state\CommonConst;
use app\common\state\MainState;
use app\common\state\HouseStateEnum;
use app\common\api\Response;
use app\common\model\HousePurchase as houseModel;

/**
 * Description of House
 * 购房补贴
 * @author sgq
 */
class House extends EnterpriseController {

    public function index() {
        return view("", ['type' => session("user")['type']]);
    }

    public function list() {
        $params = $this->request;
        $order = trim($params["order"]) ?: "desc";
        $offset = trim($params["offset"]) ?: 0;
        $limit = trim($params["limit"]) ?: 10;
        $where = [];
        $where[] = ["type", "=", $this->user["type"]];
        $where[] = ["enterpriseId", "=", $this->user["uid"]];
        $where[] = ["delete", "=", 0];
        if ($params["year"]) {
            $where[] = ["year", "=", $params["year"]];
        }
        if (\StrUtil::isNotEmpAndNull($params["name"])) {
            $where[] = ["name", "like", "%" . $params["name"] . "%"];
        }
        if (\StrUtil::isNotEmpAndNull($params["idCard"])) {
            $where[] = ["idCard", "like", "%" . $params["idCard"] . "%"];
        }
        if ($params["talentArrange"]) {
            $where[] = ["talentArrange", "=", $params["talentArrange"]];
        }
        if (\StrUtil::isNotEmpAndNull($params["spouseName"])) {
            $where[] = ["spouseName", "like", "%" . $params["spouseName"] . "%"];
        }
        if (\StrUtil::isNotEmpAndNull($params["spouseIdcard"])) {
            $where[] = ["spouseIdcard", "like", "%" . $params["spouseIdcard"] . "%"];
        }
        if (\StrUtil::isNotEmpAndNull($params["childName"])) {
            $where[] = ["childName", "like", "%" . $params["childName"] . "%"];
        }
        if (\StrUtil::isNotEmpAndNull($params["childIdCard"])) {
            $where[] = ["childIdCard", "like", "%" . $params["childIdCard"] . "%"];
        }
        if ($params["marryStatus"]) {
            $where[] = ["marryStatus", "=", $params["marryStatus"]];
        }

        $count = houseModel::where($where)->count();
        $list = houseModel::where($where)->limit($offset, $limit)->order("createTime $order")->select()->toArray();
        //获取字典表婚姻状态
        $marryMap = DictApi::selectByParentCode("marry_status");
        $cardTypeMap = DictApi::selectByParentCode("card_type");
        $streetMap = DictApi::selectByParentCode("street");
        $levelMap = DictApi::selectByParentCode("talent_arrange");

        $whrCondition = [];
        $whrCondition[] = ["type", "=", $this->user["type"]];
        $conditionMap = \app\common\model\TalentCondition::where($whrCondition)->column("name", "id");
        foreach ($list as &$item) {
            $item["marryStatusName"] = $marryMap[$item["marryStatus"]];
            $item["cardTypeName"] = $cardTypeMap[$item["cardType"]];
            $item["spouseCardTypeName"] = $cardTypeMap[$item["spouseCardType"]];
            $item["childCardTypeName"] = $cardTypeMap[$item["childCardType"]];
            $item["streetName"] = $streetMap[$item["street"]];
            $item["talentArrangeName"] = $levelMap[$item["talentArrange"]];
            $item["identifyConditionCH"] = $conditionMap[$item["identifyCondition"]];
        }unset($item);
        return json(["rows" => $list, "total" => $count]);
    }

    /**
     * 申请
     */
    public function apply(\think\Request $request) {
        $param = $request->param();
        $id = isset($param["id"]) ? $param["id"] : 0;
        $vars = [];
        if ($id) {
            $info = HouseApi::getInfoById($id);
            $childrenList = HouseApi::getChildren($id);
            $houseInfo = HouseApi::getHouseInfo($info["idCard"]);
            $dicts = DictApi::findChildDictByCode("card_type");
            $vars["dicts"] = $dicts;
            $vars["row"] = $info;
            $vars["hand"] = $houseInfo ? 2 : 1;
            $vars["childrenList"] = $childrenList;
        }
        if ($request->isPost()) {
            return $this->save($info, $request);
        }
        $batch = $info["year"] ?: BatchApi::getValidBatch(ProjectState::HOUSE, $this->user["type"])["batch"];
        $vars["year"] = $batch;
        $vars["type"] = $this->user["type"];
        return view("", $vars);
    }

    public function detail(\think\Request $request) {
        $id = $this->request["id"];
        $info = HouseApi::getInfoById($id);
        $childrenList = HouseApi::getChildren($id);
        $dicts = DictApi::findChildDictByCode("card_type");
        $vars["dicts"] = $dicts;
        $vars["row"] = $info;
        $vars["childrenList"] = $childrenList;
        $vars["type"] = $this->user["type"];
        return view("", $vars);
    }

    /**
     * 提交表单
     */
    public function submitToCheck() {
        try {
            $id = $this->request["id"];
            if (\StrUtil::isEmpOrNull($id)) {
                throw new ValidateException("系统错误,提交审核失败");
            }
            $info = HouseApi::getInfoById($id);
            if (!$info) {
                throw new ValidateException("提交审核失败，请先填写基础信息");
            }
            if ($info["enterpriseId"] != $this->user["uid"]) {
                throw new ValidateException("没有对应的人才认定申报信息");
            }
            $batch = BatchApi::checkBatchValid(["type" => ProjectState::HOUSE, "year" => $info["year"], "first_submit_time" => $info["firstSubmitTime"]], $this->user["type"]);
            if ($batch["code"] != 200) {
                throw new ValidateException($batch["msg"]);
            }
            $response = $this->validateIsEdit($info["checkState"]);
            if ($response->code != 200) {
                throw new ValidateException($response->msg);
            }
            validate(\app\enterprise\validate\HouseValidator::class)->check($info);
            $response = $this->other_validate($info, 2);
            if ($response->code != 200) {
                throw new ValidateException($response->msg);
            }

            $where = [];
            $where[] = ["mainId", "=", $id];
            $where[] = ["type", "=", ProjectState::HOUSE];
            $uploadedFileTypes = Db::table("new_talent_file")->where($where)->column("distinct typeId");

            $where = [];
            $where[] = ["project", "=", ProjectState::HOUSE];
            $where[] = ["type", "=", $this->user["type"]];
            $where[] = ["must", "=", 1];
            $where[] = ["active", "=", 1];
            $where[] = ["delete", "=", 0];
            $where[] = ["id", "not in", $uploadedFileTypes];
            $unUploadfiletypes = Db::table("new_common_filetype")->where($where)->select()->toArray();
            if ($unUploadfiletypes) {
                $msg = "以下附件为必传：<br>";
                foreach ($unUploadfiletypes as $ft) {
                    $msg .= "<span style='color:red;'>*</span>" . $ft["name"] . "<br>";
                }
                throw new ValidateException($msg);
            }
            $data["id"] = $id;
            if (!$info["firstSubmitTime"]) {
                $data["firstSubmitTime"] = date("Y-m-d H:i:s");
            }
            $data["newSubmitTime"] = date("Y-m-d H:i:s");
            $data["checkMsg"] = "";
            $data["files"] = "";
            $data["fields"] = "";
            $data["toDep"] = "";
            $data["toProcess"] = null;
            $data["checkState"] = HouseStateEnum::NEED_CHECK;
            $res = houseModel::update($data);

            if ($res) {
                $user = session("user");
                $log["id"] = getStringId();
                $log["active"] = 1;
                $log["state"] = 1;
                $log["step"] = 0;
                $log["stateChange"] = HouseStateEnum::getStateName($info["checkState"]) . "->" . HouseStateEnum::getStateName($data["checkState"]);
                $log["type"] = ProjectState::HOUSE;
                $log["mainId"] = $id;
                $log["description"] = "确认提交审核";
                $log["createUser"] = "申报用户";
                $log["createTime"] = date("Y-m-d H:i:s");
                TalentLog::create($log);
                return json(new Response(Response::SUCCESS, "提交审核成功"));
            }
            throw new ValidateException("提交审核失败");
        } catch (ValidateException $e) {
            return json(new Response(Response::ERROR, $e->getMessage()));
        } catch (\think\Exception $e) {
            $logInfo = [
                "enterprise_id" => $this->user["uid"],
                "data" => $data,
                "controller" => $this->request->controller(),
                "action" => $this->request->action(),
                "errCode" => $e->getCode(),
                "errMsg" => $e->getMessage()
            ];
            Log::write($logInfo, "error");
            return json(new Response(Response::ERROR, "发生预料外错误，请联系管理员处理，错误代码：" . $e->getCode()));
        }
    }

    public function save($info, \think\Request $request) {
        Db::startTrans();
        try {
            $batch = BatchApi::checkBatchValid(["type" => ProjectState::HOUSE, "year" => $info["year"], "first_submit_time" => $info["firstSubmitTime"]], $this->user["type"]);

            if ($batch["code"] != 200) {
                throw new ValidateException($batch["msg"]);
            }
            if ($info) {
                $response = $this->validateIsEdit($info["checkState"]);
                if ($response->code != 200) {
                    throw new ValidateException($response->msg);
                }
            }
            $data = $request->param();
            $data["year"] = $batch["batch"];
            $data["type"] = $this->user["type"];
            validate(\app\enterprise\validate\HouseValidator::class)->check($data);

            $response = $this->other_validate($data, $info ? 2 : 1);
            if ($response->code != 200) {
                throw new ValidateException($response->msg);
            }

            $id = $data["id"];
            if ($id) {
                if (!$info || $info["id"] != $id || $info["enterpriseId"] != $this->user["uid"]) {
                    throw new ValidateException("没有对应的人才认定申报信息");
                }
                $data["checkState"] = $info["checkState"];
                $data["updateUser"] = $this->user["uid"];
                $data["updateTime"] = date("Y-m-d H:i:s");
            } else {
                $data["id"] = getStringId();
                $data["checkState"] = HouseStateEnum::SAVE;
                $data["createUser"] = $this->user["uid"];
                $data["createTime"] = date("Y-m-d H:i:s");
                $data["enterpriseId"] = $this->user["uid"];
                $data["isConflict"] = 2;
                $data["isRecover"] = 2;

                $houseInfo = HouseApi::getHouseInfo($data["idCard"]);
                $data["number"] = !$houseInfo ? 1 : $houseInfo["count"] + 1;
            }
            $childList = $data["childList"];
            unset($data["jstime"]);
            unset($data["childList"]);
            if ($id) {
                $res = Db::table("un_housepurchase")->update($data);
            } else {
                $res = Db::table("un_housepurchase")->insert($data);
            }
            foreach ($childList as &$children) {
                $children["pId"] = $data["id"];
                if (\StrUtil::isEmpOrNull($children["id"])) {
                    $children["id"] = getStringId();
                    $children["createTime"] = date("Y-m-d H:i:s");
                    Db::table("un_housepurchase_children")->insert($children);
                } else {
                    $children["updateTime"] = date("Y-m-d H:i:s");
                    $res = Db::table("un_housepurchase_children")->update($children);
                }
            }unset($children);
            //添加日志
            Db::table("new_talent_checklog")->insert([
                'id' => getStringId(),
                'mainId' => $data['id'],
                'type' => intval(ProjectState::HOUSE),
                'typeFileId' => null,
                'active' => 1,
                'state' => 1,
                'step' => 0,
                'stateChange' => "保存未提交",
                'description' => "添加购房补贴申报",
                'createTime' => date("Y-m-d H:i:s", time()),
                'createUser' => "申报用户"
            ]);
            $data["childList"] = $childList;
            Db::commit();
            return json(new Response(Response::SUCCESS, "添加成功", $data));
        } catch (ValidateException $e) {
            Db::rollback();
            return json(new Response(Response::ERROR, $e->getMessage()));
        } catch (\think\Exception $e) {
            Db::rollback();
            $logInfo = [
                "enterprise_id" => $this->user["uid"],
                "data" => $data,
                "controller" => $this->request->controller(),
                "action" => $this->request->action(),
                "errCode" => $e->getCode(),
                "errMsg" => $e->getMessage()
            ];
            Log::write($logInfo, "error");
            return json(new Response(Response::ERROR, "发生预料外错误，请联系管理员处理，错误代码：" . $e->getCode()));
        }
    }

    public function deleteChildren($id) {
        if (\StrUtil::isEmpOrNull($id)) {
            return new Response(Response::ERROR, "删除失败,系统错误");
        }
        $obj = HouseApi::getChildrenById($id);
        $housePurchase = HouseApi::getInfoById($obj["pId"]);
        if ($housePurchase["checkState"] != 1 && $housePurchase["checkState"] != 10) {
            return new Response(Response::ERROR, "正在审核中,无法删除");
        }
        if (HouseApi::deleteChildrenById($id)) {
            return new Response(Response::SUCCESS, "删除成功");
        }
        return new Response(Response::ERROR, "删除失败");
    }

    public function delete($id) {
        if (\StrUtil::isEmpOrNull($id)) {
            return new Response(Response::ERROR, "删除失败,系统错误");
        }
        $obj = HouseApi::getInfoById($id);
        if ($obj["checkState"] != 1) {
            return new Response(Response::ERROR, "已提交审核，无法删除");
        }
        if (HouseApi::deleteById($id)) {
            return new Response(Response::SUCCESS, "删除成功");
        }
        return new Response(Response::ERROR, "删除失败");
    }

    public function getTalentInfo($id, $year, $declareType) {
        $ti = \app\common\api\VerifyApi::getTalentInfoById($id);
        $response = $this->getTalentArrange($ti, $year);
        if ($response->code == 500) {
            return $response;
        }
        $resTalentInfo = $response->obj;
        $ti["talentArrange"] = $resTalentInfo["talentArrange"];
        $ti["identifyCondition"] = $resTalentInfo["identifyCondition"];
        $ti["identifyConditionName"] = $resTalentInfo["identifyConditionName"];
        $ti["identifyMonth"] = $resTalentInfo["identifyMonth"];
        $ti["identifyGetTime"] = $resTalentInfo["identifyGetTime"];
        $ti["certificateStartTime"] = $resTalentInfo["certificateStartTime"];
        $ti["certificateOutTime"] = $resTalentInfo["certificateOutTime"];
        //查询房产库中是否存在房产信息
        $houseInfo = HouseApi::getHouseInfo($ti["card_number"]);
        return new Response(Response::SUCCESS, "", ["talentInfo" => $ti, "houseInfo" => $houseInfo]);
    }

    private function other_validate(&$info, $type) {
        //校验配偶是否在库
        if ($info["spouseIsLibrary"] && $info["spouseIsLibrary"] == 1) {
            if (\StrUtil::isEmpOrNull($info["spouseIdcard"])) {
                return new Response(Response::ERROR, "请填写配偶证件号码");
            }
            if (\StrUtil::isEmpOrNull($info["spouseName"])) {
                return new Response(Response::ERROR, "请填写配偶姓名");
            }
            $where = [];
            $where[] = ["card_number", "=", $info["spouseIdcard"]];
            $where[] = ["name", "=", $info["spouseName"]];
            $where[] = ["checkState", "=", \app\common\api\TalentState::CERTIFICATED];
            $where[] = ["isEffect", "<>", 4];
            $where[] = ["delete", "=", 0];
            $count = Db::table("new_talent_info")->where($where)->count();
            if ($count == 0) {
                return new Response(Response::ERROR, "人才库中未查询到配偶相关信息");
            }
        }
        if (\StrUtil::isNotEmpAndNull($info["spouseIdcard"])) {
            //校验配偶是否存在申请记录，夫妻双方同时符合政策条件的，按照“就高不重复”原则，由一方选择一项申请。
            $spouseHouseInfo = HouseApi::getHouseInfo($info["spouseIdcard"]);
            if ($spouseHouseInfo && $info["declareType"] == 1 && $spouseHouseInfo["declareType"] == 1 && $spouseHouseInfo["delete"] == 0 && $spouseHouseInfo["checkState"] != HouseStateEnum::NOTPASS) {
                return new Response(Response::ERROR, "该人才的配偶已经申请购房补贴,夫妻双方仅能由一方申请");
            }
        }
        $ti = \app\common\api\VerifyApi::getTalentInfoById($info["talentId"]);
        $info["provinceCode"] = $ti["province"];
        $info["provinceName"] = $ti["provinceName"];
        $info["cityCode"] = $ti["city"];
        $info["cityName"] = $ti["cityName"];
        $info["countyCode"] = $ti["county"];
        $info["countyName"] = $ti["countyName"];
        $info["street"] = $ti["street"];
        $info["bank"] = $ti["bank"];
        $info["bankAccount"] = $ti["bank_account"];
        $info["bankNetwork"] = $ti["bank_branch_name"];
        $info["bankNumber"] = $ti["bank_number"];
        /*         * 校验上一年度人才层次 */
        if ($type == 1) {
            $responseObj = $this->getTalentArrange($ti, $info["year"]);
            if ($responseObj->code == 500) {
                return $responseObj;
            }
            $resInfo = $responseObj->obj;
            $info["talentArrange"] = $resInfo["talentArrange"];
            $info["identifyCondition"] = $resInfo["identifyCondition"];
            $info["idenfityConditionName"] = $resInfo["identifyConditionName"];
            $info["identifyGetTime"] = $resInfo["identifyGetTime"];

            //设置上一年度人才层次有效月份
            $info["monthCount"] = count($resInfo["monthList"]);
            if (in_array($info["type"], [CommonConst::ENTERPRISE_NORMAL, CommonConst::ENTERPRISE_JC]) && $info["monthCount"] < 6) {
                return new Response(Response::ERROR, "申报年度人才证书有效期未满足六个月,无法申报购房补贴");
            }
            if (in_array($info["type"], [CommonConst::ENTERPRISE_WJ, CommonConst::ENTERPRISE_GJ]) && $info["monthCount"] < 9) {
                return new Response(Response::ERROR, "申报年度人才证书有效期未满足九个月,无法申报购房补贴");
            }
            $info["talentArrangeMonths"] = implode(",", $resInfo["monthList"]);
        }
        return new Response(Response::SUCCESS, "");
    }

    private function validateIsEdit($checkState) {
        if ($checkState != HouseStateEnum::SAVE && $checkState != HouseStateEnum::FIRST_REJECT) {
            return new Response(Response::ERROR, "正在审核中,无法修改");
        }
        return new Response(Response::SUCCESS, "");
    }

    /**
     * @param talentInfo
     * @param year
     * @description 获取上一年度的人才层次，规则如下：上一年度存在多个人才层次则取占比大的人才层次，占比相同则取人才层次高者
     * @returns com.stylefeng.guns.core.common.model.ResponseObj
     * @author Liu
     * @date 2020/5/6
     * */
    private function getTalentArrange($talentInfo, $year) {
        /**
         * 判定在申报年度内或之前是否认定，申报年度之后认定无效，根据公布入选月份判断（此处还要考虑人才层次变更）
         */
        $year = substr($year, 0, 4);
        $identifyTimeField = "identifyMonth";
        $oldStartTimeField = "oldIdentifyMonth";
        $newStartTimeField = "newIdentifyMonth";
        if ($talentInfo["enterpriseType"] == CommonConst::ENTERPRISE_JC) {
            $identifyTimeField = "identifyGetTime";
            $oldStartTimeField = "oldIdentifyGetTime";
            $newStartTimeField = "newIdentifyGetTime";
        }
        if (in_array($talentInfo["enterpriseType"], [CommonConst::ENTERPRISE_WJ]) && date("Y", strtotime($talentInfo["identifyMonth"])) == "2023") {
            $talentInfo["identifyMonth"] = "2023-01-01"; //让卫健包含2023全年
        }

        $where = [];
        $where[] = ["idCard", "=", $talentInfo["card_number"]];
        $where[] = ["checkState", "=", MainState::PASS];
        $where[] = ["isPublic", "=", 6];
        $where[] = [$oldStartTimeField, "<=", $year . "-12-31"];
        $where[] = ["createTime", ">=", "2022-10-01 00:00:00"];
        $typeChanges = \app\enterprise\model\TalentTypeChange::where($where)->field("oldTalentArrange,oldIdentifyCondition,oldIdentifyGetTime,oldIdentifyOutTime,oldIdentifyConditionName,oldIdentifyMonth,oldCertificateStartTime,oldCertificateOutTime,newIdentifyMonth,newIdentifyGetTime")->order("createTime desc")->select()->toArray();

        if (!$typeChanges && strtotime($year . "-12-31") < strtotime($talentInfo[$identifyTimeField])) {
            return new Response(Response::ERROR, "在上一年度未认定优秀人才，无法申报");
        } else {
            $typeChanges[] = [
                "oldTalentArrange" => $talentInfo["talent_arrange"],
                "oldIdentifyCondition" => $talentInfo["talent_condition"],
                "oldIdentifyGetTime" => $talentInfo["identifyGetTime"],
                "oldIdentifyOutTime" => $talentInfo["identifyExpireTime"],
                "oldIdentifyConditionName" => $talentInfo["identifyConditionName"],
                "oldIdentifyMonth" => $talentInfo["identifyMonth"],
                "oldCertificateStartTime" => $talentInfo["certificateGetTime"],
                "oldCertificateOutTime" => $talentInfo["certificateExpireTime"] ?: date("Y-m-d", strtotime(sprintf("%s +6 years -1 days", $talentInfo["certificateGetTime"]))),
                "newIdentifyMonth" => ($year + 1) . "-01-01",
                "newIdentifyGetTime" => ($year + 1) . "-01-01"
            ];
            $totalMonth = \DateUtil::getMonthBetweenDates($year . "-01-01", $year . "-12-31");
            usort($typeChanges, function($a, $b) {
                return (int) $b["oldTalentArrange"] - (int) $a["oldTalentArrange"];
            });
            $months = []; //当年度可用月份
            $talentArrange = 8; //当年度最高层次
            $resTalentInfo = [];
            foreach ($typeChanges as $typeChange) {
                $startTime = $typeChange[$oldStartTimeField];
                $endTime = $typeChange[$newStartTimeField];
                $monthList = \DateUtil::getMonthBetweenDatesNotEnd($startTime, $endTime);
                $res = \DateUtil::getEveryMonthDayBetween($endTime, $endTime, $monthList);
                $intersectMonthList = array_intersect($totalMonth, $monthList);
                if (count($intersectMonthList) > 0) {
                    if ($typeChange["oldTalentArrange"] < $talentArrange) {
                        //按当年度最高
                        $talentArrange = $typeChange["oldTalentArrange"];
                        $resTalentInfo = [
                            "talentArrange" => $typeChange["oldTalentArrange"],
                            "identifyCondition" => $typeChange["oldIdentifyCondition"],
                            "identifyGetTime" => $typeChange["oldIdentifyGetTime"],
                            "identifyConditionName" => $typeChange["oldIdentifyConditionName"],
                            "certificateStartTime" => $typeChange["oldCertificateStartTime"],
                            "certificateOutTime" => $typeChange["oldCertificateOutTime"],
                            "identifyMonth" => $typeChange["oldIdentifyMonth"],
                            "dayMap" => $res
                        ];
                    }
                    $months = array_unique(array_merge($months, $intersectMonthList));
                }
            }
            $resTalentInfo["monthList"] = $months;
            if (in_array($talentInfo["enterpriseType"], [CommonConst::ENTERPRISE_JC, CommonConst::ENTERPRISE_NORMAL]) && count($months) < 6) {
                return new Response(Response::ERROR, "申报年度人才证书有效期未满足六个月,无法申报购房补贴");
            }
            if (in_array($talentInfo["enterpriseType"], [CommonConst::ENTERPRISE_WJ, CommonConst::ENTERPRISE_GJ]) && count($months) < 9) {
                return new Response(Response::ERROR, "申报年度人才证书有效期未满足九个月,无法申报购房补贴");
            }
            return new Response(Response::SUCCESS, "", $resTalentInfo);
        }
    }

}
