<template>
    <div class="app-container">
        <!-- 首页搜索 -->
        <el-form
            :model="formData"
            ref="formData"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="100px"
            @submit.native.prevent
        >
            <el-form-item label="成套设备名称" prop="wholeTypeName">
                <el-input
                    v-model="formData.wholeTypeName"
                    placeholder="请输入成套设备名称"
                    clearable
                    maxlength="50"
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <!-- <el-form-item label="主体设备" prop="keyWord">
                <el-input
                    v-model="formData.keyWord"
                    placeholder="请输入关键字"
                    clearable
                    maxlength="50"
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="创建日期" prop="keyWord">
                <el-input
                    v-model="formData.keyWord"
                    placeholder="请输入关键字"
                    clearable
                    maxlength="50"
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item> -->
            <el-form-item>
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                    >搜索</el-button
                >
                <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    >新增</el-button
                >
            </el-col>

            <right-toolbar
                :showSearch.sync="showSearch"
                @queryTable="getList"
            />
        </el-row>

        <!-- 列表 -->
        <el-table :data="tableList" border>
            <el-table-column
                label="序号"
                align="center"
                width="80"
                type="index"
                :index="
                    indexContinuation(queryParams.pageNum, queryParams.pageSize)
                "
            >
            </el-table-column>
            <el-table-column
                prop="wholeTypeName"
                label="成套设备名称"
                align="center"
            />
            <el-table-column
                prop="typeModelName"
                label="主体设备"
                align="center"
            />
            <el-table-column
                prop="totalNum"
                label="配套设备种类数量"
                align="center"
            />
            <el-table-column prop="nickName" label="创建人" align="center" />
            <el-table-column
                prop="createTime"
                label="创建日期"
                align="center"
            />
            <el-table-column label="操作" align="center">
                <template v-slot="{ row }">
                    <!-- <el-button
                        type="text"
                        icon="el-icon-search"
                        @click="handleDetail(row)"
                        >查看</el-button
                    > -->
                    <el-button
                        type="text"
                        icon="el-icon-edit"
                        @click="handleEdit(row)"
                        >编辑</el-button
                    >
                    <el-button
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDeleteRow(row)"
                        >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="formData.pageNum"
            :limit.sync="formData.pageSize"
            @pagination="getList"
        />

        <!-- 弹框 -->
        <el-dialog
            :title="title"
            :visible.sync="open"
            v-if="open"
            width="80%"
            :close-on-click-modal="false"
        >
            <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 max-height="400">
                <el-table-column align="center" label="序号" type="index" />
                <el-table-column
                    prop="typeName"
                    align="center"
                    label="设备名称"
                />
                <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>
        </el-dialog>
    </div>
</template>

<script>
// import {
//     getDeviceTypeTree,
//     addOrUpdateWhole,
//     searchSelectList,
//     searchSelectListById,
//     deleteById,
//     editRequest,
// } from '@/api/store/poleConfig'

import { getDeviceTypeTree } from '@/api/claimAndRefund/receive'
import {
    addCompleteSetToolsApi,
    queryCompleteSetToolsApi,
    getCompleteSetToolsApi,
    delCompleteSetToolsApi,
} from '@/api/store/completeTools.js'
export default {
    name: 'poleConfig',
    data() {
        return {
            isLoading: false,
            showSearch: true,
            formData: {
                wholeTypeName: '',
                pageNum: 1,
                pageSize: 10,
            },
            houseList: [],
            title: '新增',
            open: false,
            dialogForm: {
                parentId: '',
                mountingsValue: [],
                keyWord: '',
            },
            typeOptions: [],
            mountingsOptions: [],
            dialogList: [],
            selectList: [],
            isDetail: false,
            isEdit: false,
            total: 0,
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                keyWord: '',
            },
            rowId: '',

            wholeTypeName: [],
            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,
            deviceName: '',
            tableList: [],
        }
    },
    created() {
        this.getList()
        // 获取设备树
        this.getDeviceTypeTree()
        // getDeviceTypeTree().then((res) => {
        //     // 处理为typeOptions需要的数据格式
        //     const data = res.data
        //     // this.typeOptions = this.getTree(data)
        //     // this.mountingsOptions = this.getTree(data)
        //     this.typeOptions = this.mountingsOptions = this.getTree(data)
        // })
        // getDeviceTypeTree().then(res => {
        //   // 处理为mountingsOptions需要的数据格式
        //   const data = res.data
        //   this.mountingsOptions = this.getTree(data)
        // })
    },
    methods: {
        // 获取列表
        async getList() {
            const res = await getCompleteSetToolsApi(this.formData)
            console.log(res, '成套列表')

            this.tableList = res.rows
            this.total = res.total
            // this.houseList = []
            // this.queryParams.pageNum = data.page || 1
            // this.queryParams.pageSize = data.limit || 10
            // this.queryParams.keyWord = this.formData.keyWord || ''
            // const res = await searchSelectList({ ...this.queryParams })
            // this.houseList = res.data.result
            // this.total = res.data.totalCount || 0
        },
        // 查询
        handleQuery() {
            this.queryParams.pageNum = 1
            const keyWord = this.formData.keyWord?.trim() || ''
            this.getList({ keyWord })
        },
        handleSearch() {
            const keyWord = this.dialogForm.keyWord?.trim() || ''
            this.getDetail({ id: this.rowId, keyWord })
        },
        // 重置
        resetQuery() {
            this.formData.keyWord = ''
            this.getList()
        },
        resetSearch() {
            this.dialogForm.keyWord = ''
            this.getDetail({ id: this.rowId })
        },
        // 新增
        handleAdd() {
            // 打开新增弹窗
            this.title = '成套设备新增'
            this.addCompleteForm = {
                completeSetName: '',
                mainDevice: '',
                assortDevice: '',
            }
            this.tempList = []
            this.open = true
        },
        // 编辑
        async handleEdit(row) {
            this.title = '成套设备编辑'
            this.addCompleteForm.completeSetName = row.wholeTypeName
            this.addCompleteForm.mainDevice = row.deviceTypeId
            this.saveParams.id = row.id
            this.mainDeviceDisabled = true
            this.isEdit = true
            const queryParams = {
                id: row.id,
                wholeTypeName: row.wholeTypeName,
                pageNum: 1,
                pageSize: 99999,
            }
            const { rows: res } = await queryCompleteSetToolsApi(queryParams)
            this.tempList = res
            this.open = true
        },

        // 删除当前行
        handleDeleteRow(row) {
            this.$confirm('是否确定删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    delCompleteSetToolsApi({
                        id: row.id,
                        wholeTypeName: row.wholeTypeName,
                    })
                        .then((res) => {
                            this.$message({
                                type: 'success',
                                message: '删除成功!',
                            })

                            this.getList()
                        })
                        .catch((err) => {
                            this.$message({
                                type: 'error',
                                message: '删除失败!',
                            })
                        })
                })
                .catch(() => {})
        },

        /**
         *  重庆、宁夏共享成套 2024.8.30拷贝宁夏成套设备页面改造
         *  以下为弹框内操作代码逻辑
         */
        //主体设备选择
        selMainDevice(val) {
            this.$message.closeAll()
            const checkNode = this.$refs['mainDeviceRef'].getCheckedNodes()
            this.recursionGetDeviceName(
                this.deviceTypeTreeNew,
                val[val.length - 2],
            )
            if (checkNode.length < 1) return

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

            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) {
            this.$message.closeAll()
            const checkNode = this.$refs['assortDeviceRef'].getCheckedNodes()
            this.recursionGetDeviceName(
                this.deviceTypeTreeNew,
                val[val.length - 2],
            )

            if (checkNode.length < 1) return

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

            // 先判断当前所选的配套设备是否已选择为主体设备
            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.title === '成套设备新增'
                                ? '新增成功！'
                                : '修改成功！',
                        )
                        this.open = false
                        this.tempList = []
                        this.getList()
                    }
                }
            })
        },

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

        // 递归获取设备名称
        recursionGetDeviceName(list, id) {
            try {
                list.map((e) => {
                    if (e.id == id) {
                        this.deviceName = e.label
                        throw new Error()
                    } else {
                        if (e.children && e.children.length > 0) {
                            this.recursionGetDeviceName(e.children, id)
                        }
                    }
                })
            } catch (error) {}
        },
    },
}
</script>

<style lang="scss" scoped></style>
