<template>
    <div v-loading="fullLoading" class="content">
        <div class="top">
            <div class="engineering-title">
                <div>{{ $t('engineering.add') }}</div>
            </div>
            <div class="button-group">
                <el-button type="primary" icon="el-icon-circle-check" @click="submitForm" :loading="submitLoading">{{
                    $t('engineering.plot') }}</el-button>
                <el-button @click="cancel" icon="el-icon-remove-outline">
                    {{ $t('common.cancel') }}</el-button>
            </div>
        </div>

        <div class="card">
            <el-form class="plot-form" ref="form" :model="form" :rules="rules" label-position="top">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <Select required prop="projectId" :data="projectList" :label="$t('follow.relatedProject')"
                            :styleObj="{ width: '100%' }" @change="projectChange"></Select>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <Select prop="quotationId" :data="quotationList" :label="$t('engineering.quotation')"
                            :styleObj="{ width: '100%' }" @change="quotationChange"></Select>
                    </el-col>
                    <el-col :span="4">
                        <Select prop="version" :data="versionList" :clearable="false" :label="$t('quotation.version')"
                            :styleObj="{ width: '100%' }"></Select>
                    </el-col>
                    <el-col :span="6">
                        <Select prop="elevatorModelId" :data="elevatorModelList"
                            :label="$t('elevatorModel.elevatorModel')" :styleObj="{ width: '100%' }"
                            @change="elevatorModelChange"></Select>
                    </el-col>
                    <el-col :span="6">
                        <el-button :disabled="addFlag" style="margin-top: 24px;" type="primary" icon="el-icon-plus"
                            size="mini" @click="addElevator">
                            {{ $t('elevator.addElevator') }}</el-button>
                    </el-col>
                </el-row>

                <el-button style="margin-top: 24px;" type="primary" icon="el-icon-plus" size="mini"
                    @click="handleAddElevator">{{ $t('elevator.add') }}</el-button>
                <el-table class="elevator-table" :data="elevatorTableList" max-height="400px" border
                    :header-cell-style="{ background: '#F4F6F8', color: '#92A2B5' }">
                    <el-table-column label="No." type="index" width="50" align="center"></el-table-column>
                    <el-table-column prop="elevatorModel" :label="$t('elevatorModel.elevatorModel')"
                        min-width="200px"></el-table-column>
                    <el-table-column prop="elevatorCode" :label="$t('engineering.elevatorNo')"
                        min-width="200px"></el-table-column>
                    <el-table-column prop="addType" :label="$t('engineering.addType')" min-width="200px">
                        <template slot-scope="scope">
                            <span>{{ formatDict(scope.row.addType, dict.type.plot_add_type) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="specification" :label="$t('engineering.specification')" width="600px"
                        show-overflow-tooltip></el-table-column>
                    <el-table-column prop="createTime" :label="$t('common.createTime')"
                        min-width="200px"></el-table-column>
                    <el-table-column :label="$t('common.operate')" width="250px" fixed="right" align="center">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" icon="el-icon-view"
                                @click="handleViewElevator(scope.row)">{{ $t('common.view') }}
                            </el-button>
                            <el-button size="mini" type="text" icon="el-icon-edit"
                                @click="handleEditElevator(scope.row)">{{ $t('common.edit') }}
                            </el-button>
                            <el-button size="mini" type="text" icon="el-icon-delete"
                                @click="handleDeleteElevator(scope.row)">{{ $t('common.delete') }}
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <el-row :gutter="20">
                    <el-col :span="6">
                        <Select required prop="templateId" :data="templateList"
                            :label="$t('engineering.templateSelect')" :styleObj="{ width: '100%' }"></Select>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="6">
                        <Select required prop="commonShaftMaterial" :data="dict.type.shaft_material"
                            :label="$t('engineering.commonShaftMaterial')" :styleObj="{ width: '100%' }"></Select>
                    </el-col>
                </el-row>

            </el-form>
        </div>
    </div>
</template>

<script>
import { addEngineering } from "@/api/business/civil/engineering";
import { listAllTemplates } from "@/api/business/civil/templates";
import { listAllProject } from "@/api/business/crm/project";
import { listByProjectId } from "@/api/business/quotation/quotation";
import { listByQuotationId } from "@/api/business/quotation/specification";
import store from '@/store/index'
import { parseTime } from "@/utils/ruoyi";

export default {
    name: "Plot-add",
    dicts: ['shaft_material', 'plot_add_type'],
    data() {
        return {
            id: null,
            addFlag: true,
            language: this.$i18n.locale,
            fullLoading: false,
            submitLoading: false,
            form: {},
            rules: {},
            projectList: [],
            quotationList: [],
            versionList: [],
            modelList: [],
            elevatorModelList: [],
            templateList: [],
            elevatorTableList: [],
            elevatorSet: new Set(),
        }
    },
    created() {
        this.getProjectList();
        this.getTemplateList();
    },
    activated() {
        this.getStoreElevatorInfo();
    },
    methods: {
        parseTime,
        // 获取电梯页面传过来的电梯信息
        getStoreElevatorInfo() {
            let elevatorId = this.$route.query && this.$route.query.elevatorId;
            if (elevatorId !== undefined) {
                let elevator = this.$store.state.elevators[elevatorId];
                console.log('检查电梯是否存在', this.elevatorSet, elevatorId, this.elevatorSet.has(Number(elevatorId)))
                if (this.elevatorSet.has(Number(elevatorId))) {
                    console.log("重复编辑电梯", elevatorId, elevator)
                    if (elevator !== undefined && elevator != null) {
                        // 替换电梯列表
                        for (let i = 0; i < this.elevatorTableList.length; i++) {
                            if (this.elevatorTableList[i].id == elevatorId) {
                                //保留创建时间
                                elevator.createTime = this.elevatorTableList[i].createTime
                                this.$set(this.elevatorTableList, i, elevator);
                            }
                        }
                    } else {
                        console.log("编辑电梯内存获取失败")
                    }
                } else {
                    console.log("新增电梯", elevatorId)
                    if (elevator !== undefined && elevator != null) {
                        this.elevatorSet.add(Number(elevatorId));
                        // elevator.index = this.elevatorTableList.length;
                        elevator.createTime = parseTime(new Date(), '{y}-{m}-{d}');
                        this.elevatorTableList.push(elevator);
                    } else {
                        console.log("新增电梯内存获取失败")
                    }
                }
            }
            console.log('电梯列表', this.elevatorTableList)
        },
        formatDict(value, dictData) {
            return dictData.find(dict => dict.value == value)?.label;
        },
        // 查询项目列表
        getProjectList() {
            listAllProject({ language: this.language }).then(res => {
                this.projectList = res.rows.map(item => {
                    return {
                        value: item.projectId,
                        label: item.projectNo + ':  ' + item.projectName + ' - ' + item.countryName + ' - ' + item.city
                        //  + ' - ' + item.developer
                    }
                })
            })
        },
        // 根据项目查询报价列表
        getQuotationList() {
            listByProjectId(this.form.projectId).then(res => {
                this.quotationList = res.data.map(item => {
                    return {
                        value: item.id,
                        label: item.quotationNo + ':  ' + item.projectName,
                        version: item.version
                    }
                })
            })
        },
        // 根据报价查询电梯型号列表
        getModelList() {
            listByQuotationId(this.form.quotationId).then(res => {
                this.modelList = res.data;
                this.elevatorModelList = res.data.map(item => {
                    return {
                        value: item.elevatorModelId,
                        label: item.elevatorModel
                        // label: item.elevatorCode + ':  ' + item.elevatorModel
                    }
                })
            })
        },
        // 查询模板列表
        getTemplateList() {
            listAllTemplates().then(res => {
                this.templateList = res.rows.map(item => {
                    return {
                        value: item.id,
                        label: item.templateName + ' (' + item.elevatorPosition + ')'
                    }
                })
            })
        },
        // 项目改变
        projectChange() {
            this.addFlag = true;
            this.quotationList = [];
            this.versionList = [];
            this.elevatorModelList = [];
            this.$set(this.form, 'quotationId', null);
            this.$set(this.form, 'version', null);
            this.$set(this.form, 'elevatorModelId', null);
            if (this.form.projectId) {
                this.getQuotationList();
            }
        },
        // 报价单改变
        quotationChange() {
            this.addFlag = true;
            this.$set(this.form, 'elevatorModelId', null);
            if (this.form.quotationId) {
                this.getModelList();
                let version = this.quotationList.find(item => item.value == this.form.quotationId).version;
                this.versionList = [{ value: version, label: version }]
                this.$set(this.form, 'version', version);
            } else {
                this.versionList = [];
                this.elevatorModelList = [];
                this.$set(this.form, 'version', null);
            }
        },
        // 电梯型号改变
        elevatorModelChange() {
            if (this.form.elevatorModelId && this.form.quotationId && this.form.version) {
                this.addFlag = false;
            } else {
                this.addFlag = true;
            }
        },
        // 通过报价单添加电梯
        addElevator() {
            const elevatorData = this.modelList.find(item => item.elevatorModelId == this.form.elevatorModelId);
            const elevator = Object.assign({}, elevatorData);
            elevator.id = Date.now();
            // elevator.index = this.elevatorTableList.length;
            elevator.addType = '02';
            this.elevatorTableList.push(elevator)
        },
        // 新增电梯
        handleAddElevator() {
            let query = { type: 'add' }
            this.$tab.openPage(this.$t('elevator.add'), '/civil/elevator', query);
        },
        // 查看电梯
        handleViewElevator(row) {
            store.commit('PUT_ELEVATOR', row)
            let query = { type: 'view', elevatorId: row.id }
            this.$tab.openPage(this.$t('elevator.view'), '/civil/elevator', query);
        },
        // 编辑电梯
        handleEditElevator(row) {
            store.commit('PUT_ELEVATOR', row)
            let query = { type: 'edit', elevatorId: row.id }
            this.$tab.openPage(this.$t('elevator.edit'), '/civil/elevator', query);
        },
        // 删除电梯
        handleDeleteElevator(row) {
            this.elevatorTableList = this.elevatorTableList.filter(item => item.id != row.id)
            // for (let i = 0; i < this.elevatorTableList.length; i++) {
            //     this.elevatorTableList[i].index = i
            // }
            store.commit('DEL_ELEVATOR', { id: row.id })
        },
        // 取消
        cancel() {
            this.$tab.closePage();
        },
        // 提交出图
        submitForm() {
            this.$refs['form'].validate(valid => {
                if (valid) {
                    // 电梯必填
                    if (this.elevatorTableList.length == 0) {
                        this.$modal.msgError(this.$t('elevator.required'));
                        return;
                    }
                    this.submitLoading = true;
                    this.form.elevatorList = this.elevatorTableList;
                    addEngineering(this.form).then(response => {
                        if (response.code == 200) {
                            this.$modal.msgSuccess(this.$t('common.addSuccess'));
                            this.cancel();
                        } else {
                            this.$modal.msgError(response.msg);
                        }
                        this.submitLoading = false;
                    }).catch(() => { this.submitLoading = false; });

                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
::v-deep .plot-form .el-form-item--medium .el-form-item__label {
    line-height: 15px;
}

.content {
    padding: 24px;

    .top {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .engineering-title {
            font-size: 24px;
            color: #000000;
            line-height: 26px;
        }

        .button-group {
            display: flex;
        }
    }

    .card {
        margin-top: 24px;
        background-color: white;
        padding: 24px;
        box-shadow: 0px 2px 10px 0px #CED6DD;
        border-radius: 6px;

        .elevator-table {
            margin: 24px 0 40px 0;
        }
    }
}
</style>