<template>
    <super-dialog v-bind="$attrs" v-model="isShowDialog" :width="width" :modal="false" :top="top" @open="open"
        @closed="closed" :title="'救援单信息'">
        <div class="eventInfo-dialog" :style="{ height }">
            <div class="form-module">
                <el-form ref="eventInfo" :model="eventInfo" :rules="rescueInfoRules" label-width="100px"
                    label-position="top" label-suffix="：">
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item label="派遣队伍" prop="teamId">
                                <el-cascader ref="rescueTeamIdCascader" v-model="eventInfo.teamId"
                                    :options="teamTreeData"
                                    :props="{ emitPath: false, checkStrictly: true, label: 'name', value: 'id' }"
                                    clearable filterable style="width: 100%" @change="teamIdChange"
                                    :show-all-levels="false"></el-cascader>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="派遣人员">
                                <el-input clearable v-model="eventInfo.person" placeholder="点击选择派遣人员" readonly
                                    class="el-click-input" @click.native="showDialog('userChoice')"
                                    suffix-icon="el-icon-search">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="派遣车辆" prop="dispatchCarCode">
                                <el-input clearable v-model="eventInfo.dispatchCarCode" placeholder="点击选择派遣车辆" readonly
                                    class="el-click-input" @click.native="showDialog('carChoice')"
                                    suffix-icon="el-icon-search">
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item label="派遣车型">
                                <el-select v-model="eventInfo.dispatchCarType" style="width: 100%" clearable
                                    placeholder="派遣车型">
                                    <el-option v-for="(item, index) in getDictionaryByCode(
                                        'jycl-cllx'
                                    )" :key="index" :label="item.name" :value="Number(item.value)" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="关联事件" prop="carWeight">
                                <el-input clearable v-model="eventInfo.eventTel" placeholder="点击选择关联事件" readonly
                                    class="el-click-input" @click.native="showDialog('eventChoice')"
                                    suffix-icon="el-icon-search">
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <div class="content-bottom">
                    <el-button size="small" @click="isShowDialog = false">
                        取 消
                    </el-button>
                    <el-button :disabled="tableLoading" :loading="saveLoading" size="small" type="primary" @click="handleAppoint">
                        确 定
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 车辆选择 -->
        <CarChoiceDialog :is-show.sync="carChoiceDialog" :selected-content.sync="eventInfo.car"
            @confirm="handleCarSelect" />
        <!-- 人员选择 -->
        <UserChoiceDialog :is-show.sync="userChoiceDialog" :selected-content.sync="eventInfo.user"
            @confirm="handleUserSelect" :teamFullId="eventInfo.teamFullId" />
        <!-- 事件选择 -->
        <EventChoiceDialog :is-show.sync="eventChoiceDialog" :selected-content.sync="eventInfo.event"
            @confirm="handleEventSelect" />
    </super-dialog>
</template>

<script>
import SuperDialog from '@/components/SuperDialog/index.vue'
import CarChoiceDialog from './components/CarChoiceDialog'
import UserChoiceDialog from './components/UserChoiceDialog'
import EventChoiceDialog from './components/EventChoiceDialog'
import { getDictionaryByCode } from '@/utils/dictionary'
import { appoint } from '@/api/patrolAndRescue/obstacleClearingRescue/rescueRegistration'
import moment from 'moment'
export default {
    name: 'AppointDialog',
    inheritAttrs: false,
    //   mixins: [TableMixin],
    props: {
        isShow: {
            default: false,
            type: Boolean
        },
        selectedContent: {
            default: () => [],
            type: [Array, Object]
        },
        top: {
            default: '14vh',
            type: String
        },
        width: {
            default: '60%',
            type: String
        },
        height: {
            default: '65vh',
            type: String
        },
        confirmCloseDialog: {
            default: true,
            type: Boolean
        },
        teamTreeData: {
            default: () => [],
            type: Array
        },
        baseInfo: {
            default: () => { },
            type: Object
        }
    },
    components: {
        SuperDialog,
        CarChoiceDialog,
        UserChoiceDialog,
        EventChoiceDialog
    },
    data() {
        return {
            // 车辆弹层
            carData: {},
            carChoiceDialog: false,
            // 人员弹层
            userChoiceDialog: false,
            initializeRendering: false, // 弹层内容初始化渲染
            tableMaxHeight: '600px',
            enhancedTableData: [], // 增强的表格数据（增加额外特性）
            eventInfo: {
                car: {},
                person: '',
                rescueTime: new Date()
            },
            rescueInfoRules: {
                person: [
                    {
                        required: true,
                        message: '派遣人员不能为空',
                        trigger: ['change']
                    }
                ],
                rescueStatus: [
                    {
                        required: true,
                        message: '请选择救援状态',
                        trigger: ['change']
                    }
                ],
                teamId: [
                    {
                        required: true,
                        message: '派遣队伍不能为空',
                        trigger: ['change']
                    }
                ],
                rescueTime: [
                    {
                        required: true,
                        message: '报案时间不能为空',
                        trigger: ['change']
                    }
                ]
            },
            tableLoading: false,
            dispatches: [],
            eventChoiceDialog: false,
            saveLoading: false,
        }
    },
    computed: {
        isShowDialog: {
            get() {
                return this.isShow
            },
            set(val) {
                this.$emit('update:isShow', val)
            }
        },
    },
    methods: {
        getDictionaryByCode,
        // 打开弹层时触发
        open() { },
        // 展示弹层
        showDialog(dialogName) {
            if (!dialogName) return
            if (dialogName === 'userChoice') {
                if (!this.eventInfo.teamId) {
                    this.$message.error('请先选择救援派遣队伍')
                } else {
                    this[dialogName + 'Dialog'] = true
                }
            } else {
                this[dialogName + 'Dialog'] = true
            }
        },
        teamIdChange() {
            this.eventInfo.teamFullId = this.$refs.rescueTeamIdCascader?.getCheckedNodes()[0]?.data?.path || ''
            this.eventInfo.teamId = this.$refs.rescueTeamIdCascader?.getCheckedNodes()[0]?.value || ''
            this.eventInfo.teamName = this.$refs.rescueTeamIdCascader?.getCheckedNodes()[0]?.data?.name || ''
            this.eventInfo.person = ''
            this.eventInfo.user = {}
            this.dispatches = []
        },
        handleCarSelect({ carNumber, carClass }) {
            console.log({ carNumber, carClass });

            this.$set(this.eventInfo, 'dispatchCarCode', carNumber)
            this.$set(this.eventInfo, 'dispatchCarType', carClass)
            this.dispatches.forEach(item => {
                item.dispatchCarCode = carNumber
                item.dispatchCarType = carClass
            })
        },
        handleUserSelect(user) {
            const { dispatchCarCode = '', dispatchCarType = '' } = this.eventInfo
            this.eventInfo.person = user.name
            this.dispatches = [
                {
                    dispatchCarCode,
                    dispatchCarType,
                    dispatchUserId: user.id,
                    dispatchUserName: user.name,
                    dispatchUserTel: user.tel,
                }
            ]
        },
        // 事件
        handleEventSelect({ id, eventTel }) {
            this.eventInfo.eventTel = eventTel
            this.eventInfo.uploadId = id

        },
        handleAppoint() {
            this.$refs.eventInfo.validate(async (valid, object) => {
                if (!valid) {
                    this.$message.warning(
                        `有${Object.keys(object).length
                        }个字段未通过校验，请正确填写表单内容。`
                    )
                } else {
                    this.saveLoading = true
                    let data = JSON.parse(JSON.stringify(this.baseInfo))
                    data.pegSVal = 'k' + (data.startPeg || '') + '+' + (data.startPegAdd || '')
                    data.pegEVal = 'k' + (data.endPeg || '') + '+' + (data.endPegAdd || '')
                    data.dispatches = JSON.parse(JSON.stringify(this.dispatches))
                    data.eventInfo = JSON.parse(JSON.stringify(this.eventInfo))
                    data.rescueTime = moment(data.rescueTime).format('YYYY-MM-DD HH:mm:ss')
                    this.$confirm('确认委派救援单吗？', '提示', {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(async () => {
                        try {
                            let { state, message, value } = await appoint({ ...data, ...data.road })
                            if (state) {
                                this.$message.success(`委派成功`)
                                this.closed()
                                this.$emit('offPage')
                            }
                        } finally {
                            this.saveLoading = false
                        }
                    })
                    // let data = JSON.parse(JSON.stringify(this.eventInfo))
                    // data.rescueTime = moment(data.rescueTime).format('YYYY-MM-DD HH:mm:ss')
                    // data.dispatches = JSON.parse(JSON.stringify(this.dispatches))
                    // this.$confirm('确认委派救援单吗？', '提示', {
                    //     confirmButtonText: '确认',
                    //     cancelButtonText: '取消',
                    //     type: 'warning'
                    // }).then(async () => {
                    //     console.log(data);

                    //     // this.$emit('confirm', data)
                    //     // this.closed()
                    // })
                }
            })
        },
        // 关闭弹层触发
        closed() {
            const { orgData } = this
            // 重置data中的数据
            Object.assign(this.$data, this.$options.data.call(this), { orgData })
            this.$nextTick(() => {
                this.$refs.eventInfo?.clearValidate()
            })
            if (this.confirmCloseDialog) this.isShowDialog = false
        },
    }
}
</script>

<style lang="scss" scoped>
@import "@/assets/css/element-variables";

.el-icon-plus {
    cursor: pointer;
    display: block;
    height: 100%;
    font-size: 16px !important;
    font-weight: 900;
    color: #43a1ff;
}

.eventInfo-dialog {
    width: 100%;
    display: flex;
    flex-direction: column;
    column-gap: 16px;
    min-height: 50vh;

    .form-module {
        width: 100%;
        height: 100%;
        flex: 1;
        display: flex;
        flex-direction: column;
        row-gap: 16px;
        background-color: $--system-module-color1;
        padding: 16px;
        box-sizing: border-box;
        border-radius: 8px;

        .el-form {
            height: calc(100% - 40px);
            overflow-y: scroll;

        }

        .content-bottom {
            display: flex;
            justify-content: flex-end;
            height: 40px;
        }

    }
}

::v-deep::-webkit-scrollbar-thumb,
::v-deep::-webkit-scrollbar {
    display: none;
}
</style>