<template>
    <!-- 机具成套新增页面 -->
    <div>
        <PageHeader :pageContent="pageContent" @goBack="goBack" />

        <el-form
            ref="addFormRef"
            :model="addCompleteForm"
            :rules="addCompleteRules"
            inline
            label-width="120px"
        >
            <el-form-item label="成套名称" prop="completeSetName">
                <el-input
                    placeholder="请输入成套名称"
                    v-model="addCompleteForm.completeSetName"
                />
            </el-form-item>
            <el-form-item
                label="主体设备"
                prop="mainDevice"
                class="is-required"
            >
                <el-cascader
                    ref="mainDeviceRef"
                    placeholder="请选择主体设备"
                    :options="deviceTypeTreeNew"
                    :props="deviceTypeTreeProps"
                    v-model="addCompleteForm.mainDevice"
                    @change="selMainDevice"
                    :show-all-levels="false"
                    filterable
                    clearable
                    :disabled="mainDeviceDisabled"
                />
            </el-form-item>
            <el-form-item label="配套设备" prop="assortDevice">
                <el-cascader
                    ref="assortDeviceRef"
                    placeholder="请选择配套设备"
                    :options="deviceTypeTreeNew"
                    :props="deviceTypeTreeProps"
                    v-model="addCompleteForm.assortDevice"
                    @change="selAssortDevice"
                    :show-all-levels="false"
                    filterable
                    clearable
                />
            </el-form-item>
        </el-form>

        <el-row class="mb8">
            <el-button type="primary" size="mini" @click="submitComplete"
                >保 存</el-button
            >
        </el-row>

        <el-table :data="tempList" border>
            <el-table-column align="center" label="序号" type="index" />
            <el-table-column
                prop="deviceType"
                align="center"
                label="设备型号"
            />
            <el-table-column
                prop="deviceAscription"
                align="center"
                label="设备所属"
            />
            <el-table-column align="center" label="数量">
                <template slot-scope="{ row }">
                    <el-input
                        v-model="row.deviceNum"
                        style="width: 180px"
                        placeholder="请输入数量"
                        @change="deviceNumChange"
                        maxlength="9"
                    />
                </template>
            </el-table-column>
            <el-table-column align="center" label="数量">
                <template slot-scope="{ row }">
                    <el-button
                        size="mini"
                        type="danger"
                        @click="handleDelete(row)"
                        >删 除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script>
import PageHeader from '@/components/pageHeader'
import { getDeviceTypeTree } from '@/api/claimAndRefund/receive'
import {
    addCompleteSetToolsApi,
    queryCompleteSetToolsApi,
} from '@/api/store/completeTools.js'
export default {
    components: {
        PageHeader,
    },
    props: {
        editInfo: {
            type: Object,
            default: () => null,
        },
    },
    data() {
        return {
            pageContent: '成套设备新增',
            addCompleteForm: {
                completeSetName: '',
                mainDevice: '',
                assortDevice: '',
            },
            addCompleteRules: {
                completeSetName: [
                    {
                        required: true,
                        trigger: 'blur',
                        message: '请输入成套名称',
                    },
                    {
                        max: 40,
                        message: '长度不能超过40个字符',
                    },
                ],
                // mainDevice: [
                //     {
                //         required: true,
                //     },
                // ],
                // assortDevice: [
                //     {
                //         required: true,
                //     },
                // ],
            },
            deviceTypeTreeProps: {
                multiple: false,
                value: 'id',
            },
            deviceTypeTreeNew: [], // 设备选择数据源
            tempList: [],
            mainDeviceDisabled: false,
            saveParams: {
                wholeTypeName: '', // 成套名称
                createBy: sessionStorage.getItem('userId'), // 创建人
                parentId: '', // 主体设备ID
                companyId: 101,
                deviceInfo: [],
            },
            isEdit: false,
        }
    },
    async created() {
        this.getDeviceTypeTree()

        if (this.editInfo) {
            this.pageContent = '成套设备编辑'
            this.addCompleteForm.completeSetName = this.editInfo.wholeTypeName
            this.addCompleteForm.mainDevice = this.editInfo.deviceTypeId
            this.saveParams.id = this.editInfo.id
            this.mainDeviceDisabled = true
            this.isEdit = true
            const queryParams = {
                id: this.editInfo.id,
                wholeTypeName: this.editInfo.wholeTypeName,
                pageNum: 1,
                pageSize: 99999,
            }
            const { data: res } = await queryCompleteSetToolsApi(queryParams)
            this.tempList = res.rows
        }
    },
    methods: {
        //主体设备选择
        selMainDevice(val) {
            const checkNode = this.$refs['mainDeviceRef'].getCheckedNodes()

            if (checkNode.length < 1) return

            const mainDeviceObj = {
                deviceType: checkNode[0].label, // 设备名称
                deviceTypeId: val[val.length - 1], // 设备Id
                deviceNum: '', // 数量
                deviceAscription: '主体设备', // 所属类型
                ascriptionType: 1, // 所属类型 1 主体设备 2 配套设备
            }

            if (this.tempList.length === 0) {
                this.tempList.unshift(mainDeviceObj)
            } else {
                // 判断选择的配套设备是否和主体设备重复
                const isRepeat = this.tempList.some(
                    (e) => e.deviceTypeId === mainDeviceObj.deviceTypeId,
                )
                if (isRepeat) {
                    this.$message.error(
                        '该设备已选择作为配套设备，不可作为主体设备!',
                    )
                    return
                } else {
                    this.tempList.unshift(mainDeviceObj)
                }
            }

            this.mainDeviceDisabled = true
        },
        // 配套设备选择
        selAssortDevice(val) {
            const checkNode = this.$refs['assortDeviceRef'].getCheckedNodes()

            if (checkNode.length < 1) return

            const assortDeviceObj = {
                deviceType: checkNode[0].label, // 设备名称
                deviceTypeId: val[val.length - 1], // 设备Id
                deviceNum: '', // 数量
                deviceAscription: '配套设备', // 所属类型
                ascriptionType: 2, // 所属类型 1 主体设备 2 配套设备
            }

            // 先判断当前所选的配套设备是否已选择为主体设备
            if (
                this.tempList.length > 0 &&
                this.tempList[0].deviceTypeId === assortDeviceObj.deviceTypeId
            ) {
                this.$message.error(
                    '所选设备已作为主体设备，不可再作为配套设备！',
                )
                return
            }

            // 再判断当前设备是否重复添加
            const isRepeat = this.tempList.some(
                (e) => e.deviceTypeId === assortDeviceObj.deviceTypeId,
            )

            if (isRepeat) {
                this.$message.error('该设备已添加，不可重复添加!')
                return
            } else {
                this.tempList.push(assortDeviceObj)
            }
        },
        // 删除按钮
        handleDelete(row) {
            this.tempList = this.tempList.filter(
                (e) => e.deviceTypeId !== row.deviceTypeId,
            )
            // 如果当前删除的设备为主体设备 解开表单禁用状态
            if (row.ascriptionType === 1) {
                this.mainDeviceDisabled = false
            }
        },
        // 数量输入框校验
        deviceNumChange(val) {
            let reg = /^[1-9]\d*$/
            if (!reg.test(val)) {
                this.$message.error('请输入大于0的正整数！')
            }
        },
        // 保存按钮
        submitComplete() {
            this.$refs.addFormRef.validate(async (valid) => {
                if (valid) {
                    let isNum = false
                    const isMainDevice = this.tempList.some(
                        (e) => e.ascriptionType === 1,
                    )

                    if (!isMainDevice) {
                        this.$message.error('请添加主体设备！')
                        return
                    }

                    // const isAssortDevice = this.tempList.some(
                    //     (e) => e.ascriptionType === 2,
                    // )

                    // if (!isAssortDevice) {
                    //     this.$message.error('请添加配套设备！')
                    //     return
                    // }
                    try {
                        this.tempList.forEach((e) => {
                            if (!parseInt(e.deviceNum)) {
                                this.$message.error('请输入数量！')
                                isNum = true
                                throw new Error()
                            } else {
                                e.deviceNum = parseInt(e.deviceNum)
                            }
                        })
                    } catch (error) {}

                    if (isNum) return

                    this.saveParams.parentId = this.tempList[0].deviceTypeId
                    this.saveParams.wholeTypeName =
                        this.addCompleteForm.completeSetName

                    this.saveParams.deviceInfo = this.tempList
                    const res = await addCompleteSetToolsApi(this.saveParams)

                    if (res.code == 200) {
                        this.$message.success('新增成功！')
                        this.$emit('openHomePage')
                    }
                }
            })
        },

        // 获取 设备树结构数据
        async getDeviceTypeTree() {
            const params = {
                level: 4,
            }
            const res = await getDeviceTypeTree(params)
            this.deviceTypeTreeNew = res.data.filter((e) => e.companyId == 102)
        },
        goBack() {
            this.$emit('openHomePage')
            this.tempList = []
        },
    },
}
</script>

