<template>
    <div class="vehicleConfigurationDetailPanel">
        <el-form ref="form" :model="form" :rules="rules" label-width="108px">
            <div class="inputBox flexBox">
                <span class="label">配置ID</span>
                <div>{{ form.configCode }}</div>
            </div>
            <div class="flexBox headBox">
                <el-form-item label="配置名称:" prop="configName">
                    <el-input
                        placeholder="请输入"
                        maxlength="60"
                        v-autoTrim="{ obj: form, key: 'configName' }"
                        v-model="form.configName"
                    >
                    </el-input>
                </el-form-item>
                <el-form-item label="配置描述:" prop="configDescription">
                    <el-input
                        placeholder="请输入"
                        maxlength="200"
                        v-autoTrim="{ obj: form, key: 'configDescription' }"
                        v-model="form.configDescription"
                    >
                    </el-input>
                </el-form-item>
                <el-form-item label="车辆名称:" prop="vehicleId">
                    <el-select v-model="form.vehicleId" @change="vehicleChange">
                        <el-option
                            v-for="item in vehicleNameList"
                            :label="item.vehicleName"
                            :value="item.id"
                            :key="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="车辆描述:" prop="vehicleDescription">
                    <el-input
                        placeholder="请输入"
                        maxlength="200"
                        v-autoTrim="{ obj: form, key: 'vehicleDescription' }"
                        v-model="form.vehicleDescription"
                        disabled
                    >
                    </el-input>
                </el-form-item>
            </div>
        </el-form>

        <div class="contentBox">
            <div>
                <handle-config-list
                    ref="handleConfigList"
                    @curItem="curItem"
                    @addOne="addOne"
                    @delOne="delOne"
                    :configList="configList"
                    :curOne="curOne"
                ></handle-config-list>
            </div>

            <div
                class="model"
                v-bind:style="{ width: width + 'px', height: width / 2 + 'px' }"
            >
                <!-- <img :src="modelImgSrc" width="100%" /> -->
                <canvas-sensor
                    ref="canvasSensor"
                    :coordinate="coordinate"
                    :modelImgSrc="modelImgSrc"
                ></canvas-sensor>
            </div>

            <div class="conditions">
                <div class="btnBox">
                    <el-button type="primary" @click="saveConfig"
                        >保存设置</el-button
                    >
                </div>

                <el-form
                    ref="formA"
                    :model="formA"
                    :rules="rulesA"
                    label-width="108px"
                >
                    <div class="forms">
                        <el-form-item label="X(m):" prop="sensorX">
                            <el-input
                                placeholder="请输入"
                                maxlength="9"
                                v-autoTrim="{ obj: formA, key: 'sensorX' }"
                                v-model="formA.sensorX"
                                @input="inputChange"
                            >
                            </el-input>
                        </el-form-item>
                        <el-form-item label="Y(m):" prop="sensorY">
                            <el-input
                                placeholder="请输入"
                                maxlength="9"
                                v-autoTrim="{ obj: formA, key: 'sensorY' }"
                                v-model="formA.sensorY"
                                @input="inputChange"
                            >
                            </el-input>
                        </el-form-item>
                        <el-form-item label="Z(m):" prop="sensorZ">
                            <el-input
                                placeholder="请输入"
                                maxlength="9"
                                v-autoTrim="{ obj: formA, key: 'sensorZ' }"
                                v-model="formA.sensorZ"
                            >
                            </el-input>
                        </el-form-item>
                        <el-form-item label="横摆角(deg):" prop="sensorH">
                            <el-input
                                placeholder="请输入"
                                maxlength="9"
                                v-autoTrim="{ obj: formA, key: 'sensorH' }"
                                v-model="formA.sensorH"
                                @input="inputChange"
                            >
                            </el-input>
                        </el-form-item>
                        <el-form-item label="俯仰角(deg):" prop="sensorP">
                            <el-input
                                placeholder="请输入"
                                maxlength="9"
                                v-autoTrim="{ obj: formA, key: 'sensorP' }"
                                v-model="formA.sensorP"
                            >
                            </el-input>
                        </el-form-item>
                        <el-form-item label="翻滚角(deg):" prop="sensorR">
                            <el-input
                                placeholder="请输入"
                                maxlength="9"
                                v-autoTrim="{ obj: formA, key: 'sensorR' }"
                                v-model="formA.sensorR"
                            >
                            </el-input>
                        </el-form-item>
                        <el-form-item
                            label="端口"
                            prop="sensorPort"
                            v-show="curOne.name === 'ogt'"
                        >
                            <el-input
                                placeholder="请输入"
                                maxlength="9"
                                v-autoTrim="{ obj: formA, key: 'sensorPort' }"
                                v-model="formA.sensorPort"
                            >
                            </el-input>
                        </el-form-item>
                    </div>
                </el-form>
            </div>
        </div>
        <div class="btns">
            <el-button
                v-if="form.share === '0' || form.share === ''"
                type="primary"
                @click="save(false)"
                >保存</el-button
            >
            <el-button
                v-if="form.share === '0' || form.share === '1'"
                type="primary"
                @click="save(true)"
                >另存为</el-button
            >
            <el-button type="primary" plain @click="cancel">取消</el-button>
        </div>
    </div>
</template>

<script>
import handleConfigList from "./components/handleConfigList.vue";
import canvasSensor from "./components/canvasVehicleConfiguration.vue";
import { mapState } from "vuex";

export default {
    name: "vehicleConfigurationDetail", // 车辆配置详情
    components: { handleConfigList, canvasSensor },
    data() {
        // 校验最多4位小数
        let validateNum = (rule, value, callback) => {
            !/^(-?(0|[1-9][0-9]*))(\.\d{1,4})?$/.test(value) &&
                callback(new Error(rule.message));
            callback();
        };
        // 校验不大于180且不小于-180
        let validateNumC = (rule, value, callback) => {
            if (value < -180 || value > 180) {
                callback(new Error(rule.message));
                return;
            }
            callback();
        };

        return {
            vehicleNameList: [],
            form: {
                id: "",
                configCode: "", // 配置ID
                configName: "", // 配置名称
                configDescription: "", // 配置描述
                vehicleName: "", // 车辆名称
                vehicleId: "", // 车辆名称
                vehicleDescription: "", // 车辆描述
                share: "",
            },
            formA: {
                sensorX: "", // 传感器横向偏移量（x轴）
                sensorY: "", // 传感器横向偏移量（y轴）
                sensorZ: "", // 传感器横向偏移量（z轴）
                sensorH: "", // 横摆角
                sensorP: "", // 俯仰角
                sensorR: "", // 横滚角
                sensorPort: "", // 端口
            },
            rules: {
                configName: [
                    { required: true, message: "请输入", trigger: "blur" },
                ],
                configDescription: [
                    { required: true, message: "请输入", trigger: "blur" },
                ],
                vehicleId: [
                    {
                        required: true,
                        message: "请选择",
                        trigger: "change",
                    },
                ],
                vehicleDescription: [
                    { required: true, message: "请输入", trigger: "blur" },
                ],
            },
            rulesA: {
                sensorX: [
                    {
                        required: true,
                        message: "请输入",
                        trigger: "blur",
                    },
                    {
                        validator: validateNum,
                        message: "请输入最多带有4位小数的数字",
                        trigger: ["blur"],
                    },
                ],
                sensorY: [
                    {
                        required: true,
                        message: "请输入",
                        trigger: "blur",
                    },
                    {
                        validator: validateNum,
                        message: "请输入最多带有4位小数的数字",
                        trigger: ["blur"],
                    },
                ],
                sensorZ: [
                    {
                        required: true,
                        message: "请输入",
                        trigger: "blur",
                    },
                    {
                        validator: validateNum,
                        message: "请输入最多带有4位小数的数字",
                        trigger: ["blur"],
                    },
                ],
                sensorH: [
                    { required: true, message: "请输入", trigger: "blur" },
                    {
                        validator: validateNum,
                        message: "请输入最多带有4位小数的数字",
                        trigger: ["blur"],
                    },
                    {
                        validator: validateNumC,
                        message: "请输入不小于-180且不大于180的数字",
                        trigger: ["blur"],
                    },
                ],
                sensorP: [
                    { required: true, message: "请输入", trigger: "blur" },
                    {
                        validator: validateNum,
                        message: "请输入最多带有4位小数的数字",
                        trigger: ["blur"],
                    },
                    {
                        validator: validateNumC,
                        message: "请输入不小于-180且不大于180的数字",
                        trigger: ["blur"],
                    },
                ],
                sensorR: [
                    { required: true, message: "请输入", trigger: "blur" },
                    {
                        validator: validateNum,
                        message: "请输入最多带有4位小数的数字",
                        trigger: ["blur"],
                    },
                    {
                        validator: validateNumC,
                        message: "请输入不小于-180且不大于180的数字",
                        trigger: ["blur"],
                    },
                ],
                sensorPort: [
                    { required: false, message: "请输入", trigger: "blur" },
                ],
            },
            // 传感器对象集合
            configList: {
                camera: [],
                ogt: [],
                lidar: [],
                gps: [],
            },
            // 用于当前选中项的展示
            curOne: {
                name: "",
                index: -1,
            },
            modelImgSrc: require("@/assets/common/image/others/carTopView.png"), // 车辆图片地址
            // canDraw: false,
            width: 300,
            coordinate: { x: 0, y: 0 }, // 存放传递给canvas的值
        };
    },

    watch: {
        curOne(val) {
            if (val.name === "ogt") {
                // 校验端口号
                let validatePort = (rule, value, callback) => {
                    !/^(\d{5})$/.test(value) &&
                        callback(new Error(rule.message));

                    if (value > 65535 || value < 62000) {
                        callback(new Error(rule.message));
                        return;
                    }
                    callback();
                };

                let validatePortNoRepeat = (rule, value, callback) => {
                    let ports = this.configList.ogt.map(
                        (i) => i.sensorPort + ""
                    );
                    ports.splice(this.curOne.index, 1);
                    
                    if (ports.includes(value)) {
                        callback(new Error(rule.message));
                        return;
                    } else {
                        callback();
                    }
                };

                this.rulesA.sensorPort[0].required = true;
                this.rulesA.sensorPort[1] = {
                    validator: validatePort,
                    message: "请输入62000至65535之间的5位数字",
                    trigger: ["blur"],
                };
                this.rulesA.sensorPort[2] = {
                    validator: validatePortNoRepeat,
                    message: "端口号重复",
                    trigger: ["blur"],
                };
            } else {
                this.rulesA.sensorPort[0].required = false;
                this.rulesA.sensorPort.length = 1;
            }
        },
    },

    computed: {
        ...mapState(["fileHost", "fileUrl"]),
    },

    methods: {
        // 获取车辆名称私有下拉列表
        async getMyVehicleList() {
            await this.$axios({
                method: "post",
                url: this.$api.modelLibrary.getMyVehicleList,
                data: {},
            }).then((res) => {
                if (res.code == 200 && res.info) {
                    this.vehicleNameList = res.info;
                } else {
                    this.$message.error(res.message || "获取信息失败");
                }
            });
        },
        getImgUrl(addr) {
            let url = "";
            if (process.env.VUE_APP_IS_DEV == "true") {
                url = this.fileHost + this.fileUrl;
            } else {
                url = this.fileUrl;
            }

            let token = localStorage.getItem("Authorization").split(" ")[1];
            let src = `${url}?objectName=${addr}&access_token=${token}`;
            return src;
        },
        vehicleChange(id) {
            let item = this.vehicleNameList.find((i) => i.id == id);
            this.form.vehicleDescription = item.description;
            this.modelImgSrc = this.getImgUrl(item.vehicleTopView);
            this.$refs.canvasSensor.drawBg();
        },
        // 验证各传感器数组的每一项表单数据是否齐全
        validateSensorsList() {
            // console.log(Object.keys(this.configList));
            // console.log(Object.values(this.configList));
            // console.log(Object.entries(this.configList));

            let lists = Object.entries(this.configList);

            for (let index = 0; index < lists.length; index++) {
                const element = lists[index];
                let oneIndex = element[1].findIndex(
                    (i) => i.sensorX == null && i.sensorY == null
                );
                // console.log(oneIndex);
                if (oneIndex > -1) {
                    this.$refs.handleConfigList.configHandle(
                        element[0],
                        oneIndex
                    );

                    // 如果对应项未展开 让其展开
                    if (
                        element[0] === "camera" &&
                        !this.$refs.handleConfigList.isActiveA
                    ) {
                        this.$refs.handleConfigList.isActiveA = true;
                    } else if (
                        element[0] === "ogt" &&
                        !this.$refs.handleConfigList.isActiveB
                    ) {
                        this.$refs.handleConfigList.isActiveB = true;
                    } else if (
                        element[0] === "lidar" &&
                        !this.$refs.handleConfigList.isActiveC
                    ) {
                        this.$refs.handleConfigList.isActiveC = true;
                    } else if (
                        element[0] === "gps" &&
                        !this.$refs.handleConfigList.isActiveE
                    ) {
                        this.$refs.handleConfigList.isActiveE = true;
                    }

                    this.$message.error("请先设置数据并保存");
                    return false;
                }
            }
            return true;
        },
        save(isAdd) {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    if (isAdd) {
                        this.form.id = "";
                    }

                    if (!this.validateSensorsList()) return;
                    // console.log(this.configList);
                    // console.log(Object.keys(this.configList));
                    // console.log(Object.values(this.configList));
                    // console.log(Object.entries(this.configList));

                    // this.curOne = {
                    //     name: "gps",
                    //     index: 0,
                    // };

                    // return;

                    let data = Object.assign({}, this.form, {
                        configSensors: this.configList,
                    });
                    this.$axios({
                        method: "post",
                        url: this.$api.modelLibrary.saveConfig,
                        data,
                    }).then((res) => {
                        if (res.code == 200) {
                            this.$message.success("保存成功");
                            this.cancel();
                        } else {
                            this.$message.error(res.message || "保存失败");
                        }
                    });
                }
            });
        },
        /**
         * info 新增传感器信息
         * type 传感器类型
         */
        addOne(info, type) {
            // 如果列表里没有对应类型的数组则需手动添加
            if (!this.configList[type]) {
                this.configList[type] = [];
            }
            //若直接传info即this.form，可能是由于传入了响应式，造成数据会变动
            this.configList[type].unshift({ ...info });
        },
        delOne(type, index) {
            this.configList[type].splice(index, 1);
        },
        curItem(item, isAdd) {
            this.$refs.formA.resetFields();
            this.curOne = item;
            if (isAdd) {
                this.formA.sensorX = "0";
                this.formA.sensorY = "0";
                this.formA.sensorZ = "0";
                this.formA.sensorH = "0";
                this.formA.sensorP = "0";
                this.formA.sensorR = "0";
                if (this.curOne.name === "ogt") {
                    this.formA.sensorPort = "62001";
                }
            } else {
                Object.assign(
                    this.formA,
                    this.configList[item.name][item.index]
                );
            }
            this.$refs.canvasSensor.clear();
            this.inputChange();
        },
        saveConfig() {
            if (this.curOne.index < 0) {
                this.$message.info("请先选择传感器");
                return;
            }
            this.$refs.formA.validate((valid) => {
                if (valid) {
                    Object.assign(
                        this.configList[this.curOne.name][this.curOne.index],
                        this.formA
                    );
                    this.$message.success("保存设置成功");
                }
            });
        },
        cancel() {
            this.$router.replace({ path: "/vehicleConfigurationList" });
        },
        domHandle() {
            $(document).ready(() => {
                this.width = $(
                    ".vehicleConfigurationDetailPanel .model"
                ).outerWidth();
                // this.canDraw = true;
            });
        },
        inputChange() {
            if (this.curOne.index < 0) return;
            if (
                this.formA.sensorX === "" ||
                this.formA.sensorY === "" ||
                this.formA.sensorH === ""
            )
                return;
            this.coordinate = {
                x: this.formA.sensorX,
                y: this.formA.sensorY,
                h: this.formA.sensorH,
            };
        },
    },

    mounted() {
        setTimeout(() => {
            this.domHandle();
        }, 0);

        this.getMyVehicleList();

        if (this.$route.query.id) {
            let id = "";
            this.form.id = id = this.$route.query.id;
            this.form.share = this.$route.query.share;

            if (id) {
                this.$axios({
                    method: "post",
                    url: this.$api.modelLibrary.getConfigInfo,
                    data: {
                        id,
                    },
                }).then((res) => {
                    if (res.code == 200 && res.info) {
                        this.form = res.info;
                        this.configList = res.info.configSensors;
                        this.modelImgSrc = this.getImgUrl(
                            res.info.vehicleTopView
                        );
                        // this.validateSensorsList();
                    } else {
                        this.$message.error(res.message || "获取信息失败");
                    }
                });
            }
        }
    },
};
</script>

<style lang='less' scoped>
.vehicleConfigurationDetailPanel {
    margin: 55px 50px 0;
}

.headBox {
    .el-form-item {
        margin-right: 20px;
    }
}

.inputBox.flexBox {
    margin-bottom: 22px;

    .label {
        width: 88px;
    }

    div {
        line-height: 32px;
    }
}

.contentBox {
    display: flex;
    justify-content: space-between;
    margin-top: 30px;

    .model {
        // width: 400px;
        flex: 1;
        margin: 0 10%;
    }

    .conditions {
        .btnBox {
            padding: 0 0 30px;
        }

        .forms /deep/ .el-form-item__label {
            width: 120px !important;
        }

        .forms /deep/ .el-form-item__content {
            margin-left: 120px !important;
        }
    }
}

.btns {
    padding-top: 30px;
    text-align: center;
}
</style>