<template>
    <el-dialog
        v-dialogDrag
        v-loading.fullscreen.lock="fullscreenLoading"
        :before-close="cancel"
        :title="dialogTitle"
        :visible.sync="dialogShowFlag"
        append-to-body
        width="600px"
        center 
    >
        <div class="form_box_one">
            <div style="font-size: 16px;">总金额（元）：{{ totalPrice }}</div>
            <el-form ref="dynamicValidateForm" :model="dynamicValidateForm" class="demo-dynamic" label-width="140px">
                <div v-for="(domain, index) in dynamicValidateForm.premiumList" :key="domain.key" class="bor_box">
                    <p class="form_box_title">编码管理设备</p>
                    <div class="form_box_line"></div>
                    <div class="form_box_item">
                        <el-form-item :prop="'premiumList.' + index + '.repairRemark'" label="技术鉴定：">
                            <el-input
                                v-model="domain.repairRemark"
                                placeholder="请输入"
                                size="small"
                                style="width: 350px"
                            ></el-input>
                        </el-form-item>
                        <el-form-item :prop="'premiumList.' + index + '.partId'" label="需要的配件：">
                            <treeselect
                                v-model="domain.partId"
                                style="width: 350px"
                                 :options="getTopTwoLevels(deptList)"
                                :normalizer="normalizer"
                                noChildrenText="没有数据了"
                                noOptionsText="没有数据"
                                noResultsText="没有搜索结果"
                                placeholder="请选择配件"
                                :disable-branch-nodes="true"
                                @input="handleSelectTree($event, index)"
                            />
                        </el-form-item>
                        <el-form-item v-if="index == 0" :prop="'premiumList.' + index + '.repairer'" label="维修人：">
                            <el-select
                                v-model="domain.repairer"
                                placeholder="请选择"
                                size="small"
                                filterable
                                style="width: 350px"
                            >
                                <el-option
                                    v-for="dict in userSelectList"
                                    :key="dict.userId"
                                    :label="dict.userName"
                                    :value="dict.userId"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item v-if="index == 0" :prop="'premiumList.' + index + '.updateTime'" label="维修时间：">
                            <el-date-picker
                                v-model="domain.updateTime"
                                type="date"
                                value-format="yyyy-MM-dd"
                                style="width: 350px"
                                placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                        <!-- <el-form-item
                            :prop="'premiumList.' + index + '.partType'"
                            label="是否收费："
                            required
                            :rules="{
                                required: true,
                                message: '请选择是否收费',
                                trigger: 'blur',
                            }"
                        >
                            <el-radio-group style="width: 350px" v-model="domain.partType">
                                <el-radio :label="1">是</el-radio>
                                <el-radio :label="0">否</el-radio>
                            </el-radio-group>
                        </el-form-item> -->

                        <el-form-item
                            :prop="'premiumList.' + index + '.partNum'"
                            label="配件数量："
                            :rules="{
                                required: false,
                                validator: numberIntegerValidatorPart,
                                trigger: 'blur',
                            }"
                        >
                            <el-input
                                v-model="domain.partNum"
                                placeholder="请输入"
                                size="small"
                                maxlength="10"
                                style="width: 350px"
                     
                            ></el-input>
                        </el-form-item>
                        <el-form-item
                            :prop="'premiumList.' + index + '.partCost'"
                            label="费用(元)："
                            :rules="{
                                required: false,
                                validator: meneyIntegerValidator,
                                trigger: 'change',
                            }"
                        >
                            <!-- <el-input
                                v-model="domain.partCost"
                                placeholder="请输入"
                                size="small"
                                maxlength="10"
                                style="width: 350px"
                            ></el-input> -->
                            <el-select
                                v-model="domain.partCost"
                                placeholder="请选择费用"
                                size="small"
                                style="width: 350px"
                                clearable
                            >
                                <el-option
                                    v-for="price in domain.childPrices"
                                    :key="price"
                                    :label="price"
                                    :value="price"
                                />
                            </el-select>
                        </el-form-item>

                        <el-form-item
                            :prop="'premiumList.' + index + '.partChange'"
                            label="更换下的配件："
                            :rules="{
                                required: false,
                                trigger: 'blur',
                            }"
                        >
                            <el-input
                                v-model="domain.partChange"
                                placeholder="请输入"
                                size="small"
                                maxlength="10"
                                style="width: 350px"
                            ></el-input>
                        </el-form-item>

                        <el-form-item
                            :prop="'premiumList.' + index + '.partChangeNum'"
                            label="更换的配件数量："
                            :rules="{
                                required: false,
                                validator: meneyIntegerValidator,
                                trigger: 'blur',
                            }"
                        >
                            <el-input
                                v-model="domain.partChangeNum"
                                placeholder="请输入"
                                size="small"
                                maxlength="10"
                                style="width: 350px"
                            ></el-input>
                        </el-form-item>
                        <el-form-item :prop="'premiumList.' + index + '.repairContent'" label="维修内容：">
                            <el-input
                                v-model="domain.repairContent"
                                maxlength="100"
                                placeholder="请输入"
                                show-word-limit
                                size="small"
                                style="width: 350px"
                                type="textarea"
                            ></el-input>
                        </el-form-item>
                        <el-form-item :prop="'premiumList.' + index + '.fileList'" label="附件：">
                            <el-upload
                                ref="upload_attach"
                                class="upload-demo"
                                :action="uploadUrl"
                                :headers="headers"
                                :data="{ fileType: 'sx' }"
                                list-type="picture-card"
                                accept="image/*,application/pdf,.doc,.docx"
                                :multiple="false"
                                :limit="5"
                                :file-list="domain.fileList"
                                :before-upload="beforeUpload"
                                :on-exceed="handleExceed"
                                :on-success="(res, file, fileList) => handleSuccess(file, fileList, domain)"
                                style="width: 350px"
                            >
                                <i slot="default" class="el-icon-plus"></i>
                                <div slot="file" slot-scope="{ file }">
                                    <img
                                        v-if="isPDF(file)"
                                        class="el-upload-list__item-thumbnail"
                                        :src="pdfImg"
                                        alt=""
                                    />
                                    <img
                                        v-else-if="isWord(file)"
                                        class="el-upload-list__item-thumbnail"
                                        :src="wordImg"
                                        alt=""
                                    />
                                    <img v-else class="el-upload-list__item-thumbnail" :src="file.fileUrl" alt="" />
                                    <span class="el-upload-list__item-actions">
                                        <span class="el-upload-list__item-preview" @click="handlePreview(file)">
                                            <i class="el-icon-zoom-in" />
                                        </span>
                                        <span class="el-upload-list__item-delete" @click="handleRemove(file, domain)">
                                            <i class="el-icon-delete" />
                                        </span>
                                    </span>
                                </div>
                            </el-upload>
                        </el-form-item>
                    </div>
                    <div class="add_box">
                        <el-button icon="el-icon-plus" size="mini" type="success" @click="addDomainOne"
                            >添加配件
                        </el-button>
                        <el-button size="mini" icon="el-icon-delete" @click="delDomain(domain, 1)" v-show="index > 0"
                            >删除</el-button
                        >
                    </div>
                </div>
            </el-form>
            <div slot="footer" class="dialog-footer" v-if="rowObj.code !== null && rowObj.code !== ''">
                <el-button @click="cancel">取消</el-button>
                <el-button  @click="clearSave" v-if="rowObj.submitStatus==1">清除保存</el-button>
                <el-button type="primary" @click="save">保存</el-button>
                <el-button type="success" @click="submit">提交</el-button>
            </div>
        </div>
        <div class="form_box_two">
            <el-form
                ref="dynamicValidateFormTwo"
                :model="dynamicValidateFormTwo"
                class="demo-dynamic"
                label-width="140px"
            >
                <div v-for="(domain, index) in dynamicValidateFormTwo.premiumListTwo" :key="domain.key" class="bor_box">
                    <p class="form_box_title">数量管理设备</p>
                    <div class="form_box_line"></div>
                    <div class="form_box_item">
                        <el-form-item :prop="'premiumListTwo.' + index + '.repairRemark'" label="技术鉴定：">
                            <el-input
                                v-model="domain.repairRemark"
                                placeholder="请输入"
                                size="small"
                                style="width: 350px"
                            ></el-input>
                        </el-form-item>
                        <el-form-item
                            v-if="index == 0"
                            :prop="'premiumListTwo.' + index + '.repairNum'"
                            label="维修数量："
                            :rules="{
                                required: true,
                                validator: numberIntegerValidator,
                                trigger: 'blur',
                            }"
                        >
                            <el-input
                                v-model="domain.repairNum"
                                placeholder="请输入"
                                size="small"
                                maxlength="10"
                                style="width: 350px"
                            ></el-input>
                        </el-form-item>
                        <el-form-item
                            v-if="index == 0"
                            :prop="'premiumListTwo.' + index + '.repairer'"
                            label="维修人："
                        >
                            <el-select
                                v-model="domain.repairer"
                                placeholder="请选择"
                                size="small"
                                filterable
                                style="width: 350px"
                            >
                                <el-option
                                    v-for="dict in userSelectList"
                                    :key="dict.userId"
                                    :label="dict.userName"
                                    :value="dict.userId"
                                />
                            </el-select>
                        </el-form-item>

                        <el-form-item v-if="index == 0" :prop="'premiumListTwo.' + index + '.updateTime'" label="维修时间：">
                                <el-date-picker
                                    v-model="domain.updateTime"
                                    type="date"
                                    value-format="yyyy-MM-dd"
                                    style="width: 350px"
                                    placeholder="选择日期">
                                </el-date-picker>
                        </el-form-item>
                        <el-form-item :prop="'premiumListTwo.' + index + '.partId'" label="需要的配件：">
                            <treeselect
                                style="width: 350px"
                                v-model="domain.partId"
                                :options="getTopTwoLevels(deptList)"
                                :normalizer="normalizer"
                                noChildrenText="没有数据了"
                                noOptionsText="没有数据"
                                noResultsText="没有搜索结果"
                                placeholder="选择配件"
                                :disable-branch-nodes="true"
                                @input="handleSelectTreeNum($event, index)"
                            />
                        </el-form-item>
                        <!-- <el-form-item
                            :prop="'premiumListTwo.' + index + '.partType'"
                            label="是否收费："
                            required
                            :rules="{
                                required: true,
                                message: '请选择是否收费',
                                trigger: 'blur',
                            }"
                        >
                            <el-radio-group style="width: 350px" v-model="domain.partType">
                                <el-radio :label="1">是</el-radio>
                                <el-radio :label="0">否</el-radio>
                            </el-radio-group>
                        </el-form-item> -->
                        <el-form-item
                            :prop="'premiumListTwo.' + index + '.partNum'"
                            label="配件数量："
                            :rules="{
                                required: false,
                                validator: numberIntegerValidatorPart,
                                trigger: 'blur',
                            }"
                        >
                            <el-input
                                v-model="domain.partNum"
                                placeholder="请输入"
                                size="small"
                                maxlength="10"
                                style="width: 350px"
                            ></el-input>
                        </el-form-item>
                        <el-form-item
                            :prop="'premiumListTwo.' + index + '.partCost'"
                            label="费用(元)："
                            :rules="{
                                required: false,
                                validator: meneyIntegerValidator,
                                trigger: 'change',
                            }"
                        >
                            <!-- <el-input
                                v-model="domain.partCost"
                                placeholder="请输入"
                                size="small"
                                maxlength="10"
                                style="width: 350px"
                            ></el-input> -->
                            <el-select
                                v-model="domain.partCost"
                                placeholder="请选择费用"
                                size="small"
                                style="width: 350px"
                                clearable
                            >
                                <el-option
                                    v-for="price in domain.childPrices"
                                    :key="price"
                                    :label="price"
                                    :value="price"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item
                            :prop="'premiumListTwo.' + index + '.partChange'"
                            label="更换下的配件："
                            :rules="{
                                required: false,
                                trigger: 'blur',
                            }"
                        >
                            <el-input
                                v-model="domain.partChange"
                                placeholder="请输入"
                                size="small"
                                maxlength="10"
                                style="width: 350px"
                            ></el-input>
                        </el-form-item>

                        <el-form-item
                            :prop="'premiumListTwo.' + index + '.partChangeNum'"
                            label="更换的配件数量："
                            :rules="{
                                required: false,
                                validator: meneyIntegerValidator,
                                trigger: 'blur',
                            }"
                        >
                            <el-input
                                v-model="domain.partChangeNum"
                                placeholder="请输入"
                                size="small"
                                maxlength="10"
                                style="width: 350px"
                            ></el-input>
                        </el-form-item>
                        <el-form-item :prop="'premiumListTwo.' + index + '.repairContent'" label="维修内容：">
                            <el-input
                                v-model="domain.repairContent"
                                maxlength="100"
                                placeholder="请输入"
                                show-word-limit
                                size="small"
                                style="width: 350px"
                                type="textarea"
                            ></el-input>
                        </el-form-item>
                        <el-form-item :prop="'premiumListTwo.' + index + '.fileList'" label="附件：">
                            <el-upload
                                ref="upload_attach"
                                class="upload-demo"
                                :action="uploadUrl"
                                :headers="headers"
                                list-type="picture-card"
                                accept="image/*,application/pdf,.doc,.docx"
                                :multiple="false"
                                :limit="5"
                                :file-list="domain.fileList"
                                :before-upload="beforeUpload"
                                :on-exceed="handleExceed"
                                :on-success="(res, file, fileList) => handleSuccess(file, fileList, domain)"
                                style="width: 350px"
                            >
                                <i slot="default" class="el-icon-plus"></i>
                                <div slot="file" slot-scope="{ file }">
                                    <img
                                        v-if="isPDF(file)"
                                        class="el-upload-list__item-thumbnail"
                                        :src="pdfImg"
                                        alt=""
                                    />
                                    <img
                                        v-else-if="isWord(file)"
                                        class="el-upload-list__item-thumbnail"
                                        :src="wordImg"
                                        alt=""
                                    />
                                    <img v-else class="el-upload-list__item-thumbnail" :src="file.fileUrl" alt="" />
                                    <span class="el-upload-list__item-actions">
                                        <span class="el-upload-list__item-preview" @click="handlePreview(file)">
                                            <i class="el-icon-zoom-in" />
                                        </span>
                                        <span class="el-upload-list__item-delete" @click="handleRemove(file, domain)">
                                            <i class="el-icon-delete" />
                                        </span>
                                    </span>
                                </div>
                            </el-upload>
                        </el-form-item>
                    </div>
                    <div class="add_box">
                        <el-button icon="el-icon-plus" size="mini" type="success" @click="addDomainTwo"
                            >添加配件
                        </el-button>
                        <el-button size="mini" icon="el-icon-delete" @click="delDomain(domain, 2)" v-show="index > 0"
                            >删除</el-button
                        >
                    </div>
                </div>
            </el-form>
            <div slot="footer" class="dialog-footer" v-if="rowObj.code == null || rowObj.code == ''">
                <el-button @click="cancel">取消</el-button>
                <el-button  @click="clearSaveTwo" v-if="rowObj.submitStatus==1">清除保存</el-button>
                <el-button type="primary" @click="saveTwo">保存</el-button>
                <el-button type="success" @click="submitTwo">提交</el-button>
            </div>
        </div>
    </el-dialog>
</template>
<script>
import {
    getUserSelectApi,
    getRepairMaTypeListApi,
    listPartType,
    getCostByPidAndNumApi,

    submitRepairApplyApiNew,
    saveRepairApplyApiNew,
    getSaveInfo,
    clearSaveApi,
} from '@/api/repairTest/repair'
// import { listPartType, } from "@/api/store/tools";
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getInfo } from '@/api/login'

export default {
    components: { Treeselect },
    props: {
        // 弹窗是否显示
        isShowFlag: {
            type: Boolean,
            default: false,
        },
        // 对应操作数据键值
        priKey: {
            type: [String, Number],
            default: '',
        },
        //弹窗标题
        dialogTitle: {
            type: String,
            default: '',
        },
        //弹窗标题
        rowObj: {
            type: Object,
            default: {},
        },
    },
    watch: {
        // 监听计算属性 formToWatch 的变化
        formToWatch: {
            handler: 'calculateTotalPrice',
            deep: true
        },
        isShowFlag(val) {
            if (val) {
                this.init()
                this.calculateTotalPrice(); // 弹窗显示时计算总金额
            }
        },
        // // 监听 rowObj.manageType 变化，变化时重新计算总金额
        // 'rowObj.manageType': {
        //     handler: 'calculateTotalPrice',
        //     immediate: true
        // }
    },
    computed: {
        dialogShowFlag: {
            get() {
                return this.isShowFlag
            },
            set(v) {
                this.$emit('update:isShowFlag', v)
            },
        },
                // 根据 manageType 动态返回要监听的表单数据
        formToWatch() {
            return this.rowObj.manageType == 0 ? this.dynamicValidateForm.premiumList : this.dynamicValidateFormTwo.premiumListTwo;
        }
    },
    data() {
        return {
            uploadUrl: process.env.VUE_APP_BASE_API + '/system/sys/file/upload', // 上传的图片服务器地址
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('token'),
            },
            pdfImg: require('@/assets/images/pdf.png'),
            wordImg: require('@/assets/images/word.png'),
            fullscreenLoading: false,
            dynamicValidateForm: {
                premiumList: [
                    {
                        selected: 'Y',
                        premium: undefined,
                        rate: undefined,
                        feeRate: undefined,
                        fee: undefined,
                        baofei1_unit: '',
                        shangyoufeiyonge_unit: '',
                        downRate: undefined,
                        downFee: undefined,
                        xiayoufeiyonge_unit: '',
                        fileList: [], // 附件
                        repairRemark: '', // 技术鉴定
                    },
                ],
            },
            dynamicValidateFormTwo: {
                premiumListTwo: [
                    {
                        selected: 'Y',
                        premium: undefined,
                        rate: undefined,
                        feeRate: undefined,
                        fee: undefined,
                        baofei1_unit: '',
                        shangyoufeiyonge_unit: '',
                        downRate: undefined,
                        downFee: undefined,
                        xiayoufeiyonge_unit: '',
                        fileList: [], // 附件
                        repairRemark: '', // 技术鉴定
                    },
                ],
            },
            deptList: [],
            userSelectList: [],
            companyId: '',
            taskId: '',
            isRequired: false,
            totalPrice: 0, // 总金额

            currentUserId: '' //当前登录人
        }
    },
    mounted() {
        this.calculateTotalPrice();
        this.$eventBus.$on('typeId', (typeId) => {
            this.typeId = typeId
            this.calculateTotalPrice(); // typeId变化时计算总金额
        })
        this.getTree()
    },
    methods: {
        calculateTotalPrice() {
            let total = 0;
            if(this.rowObj.manageType == 0){
                this.dynamicValidateForm.premiumList.forEach((domain) => {
                const partNum = parseFloat(domain.partNum) || 0;
                const partCost = parseFloat(domain.partCost) || 0;
                total += partNum * partCost;
            });   
            }else {
                this.dynamicValidateFormTwo.premiumListTwo.forEach((domain) => {
                const partNum = parseFloat(domain.partNum) || 0;
                const partCost = parseFloat(domain.partCost) || 0;
                total += partNum * partCost;
            });
            }
            this.totalPrice = total.toFixed(2);
        },



        // 处理数据，只保留前两级节点
        getTopTwoLevels(nodes, level = 1) {
            if (level > 2) return [];
            return nodes.map(node => {
                const newNode = { ...node };
                if (newNode.children) {
                    newNode.children = this.getTopTwoLevels(newNode.children, level + 1);
                }
                return newNode;
            });
        },

        //正则校验配件费用
        meneyIntegerValidator(rule, value, callback) {
            const reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
            if (value === '' || reg.test(value)) {
                callback()
            } else {
                callback(new Error('请输入大于0的数,最多2位小数'))
            }
        },
        //正则校验配件数量--维修数量
        numberIntegerValidator(rule, value, callback) {
            const reg = /^\+?[1-9][0-9]*$/
            // if ((value === '' || reg.test(value)) && value <= this.rowObj.repairNum) {
            //   callback()
            // } else {
            //   callback(new Error('请输入大于0的并且小于维修总量的正整数'))
            // }

            if (this.isRequired && (value === '' || !reg.test(value))) {
                callback(new Error('请输入大于0的正整数'))
            } else {
                callback()
            }
        },

        numberIntegerValidatorPart(rule, value, callback) {
            // 若值为空字符串，直接通过验证
            if (value === '') {
                callback();
                return;
            }
            const reg = /^(0|[1-9]\d*)$/; // 调整正则表达式，支持 0 和正整数
            if (reg.test(value)) {
                callback();
            } else {
                callback(new Error('请输入正整数或 0'));
            }
        },
        getTree() {
            listPartType().then((response) => {
                this.deptList = this.handleTree(response.data, 'paId')
            })
        },
        /** 转换部门数据结构 */
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children
            }
            return {
                id: node.paId,
                label: node.paName,
                children: node.children,
            }
        },
        getList() {
            let params = {
                taskId: this.taskId,
            }
            this.loading = true
            getRepairMaTypeListApi(params).then((res) => {
                if (res.code == 200) {
                    this.repairList = res.rows
                    this.total = res.total
                    this.loading = false
                }
            })
        },
       async init() {
          console.log('this.rowObj', this.rowObj)
          try {
            // 清空原有数据
            this.dynamicValidateForm.premiumList = []
            this.dynamicValidateFormTwo.premiumListTwo = []

            if (this.rowObj.submitStatus === 1 && this.rowObj.manageType ==1) {
              const res = await getSaveInfo({ typeId: this.rowObj.typeId,maId:this.rowObj.maId })
              this.dynamicValidateFormTwo.premiumListTwo = res.data.partList.map((item, index) => ({
                ...item,
                key: `${Date.now()}_${index}` // 生成唯一 key
              }))
              this.dynamicValidateFormTwo.premiumListTwo.forEach((domain, index) => {
                if (domain.partId) {
                  this.handleSelectTreeNum(domain.partId, index)
                }
              })
              if(res.data.partList.length==0){
                this.dynamicValidateFormTwo.premiumListTwo.push({repairer:res.data.repairer,updateTime:res.data.createTime,repairNum:res.data.repairNum})
              }
            }else if(this.rowObj.submitStatus === 1 && this.rowObj.manageType ==0){
              const res = await getSaveInfo({ typeId: this.rowObj.typeId,maId:this.rowObj.maId })
              this.dynamicValidateForm.premiumList = res.data.partList.map((item, index) => ({
                ...item,
                key: `${Date.now()}_${index}` // 生成唯一 key
              }))
              this.dynamicValidateForm.premiumList.forEach((domain, index) => {
                if (domain.partId) {
                  this.handleSelectTreeNum(domain.partId, index)
                }
              })
             if(res.data.partList.length==0){
                this.dynamicValidateForm.premiumList.push({repairer:res.data.repairer,updateTime:res.data.createTime,repairNum:res.data.repairNum})
              }

            }else {
              if (this.rowObj.manageType === 0) {
                this.addDomainOne()
              } else {
                this.addDomainTwo()
              }
              this.dynamicValidateForm.premiumList.forEach((item) => {
                    item.repairRemark = this.rowObj.repairRemark
                })
              this.dynamicValidateFormTwo.premiumListTwo.forEach((item) => {
                    item.repairRemark = this.rowObj.repairRemark
              })
              
            }


            // 获取用户信息和用户选择列表
            const userInfoRes = await getInfo()
            this.companyId = userInfoRes.user.companyId
            this.currentUserId = userInfoRes.user.userId

            const userSelectRes = await getUserSelectApi({ roleIds: [133] })
            this.userSelectList = userSelectRes.data
          } catch (error) {
            console.error('初始化出错:', error)
          }
        },
        // 取消按钮
        cancel() {
            this.dialogShowFlag = false
            // this.$refs["form"].resetFields();
            this.dynamicValidateForm.premiumList = [];
            this.dynamicValidateFormTwo.premiumListTwo = [];
        },
        addDomainOne() {
            const formatDate = (date) => {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            };
            // 检查 currentUserId 是否在 userSelectList 的 userId 中
            const isUserIdInList = this.userSelectList.some(user => user.userId === this.currentUserId);
            // 选择配件 partId
            // 是否收费 partType
            // 配件数量 partNum
            // 配件费用 partCost
            // 维修内容 repairContent
            // 维修数量 repairNum
            const newDomain = {
                selected: 'N',
                // partId: '',
                repairer: this.userSelectList.length > 0 && isUserIdInList ? this.currentUserId : '',  // 默认选择第一条数据
                partType: 0,
                partNum: '',
                partCost: '',
                repairContent: '',
                repairNum: 1,
                key: Date.now(),
                repairRemark: this.rowObj.repairRemark || '',
                fileList: [],
                partChange: '',
                partChangeNum: '',
                 updateTime: formatDate(new Date()),
            };
            this.dynamicValidateForm.premiumList.push(newDomain);
        },
        delDomain(domain, type) {
            if (type == 1) {
                this.dynamicValidateForm.premiumList = this.dynamicValidateForm.premiumList.filter(
                    (item) => item.key != domain.key,
                )
            } else {
                this.dynamicValidateFormTwo.premiumListTwo = this.dynamicValidateFormTwo.premiumListTwo.filter(
                    (item) => item.key != domain.key,
                )
            }
        },
        addDomainTwo() {
            const formatDate = (date) => {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            };

            // 检查 currentUserId 是否在 userSelectList 的 userId 中
            const isUserIdInList = this.userSelectList.some(user => user.userId === this.currentUserId);

            const newDomain = {
                selected: 'N',
                // partId: '',
                repairer: this.userSelectList.length > 0 && isUserIdInList ? this.currentUserId : '', // 默认选择第一条数据
                partType: 0,
                partNum: '',
                partCost: '',
                repairContent: '',
                repairNum: 1,
                key: Date.now(),
                repairRemark: this.rowObj.repairRemark || '',
                fileList: [],
                partChange: '',
                partChangeNum: '',
                 updateTime: formatDate(new Date()),
            };
            this.dynamicValidateFormTwo.premiumListTwo.push(newDomain);
        },
        submit() {
            this.$refs['dynamicValidateForm'].validate((valid) => {
                if (valid) {
                    // 编码管理传递参数
                    console.log('this.dynamicValidateForm.premiumList1111)', this.dynamicValidateForm.premiumList)
                    let params = {
                        maId: this.rowObj.maId,
                        typeId: this.rowObj.typeId,
                        id: this.rowObj.id,
                        repairType: 1,
                        companyId: this.companyId,
                        partStrList: JSON.stringify(this.dynamicValidateForm.premiumList),
                        manageType: 0,
                        repairNum: this.dynamicValidateForm.premiumList[0]?.repairNum ?? 1,
                        maId: this.rowObj.maId,
                    }
                    this.fullscreenLoading = true
                    submitRepairApplyApiNew(params)
                        .then((res) => {
                            if (res.code == 200) {
                                this.getList()
                                this.fullscreenLoading = false
                                this.dialogShowFlag = false
                                this.index = null
                                this.$message.success('操作成功!')
                                this.$emit('domainChangeTwo', res.code)
                            }
                        })
                        .catch(() => {
                            this.index = null
                            this.fullscreenLoading = false
                        })
                } else {
                    return false
                }
            })
        },

        save() {
            this.$refs['dynamicValidateForm'].validate((valid) => {
                if (valid) {
                    // 编码管理传递参数
                    console.log('this.dynamicValidateForm.premiumList1111)', this.dynamicValidateForm.premiumList)
                    let params = {
                        maId: this.rowObj.maId,
                        typeId: this.rowObj.typeId,
                        id: this.rowObj.id,
                        repairType: 1,
                        companyId: this.companyId,
                        partStrList: JSON.stringify(this.dynamicValidateForm.premiumList),
                        manageType: 0,
                        repairNum: this.dynamicValidateForm.premiumList[0]?.repairNum ?? 1,
                        maId: this.rowObj.maId,
                    }
                    this.fullscreenLoading = true
                    saveRepairApplyApiNew(params)
                        .then((res) => {
                            if (res.code == 200) {
                                this.getList()
                                this.fullscreenLoading = false
                                this.dialogShowFlag = false
                                this.index = null
                                this.$message.success('操作成功!')
                                this.$emit('domainChangeTwo', res.code)
                            }
                        })
                        .catch(() => {
                            this.index = null
                            this.fullscreenLoading = false
                        })
                } else {
                    return false
                }
            })
        },


        submitTwo() {
            this.$refs['dynamicValidateFormTwo'].validate((valid) => {
                if (valid) {
                    if(this.dynamicValidateFormTwo.premiumListTwo[0]?.repairNum > this.rowObj.repairNotFinishNum){
                        this.$message.error('维修数量不能大于待维修数量')
                        return
                    }
                    // 数量管理传递参数
                    let params = {
                        maId: this.rowObj.maId,
                        typeId: this.rowObj.typeId,
                        id: this.rowObj.id,
                        companyId: this.companyId,
                        repairType: 1,
                        partStrList: JSON.stringify(this.dynamicValidateFormTwo.premiumListTwo),
                        manageType: 1,
                        repairNum: this.dynamicValidateFormTwo.premiumListTwo[0]?.repairNum ?? 1,
                    }
                    this.fullscreenLoading = true
                    console.log("xxxxxxxxxxxxxxxxxxx",params)
                    submitRepairApplyApiNew(params)
                        .then((res) => {
                            if (res.code == 200) {
                                this.getList()
                                this.fullscreenLoading = false
                                this.dialogShowFlag = false
                                this.index = null
                                this.$message.success('操作成功!')
                                this.$emit('domainChange', res.code)
                            }
                        })
                        .catch(() => {
                            this.index = null
                            this.fullscreenLoading = false
                        })
                } else {
                    return false
                }
            })
        },
        //保存
        saveTwo() {
            this.$refs['dynamicValidateFormTwo'].validate((valid) => {
                if (valid) {
                    if(this.dynamicValidateFormTwo.premiumListTwo[0]?.repairNum > this.rowObj.repairNotFinishNum){
                        this.$message.error('维修数量不能大于待维修数量')
                        return
                    }
                    // 数量管理传递参数
                    let params = {
                        maId: this.rowObj.maId,
                        typeId: this.rowObj.typeId,
                        id: this.rowObj.id,
                        companyId: this.companyId,
                        repairType: 1,
                        partStrList: JSON.stringify(this.dynamicValidateFormTwo.premiumListTwo),
                        manageType: 1,
                        repairNum: this.dynamicValidateFormTwo.premiumListTwo[0]?.repairNum ?? 1,
                    }
                    this.fullscreenLoading = true
                    console.log("xxxxxxxxxxxxxxxxxxx",params)
                    saveRepairApplyApiNew(params)
                        .then((res) => {
                            if (res.code == 200) {
                                this.getList()
                                this.fullscreenLoading = false
                                this.dialogShowFlag = false
                                this.index = null
                                this.$message.success('操作成功!')
                                this.$emit('domainChange', res.code)
                            }
                        })
                        .catch(() => {
                            this.index = null
                            this.fullscreenLoading = false
                        })
                } else {
                    return false
                }
            })
        },

        async clearSave() {
            try {
                // 弹出确认对话框
                await this.$confirm('是否确认清除保存？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });

                // 用户确认后调用清除保存接口
                const params = {
                    maId: this.rowObj.maId,
                    typeId: this.rowObj.typeId,
                    id: this.rowObj.id
                };
                this.fullscreenLoading = true
                const res = await clearSaveApi(params);

                if (res.code === 200) {
                    
                    // 清除成功提示
                    this.$message.success('清除保存成功');
                    
                    this.fullscreenLoading = false
                    this.dialogShowFlag = false
                    this.$emit('domainChangeTwo', res.code)
                } else {
                    // 清除失败提示
                    this.fullscreenLoading = false
                    this.$message.error('清除保存失败，请稍后重试');
                    
                }
            } catch (error) {
                if (error !== 'cancel') {
                    // 接口调用出错提示
                    this.fullscreenLoading = false
                    this.$message.error('操作出错，请稍后重试');
                    
                }
            }
        },

        async clearSaveTwo() {
            try {
                // 弹出确认对话框
                await this.$confirm('是否确认清除保存？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });

                // 用户确认后调用清除保存接口
                const params = {
                    maId: this.rowObj.maId,
                    typeId: this.rowObj.typeId,
                    id: this.rowObj.id
                };
                this.fullscreenLoading = true
                const res = await clearSaveApi(params);

                if (res.code === 200) {
                    
                    // 清除成功提示
                    this.$message.success('清除保存成功');
                    this.fullscreenLoading = false
                    this.dialogShowFlag = false
                    this.$emit('domainChange', res.code)
                } else {
                    // 清除失败提示
                    this.fullscreenLoading = false
                    this.$message.error('清除保存失败，请稍后重试');
                    
                }
            } catch (error) {
                if (error !== 'cancel') {
                    // 接口调用出错提示
                    this.fullscreenLoading = false
                    this.$message.error('操作出错，请稍后重试');
                    
                }
            }
        },

        handleSelectTree(value, index) {
            if (value) {
                this.isRequired = true;
                // 查找选中配件的子级节点
                const selectedNode = this.findNode(this.deptList, value);
                if (selectedNode && selectedNode.children) {
                    // 提取子级节点的 buyPrice
                    const uniquePrices = new Set(
                        selectedNode.children
                            .map(child => child.buyPrice)
                            .filter(price => price !== undefined)
                            .map(price => parseFloat(price).toFixed(2))
                    );
                     this.dynamicValidateForm.premiumList[index].childPrices = Array.from(uniquePrices).sort((a, b) => a - b);
                } else {
                    this.dynamicValidateForm.premiumList[index].childPrices = [];
                }
            } else {
                this.$refs['dynamicValidateForm'].clearValidate();
                this.$refs['dynamicValidateFormTwo'].clearValidate();
                this.isRequired = false;
                this.dynamicValidateForm.premiumList[index].childPrices = [];
            }
        },

        handleSelectTreeNum(value, index) {
            if (value) {
                this.isRequired = true;
                // 查找选中配件的子级节点
                const selectedNode = this.findNode(this.deptList, value);
                if (selectedNode && selectedNode.children) {
                    // 提取子级节点的 buyPrice
                     const uniquePrices = new Set(
                        selectedNode.children
                            .map(child => child.buyPrice)
                            .filter(price => price !== undefined)
                            .map(price => parseFloat(price).toFixed(2))
                    );
                    this.dynamicValidateFormTwo.premiumListTwo[index].childPrices = Array.from(uniquePrices).sort((a, b) => a - b);
                } else {
                    this.dynamicValidateFormTwo.premiumListTwo[index].childPrices = [];
                }
            } else {
                this.$refs['dynamicValidateForm'].clearValidate();
                this.$refs['dynamicValidateFormTwo'].clearValidate();
                this.isRequired = false;
                this.dynamicValidateFormTwo.premiumListTwo[index].childPrices = [];
            }
        },

        // 递归查找节点
        findNode(nodes, id) {
            for (const node of nodes) {
                if (node.paId === id) {
                    return node;
                }
                if (node.children) {
                    const found = this.findNode(node.children, id);
                    if (found) {
                        return found;
                    }
                }
            }
            return null;
        },
        isPDF(file) {
            console.log('🚀 ~ isPDF ~ file:', file)
            console.log(file?.fileName && /\.(pdf)$/i.test(file.fileName))
            return file?.fileName && /\.(pdf)$/i.test(file.fileName);
        },
        isWord(file) {
            return file?.fileName && /\.(docx?|wps)$/i.test(file.fileName);
        },
        handleRemove(file, domain) {
            console.log('🚀 ~ handleRemove ~ file:', file)
            domain.fileList.splice(domain.fileList.indexOf(file), 1)
            console.log('🚀 ~ domain.fileList:', domain.fileList)
        },
        handlePreview(file) {
            console.log("ccccccccccccccccc",file)
            if (file.response) {
                window.open(file.response.data.fileUrl)
            } else {
                window.open(file.fileUrl)
            }
        },
        handleExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
                    files.length + fileList.length
                } 个文件`,
            )
        },
        beforeUpload(file) {
            const isLtMB = file.size / 1024 / 1024 < 20
            if (!isLtMB) {
                this.$message.error('上传文件大小不能超过 20MB!')
            }
            return isLtMB
        },
        handleSuccess(file, fileList, row) {
            console.log('🚀 ~ handleSuccess ~ row:', row)
            console.log('🚀 ~ handleSuccess ~ file:', file)
            if (!row.fileList) {
                row.fileList = []
            }
            row.fileList.push({
                fileName: file.response.data.fileName,
                fileUrl: process.env.VUE_APP_BASE_API + '/system'+ file.response.data.fileUrl,
            })
        },
        // // 获取配件总费用
        // async getPartCost(domain) {
        //     console.log('🚀 ~ getPartCost ~ domain:', domain)
        //     try {
        //         const params = {
        //             partId: domain.partId,
        //             partNum: domain.partNum,
        //         }
        //         const res = await getCostByPidAndNumApi(params)
        //         console.log('🚀 ~ getPartCost ~ res:', res)
        //         domain.partCost = res.data
        //     } catch (error) {
        //         console.log('🚀 ~ getPartCost ~ error:', error)
        //     }
        // },
    },
}
</script>
<style lang="scss" scoped>
.form_box_one {
    width: 100%;
    display: flex;
    flex-direction: column;

    .form_box_title {
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        font-size: 12px;
    }

    .form_box_line {
        margin: 8px 0;
        width: 100%;
        border-bottom: 2px solid #1a1c22;
    }

    .form_box_item {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

    .add_box {
        display: flex;
        justify-content: flex-end;
        margin-right: 3%;
    }
}

.form_box_two {
    display: flex;
    flex-direction: column;

    .form_box_title {
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        font-size: 12px;
    }

    .form_box_line {
        margin: 8px 0;
        width: 100%;
        border-bottom: 2px solid #1a1c22;
    }

    .form_box_item {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

    .add_box {
        display: flex;
        justify-content: flex-end;
        margin-right: 3%;
    }
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-right: 3%;
    margin-top: 10px;
}
</style>
