"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __spreadArrays = (this && this.__spreadArrays) || function () {
    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
    for (var r = Array(s), k = 0, i = 0; i < il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
            r[k] = a[j];
    return r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CardTempaleServerse = void 0;
var mslib_1 = require("mslib");
var nslib_1 = require("../refs/nslib");
var typescript_ioc_1 = require("typescript-ioc");
var dayjs = require("dayjs");
var uuid_1 = require("uuid");
/**
 *
 * @date 2023-05-10 11:13:01
 * @author 郁忠彪
 */
var CardTempaleServerse = /** @class */ (function () {
    function CardTempaleServerse() {
        //操作人姓名
        this.userName = '非标';
        // 操作人id
        this.userId = "0";
        // 区域id,默认全部
        this.areaId = ['-1'];
        // 默认1
        this.lotCount = 1;
        // 支付渠道 默认其他
        this.payChannel = 1000;
        // 充值方式,(0 钱(单位:分),1 月,2 天,3 小时,4次，5 时间,默认按天充值
        this.chargeMethod = 2;
        // 充值车的充值月数或天数或次数或金额，默认0
        this.chargeNumber = 0;
        // 支付金额（单位：分），默认0
        this.amount = 0;
        // 免费赠送的月数或天数或次数，默认0
        this.freeNumber = 0;
    }
    /**
     * 新增或者修改内部车
     * @param parameters
     */
    CardTempaleServerse.prototype.addOrUpCarCardNo = function (param) {
        return __awaiter(this, void 0, void 0, function () {
            var useName, carType, carList, areaId, lotCount, validFrom, validTo, id, parkId, mustFields, checkRes, upData, carInfoRes, _i, carList_1, carInfo, upcardInfo, addPlateNoInfo, _loop_1, _a, carList_2, ow, delPlateNoInfo, _loop_2, _b, _c, ow, plateNoInfo, upRes, sqlApiClient, cardIdInfo, addRes, payRes, e_1;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        _d.trys.push([0, 15, , 16]);
                        mslib_1.logger.info("\u5185\u90E8\u8F66\u64CD\u4F5C\u8BF7\u6C42\u53C2\u6570\uFF1A" + JSON.stringify(param));
                        useName = param.useName, carType = param.carType, carList = param.carList, areaId = param.areaId, lotCount = param.lotCount, validFrom = param.validFrom, validTo = param.validTo, id = param.id, parkId = param.parkId;
                        areaId = areaId ? areaId : this.areaId;
                        lotCount = lotCount ? lotCount : this.lotCount;
                        mustFields = {
                            // "useName": "户主名",
                            "carType": "车牌类型",
                            "carList": "车牌列表",
                            "parkId": "车场id",
                        };
                        return [4 /*yield*/, this.paramsIsNullCheck(param, mustFields)];
                    case 1:
                        checkRes = _d.sent();
                        if (checkRes) {
                            return [2 /*return*/, this.resModeInfo(-1, checkRes, null)];
                        }
                        // 时间检验
                        if (validFrom && validTo) {
                            if (dayjs(validTo).valueOf() <= dayjs().valueOf()) {
                                return [2 /*return*/, this.resModeInfo(-1, '有效期结束时间不能小于当前', null)];
                            }
                            if (dayjs(validTo).valueOf() <= dayjs(validFrom).valueOf()) {
                                return [2 /*return*/, this.resModeInfo(-1, '有效期结束时间不能小于开始时间', null)];
                            }
                        }
                        upData = {
                            parkId: parkId,
                            userId: this.userId,
                            userName: this.userName,
                            cardInfo: JSON.stringify({
                                cardName: useName,
                                useName: useName,
                                remak: id ? id.toString() : '' //将第三方id保存到备注用于处理删除
                            }),
                            carLotList: [],
                            plateNoInfo: []
                        };
                        carInfoRes = void 0;
                        _i = 0, carList_1 = carList;
                        _d.label = 2;
                    case 2:
                        if (!(_i < carList_1.length)) return [3 /*break*/, 8];
                        carInfo = carList_1[_i];
                        return [4 /*yield*/, this.tyExternalApiClient.getCarCardInfo({ parkId: parkId, plateNo: carInfo.plateNo, state: 0 })];
                    case 3:
                        carInfoRes = _d.sent();
                        if (!carInfoRes) return [3 /*break*/, 7];
                        // 维护id得唯一性
                        if (id && carInfoRes.remak != id) {
                            return [2 /*return*/, this.resModeInfo(-1, '和已存在id不匹配', null)];
                        }
                        upcardInfo = {
                            cardId: carInfoRes.cardId,
                            useName: useName ? useName : carInfoRes.useName,
                            cardName: useName ? useName : carInfoRes.useName,
                            remak: id ? id : '' //将第三方id保存到备注用于处理删除
                        };
                        upData.cardInfo = JSON.stringify(upcardInfo);
                        addPlateNoInfo = [];
                        _loop_1 = function (ow) {
                            addPlateNoInfo.push({ plateNo: ow.plateNo });
                            for (var _i = 0, _a = JSON.parse(carInfoRes.plateNoInfo); _i < _a.length; _i++) {
                                var on = _a[_i];
                                if (ow.plateNo == on.plateNo) {
                                    var index = addPlateNoInfo.findIndex(function (item) { return item.plateNo == ow.plateNo; });
                                    if (index > -1) {
                                        // 将已经存在得弹出，不存在得新增
                                        addPlateNoInfo.splice(index, 1);
                                    }
                                    break;
                                }
                            }
                        };
                        // 筛选需要新增得数据
                        for (_a = 0, carList_2 = carList; _a < carList_2.length; _a++) {
                            ow = carList_2[_a];
                            _loop_1(ow);
                        }
                        delPlateNoInfo = [];
                        _loop_2 = function (ow) {
                            delPlateNoInfo.push({ id: ow.id });
                            for (var _i = 0, carList_3 = carList; _i < carList_3.length; _i++) {
                                var on = carList_3[_i];
                                if (on.plateNo == ow.plateNo) {
                                    var index = delPlateNoInfo.findIndex(function (item) { return item.id == ow.id; });
                                    if (index > -1) {
                                        // 将已经存在得弹出，不存在得删除
                                        delPlateNoInfo.splice(index, 1);
                                    }
                                    break;
                                }
                            }
                        };
                        // 筛选需要删除得数据
                        for (_b = 0, _c = JSON.parse(carInfoRes.plateNoInfo); _b < _c.length; _b++) {
                            ow = _c[_b];
                            _loop_2(ow);
                        }
                        plateNoInfo = __spreadArrays(delPlateNoInfo, addPlateNoInfo);
                        if (!(plateNoInfo.length > 0)) return [3 /*break*/, 6];
                        upData.plateNoInfo = JSON.stringify(plateNoInfo);
                        upData.carLotList = JSON.stringify(upData.carLotList);
                        return [4 /*yield*/, this.tyExternalApiClient.modifyCarCardNo(upData)];
                    case 4:
                        upRes = _d.sent();
                        if (+upRes.resCode != 0) {
                            return [2 /*return*/, upRes];
                        }
                        if (!(validFrom && validTo)) return [3 /*break*/, 6];
                        mslib_1.logger.info(dayjs(validTo).valueOf());
                        mslib_1.logger.info(dayjs(carInfoRes.carLotList[0].endTime).valueOf());
                        if (!(carInfoRes.carLotList[0].endTime && dayjs(validTo).valueOf() > dayjs(carInfoRes.carLotList[0].endTime).valueOf())) return [3 /*break*/, 6];
                        return [4 /*yield*/, this.payCarCardFee(validFrom, validTo, carType, carInfoRes.cardId, parkId)];
                    case 5: 
                    // 内部车充值
                    // 参数 validFrom充值开始时间 validTo充值开结束时间  carType车牌类型 cardId卡片id
                    return [2 /*return*/, _d.sent()];
                    case 6: return [2 /*return*/, this.resModeInfo(0, '成功', null)];
                    case 7:
                        _i++;
                        return [3 /*break*/, 2];
                    case 8:
                        if (!(!carInfoRes && carList.length > 0)) return [3 /*break*/, 14];
                        if (!useName) {
                            mslib_1.logger.info("\u65B0\u589E\u5185\u90E8\u8F66\u7528\u6237\u540D\u5FC5\u4F20");
                            return [2 /*return*/, this.resModeInfo(-1, '新增内部车用户名必传', null)];
                        }
                        sqlApiClient = nslib_1.generateTySqlApiClient(parkId);
                        if (!id) return [3 /*break*/, 10];
                        return [4 /*yield*/, sqlApiClient.selectOne("SELECT id FROM  t_" + parkId + "_card WHERE  remark='" + id + "'")];
                    case 9:
                        cardIdInfo = _d.sent();
                        if (cardIdInfo) {
                            return [2 /*return*/, this.resModeInfo(-1, 'id以存在', null)];
                        }
                        _d.label = 10;
                    case 10:
                        upData.carLotList.push({
                            carType: carType,
                            areaId: areaId,
                            lotCount: lotCount,
                            lotName: ""
                        });
                        upData.carLotList = JSON.stringify(upData.carLotList);
                        upData.plateNoInfo = JSON.stringify(carList);
                        return [4 /*yield*/, this.tyExternalApiClient.addCarCardNo(upData)];
                    case 11:
                        addRes = _d.sent();
                        if (+addRes.resCode != 0) {
                            return [2 /*return*/, addRes];
                        }
                        if (!(validFrom && validTo)) return [3 /*break*/, 13];
                        return [4 /*yield*/, this.payCarCardFee(validFrom, validTo, carType, JSON.parse(addRes.data).cardId, parkId)];
                    case 12:
                        payRes = _d.sent();
                        return [2 /*return*/, payRes];
                    case 13: return [2 /*return*/, this.resModeInfo(0, '成功', JSON.parse(addRes.data).cardId)];
                    case 14: return [3 /*break*/, 16];
                    case 15:
                        e_1 = _d.sent();
                        mslib_1.logger.info("\u5185\u90E8\u8F66\u64CD\u4F5C\u5F02\u5E38\uFF1A" + e_1);
                        return [2 /*return*/, this.resModeInfo(-1, '内部车操作异常', null)];
                    case 16: return [2 /*return*/];
                }
            });
        });
    };
    /**
         *
         * 内部车删除
         */
    CardTempaleServerse.prototype.delCarCardNo = function (param) {
        return __awaiter(this, void 0, void 0, function () {
            var carList, source, id, parkId, delRes, sqlApiClient, cardIdInfo, upData, carInfoRes, _i, carList_4, plateNo, upcardInfo, delPlateNoInfo, _a, _b, ow, _c, carList_5, on, upRes, e_2;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        mslib_1.logger.info("\u5185\u90E8\u8F66\u5220\u9664\u8BF7\u6C42\u53C2\u6570\uFF1A" + JSON.stringify(param));
                        _d.label = 1;
                    case 1:
                        _d.trys.push([1, 17, , 18]);
                        carList = param.carList, source = param.source, id = param.id, parkId = param.parkId;
                        if (!carList && carList.length == 0 && !id) {
                            return [2 /*return*/, this.resModeInfo(-1, '车牌列表和卡片id不能同时为空', null)];
                        }
                        delRes = void 0;
                        if (!id) return [3 /*break*/, 7];
                        if (!(source == 1)) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.tyExternalApiClient.delCarCardInfo({ parkId: parkId, cardId: id })];
                    case 2:
                        delRes = _d.sent();
                        return [2 /*return*/, delRes];
                    case 3:
                        sqlApiClient = nslib_1.generateTySqlApiClient(parkId);
                        return [4 /*yield*/, sqlApiClient.selectOne("SELECT id FROM  t_" + parkId + "_card WHERE  remark='" + id + "'")];
                    case 4:
                        cardIdInfo = _d.sent();
                        if (!cardIdInfo) {
                            return [2 /*return*/, this.resModeInfo(-1, '未匹配到内部车信息', null)];
                        }
                        return [4 /*yield*/, this.tyExternalApiClient.delCarCardInfo({ parkId: parkId, cardId: cardIdInfo.id })];
                    case 5:
                        delRes = _d.sent();
                        return [2 /*return*/, delRes];
                    case 6: return [3 /*break*/, 16];
                    case 7:
                        upData = {
                            parkId: parkId,
                            userId: this.userId,
                            userName: this.userName,
                            cardInfo: {},
                            carLotList: [],
                            plateNoInfo: []
                        };
                        carInfoRes = void 0;
                        _i = 0, carList_4 = carList;
                        _d.label = 8;
                    case 8:
                        if (!(_i < carList_4.length)) return [3 /*break*/, 11];
                        plateNo = carList_4[_i];
                        return [4 /*yield*/, this.tyExternalApiClient.getCarCardInfo({ parkId: parkId, plateNo: plateNo, state: 0 })];
                    case 9:
                        carInfoRes = _d.sent();
                        if (carInfoRes) {
                            return [3 /*break*/, 11];
                        }
                        _d.label = 10;
                    case 10:
                        _i++;
                        return [3 /*break*/, 8];
                    case 11:
                        if (!(JSON.parse(carInfoRes.carLotList).length == 1)) return [3 /*break*/, 13];
                        return [4 /*yield*/, this.tyExternalApiClient.delCarCardInfo({ parkId: parkId, cardId: carInfoRes.cardId })];
                    case 12: return [2 /*return*/, _d.sent()];
                    case 13:
                        if (!carInfoRes) return [3 /*break*/, 15];
                        upcardInfo = {
                            cardId: carInfoRes.cardId,
                            useName: carInfoRes.useName,
                            cardName: carInfoRes.cardName,
                        };
                        upData.cardInfo = JSON.stringify(upcardInfo);
                        delPlateNoInfo = [];
                        // 筛选需要删除得数据
                        for (_a = 0, _b = JSON.parse(carInfoRes.plateNoInfo); _a < _b.length; _a++) {
                            ow = _b[_a];
                            for (_c = 0, carList_5 = carList; _c < carList_5.length; _c++) {
                                on = carList_5[_c];
                                if (on == ow.plateNo) {
                                    delPlateNoInfo.push({ id: ow.id });
                                    break;
                                }
                            }
                        }
                        if (!(delPlateNoInfo.length > 0)) return [3 /*break*/, 15];
                        upData.plateNoInfo = JSON.stringify(delPlateNoInfo);
                        return [4 /*yield*/, this.tyExternalApiClient.modifyCarCardNo(upData)];
                    case 14:
                        upRes = _d.sent();
                        if (+upRes.resCode != 0) {
                            return [2 /*return*/, upRes];
                        }
                        return [2 /*return*/, this.resModeInfo(0, '成功', null)];
                    case 15: return [2 /*return*/, this.resModeInfo(0, '成功', null)];
                    case 16: return [3 /*break*/, 18];
                    case 17:
                        e_2 = _d.sent();
                        return [2 /*return*/, this.resModeInfo(-1, '异常：' + e_2, null)];
                    case 18: return [2 /*return*/];
                }
            });
        });
    };
    /**
          * 内部车充值
          * @param  参数 validFrom充值开始时间 validTo充值开结束时间  carType车牌类型 cardId卡片id
          */
    CardTempaleServerse.prototype.payCarCardFee = function (validFrom, validTo, carType, cardId, parkId) {
        return __awaiter(this, void 0, void 0, function () {
            var payData, payRes;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        payData = {
                            parkId: parkId,
                            userId: this.userId,
                            userName: this.userName,
                            cardId: cardId,
                            orderNo: uuid_1.v4(),
                            carType: carType,
                            payChannel: this.payChannel,
                            chargeMethod: this.chargeMethod,
                            chargeNumber: this.chargeNumber,
                            amount: this.amount,
                            freeNumber: this.freeNumber,
                            validFrom: validFrom,
                            validTo: validTo,
                            createTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
                            remark: ''
                        };
                        return [4 /*yield*/, this.tyExternalApiClient.payCarCardFee(payData)];
                    case 1:
                        payRes = _a.sent();
                        return [2 /*return*/, payRes];
                }
            });
        });
    };
    /**
        * 验证参数是否为空
        * @param data 参数
        * @param mustFields 需要验证的参数集合 string,number,object,bigint,boolean,symbol,undefined,function
        */
    CardTempaleServerse.prototype.paramsIsNullCheck = function (data, mustFields) {
        for (var item in mustFields) {
            var text = mustFields[item];
            var val = data[item];
            var type = typeof (val);
            switch (type) {
                case 'string':
                    if (val == null || val == '' || !val.length) {
                        return text + "为必填项！";
                    }
                    break;
                case 'number':
                    if (Object.is(val, NaN)) {
                        return text + "为必填项！";
                    }
                    break;
                case 'object':
                    if (val == null || !val.length) {
                        return text + "为必填项！";
                    }
                    break;
                default:
                    if (val == null) {
                        return text + "为必填项！";
                    }
                    break;
            }
        }
        return "";
    };
    CardTempaleServerse.prototype.resModeInfo = function (resCode, resMsg, date) {
        mslib_1.logger.info(resMsg);
        return { resCode: resCode, resMsg: resMsg, date: date };
    };
    __decorate([
        typescript_ioc_1.Inject,
        __metadata("design:type", nslib_1.TyExternalApiClient
        //操作人姓名
        )
    ], CardTempaleServerse.prototype, "tyExternalApiClient", void 0);
    return CardTempaleServerse;
}());
exports.CardTempaleServerse = CardTempaleServerse;
//# sourceMappingURL=CardTempaleServerse.js.map