<template>
    <div class="transfer-container">
        <!-- 左侧：目标指标库 -->
        <div class="transfer-column">
            <div class="ti">
                <h3>
                    目标指标库({{
                        currentLevel === "01"
                            ? "省局"
                            : currentLevel === "02"
                            ? "市州"
                            : currentLevel === "03"
                            ? "县级"
                            : "-"
                    }})
                </h3>
                <el-button type="primary" @click="handleAdd">添加</el-button>
            </div>

            <el-table
                v-bind="leftTableProps"
                ref="leftTableRef"
                @selection-change="handleLeftSelectionChange"
            >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="name" label="指标名称" />
                <el-table-column prop="expectValue" label="预期值">
                 <template #default="scope">
                      <!-- 预期值单位为数量\百分比 -->
                      <span v-if="scope.row.targetValueType === '1' || scope.row.targetValueType === '2'">
                        {{ scope.row.expectValue }}
                      </span>
                      <!-- 预期值单位为是否达标 -->
                      <span v-else-if="scope.row.targetValueType === '3'">
                        {{ scope.row.expectValue === 1 ? '达标' : '未达标' }}
                      </span>
                      <span v-else>{{ scope.row.expectValue }}</span>
                    </template>
                 </el-table-column>
                <el-table-column prop="unit" label="计量单位" />
            </el-table>

            <el-pagination
                v-if="leftTotal > 10"
                :page-size="10"
                :total="leftTotal"
                @size-change="handleLeftPageSizeChange"
                @current-change="handleLeftCurrentChange"
            />
        </div>

        <!-- 右侧：年度目标指标 -->
        <div class="transfer-column">
            <div class="ti">
                <h3>{{currentName}}年度目标指标</h3>
                <el-button type="danger" @click="handleDelete">删除</el-button>
            </div>
            <div
                v-if="showRedText && (currentLevel !== '100')"
                class="tips"
            >
                * 温馨提示：不可删除项（标红项）是<span>{{
                    upperDisplay
                }}</span
                >向您单位下发的年度目标指标，您的年度目标指标中需包含此内容，不可删除，请您根据本单位实际情况进行制定本单位其他年度目标指标
            </div>
            <el-table
                v-bind="rightTableProps"
                row-key="i"
                ref="rightTableRef"
                @selection-change="handleRightSelectionChange"
            >
                <el-table-column type="selection" width="55" :selectable="selectable">
                </el-table-column>
                <el-table-column prop="name" label="指标名称" >
                   <template #default="scope">
                      <span :class="{tips: scope.row.isFixed}">{{ scope.row.name }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="预期值">
                    <template #default="scope">
                        <!-- 预期值单位为数量 -->
                        <el-input-number
                            style="width: 100%"
                            v-if="scope.row.targetValueType === '1'"
                            v-model="scope.row.expectValue"
                            placeholder="请输入预期值"
                            size="small"
                            :disabled="scope.row.isFixed"
                            :controls="false"
                            :precision="0"
                            :min="0"
                        />
                        <!-- 预期值为百分比 -->
                        <el-input-number
                        style="width: 100%"
                            v-else-if="scope.row.targetValueType === '2'"
                            v-model="scope.row.expectValue"
                            placeholder="请输入预期值"
                            size="small"
                            :disabled="scope.row.isFixed"
                            :controls="false"
                            :precision="0"
                            :min="0"
                            :max="100"
                        />
                        <!-- 预期值为是否达标 -->
                        <el-select
                        style="width: 100%"
                            v-else-if="scope.row.targetValueType === '3'"
                            v-model="scope.row.expectValue"
                            placeholder="请选择预期值"
                            size="small"
                            :disabled="scope.row.isFixed"
                        >
                            <el-option label="达标" :value="1" />
                            <el-option label="未达标" :value="0" />
                        </el-select>
                        <!-- 如果有其他的，避免错误显示 -->
                        <!-- 预期值单位为数量 -->
                        <el-input-number
                        style="width: 100%"
                            v-else
                            v-model="scope.row.expectValue"
                            placeholder="请输入预期值"
                            size="small"
                            :disabled="scope.row.isFixed"
                            :controls="false"
                            :precision="0"
                            :min="0"
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="unit" label="计量单位">
                  <template #default="scope">
                      <span :class="{tips: scope.row.isFixed}">{{ scope.row.unit }}</span>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                v-if="rightTotal > 10"
                :page-size="10"
                :total="rightTotal"
                @size-change="handleRightPageSizeChange"
                @current-change="handleRightCurrentChange"
            />
        </div>
    </div>
</template>

<script setup>
    import { ref, computed, reactive, nextTick, onMounted, watch } from "vue"
    import { ElTable, ElPagination } from "element-plus"
import { add } from '@/utils/calc.js';
    const leftCurrent = ref(1)
    const rightCurrent = ref(1)
    const props = defineProps({
        transData: {
            type: Array,
            default: []
        },
        currentLevel: {
            type: String,
            default: ""
        },
        currentName: {
            type: String,
            default: ""
        },
        upperDisplay: {
            type: String,
            default: ""
        }
    })
    // 左侧原始数据（可操作）
    const leftData = ref([
        // {
        //     id: 1,
        //     name: "指标1",
        //     expectValue: 10,
        //     unit: "个",
        //     checked: false,
        //     isFixed: false
        // }
    ])
    // 是否显示右边的红字
    const showRedText = computed(() => {
        return rightData.value.some((item) => item.isFixed)
    })

    // 右侧默认固定数据（不可编辑、不可删除）
    const rightData = ref([])

    // 左侧分页参数
    const leftPagination = reactive({
        currentPage: 1,
        pageSize: 10
    })
    const leftTotal = computed(() => leftData.value.length)

    // 右侧分页参数
    const rightPagination = reactive({
        currentPage: 1,
        pageSize: 10
    })
    const rightTotal = computed(() => rightData.value.length)

    // 左侧表格数据（分页处理）
    const leftTableProps = computed(() => ({
        data: leftData.value.slice(
            (leftPagination.currentPage - 1) * leftPagination.pageSize,
            leftPagination.currentPage * leftPagination.pageSize
        ),
        border: true,
        style: "width: 100%; margin-top: 10px"
    }))

    // 右侧表格数据（分页处理）
    const rightTableProps = computed(() => ({
        data: rightData.value.slice(
            (rightPagination.currentPage - 1) * rightPagination.pageSize,
            rightPagination.currentPage * rightPagination.pageSize
        ),
        border: true,
        style: "width: 100%; margin-top: 10px"
    }))

    // 表格引用
    const leftTableRef = ref(null)
    const rightTableRef = ref(null)

    // 左侧选中项
    const leftSelected = ref([])
    const handleLeftSelectionChange = (rows) => {
        leftSelected.value = rows
    }
    const selectable = (row) => !row.isFixed
    // 右侧选中项
    const rightSelected = ref([])
    const handleRightSelectionChange = (rows) => {
        console.log(`output->rows`, rows)
        rightSelected.value = rows
        // rightSelected.value = rows.filter((row) => !row.isFixed)
        // console.log(`output->rightSelected.value`, rightSelected.value)
        // 更新数据中的checked状态
        // rightData.value.forEach((item) => {
        //     item.checked =
        //         rightSelected.value.some((row) => row.id === item.id) && !item.isFixed
        // })
    }

    // 处理行选择变更
    const handleRowCheck = (row, checked) => {
        // console.log(`output->勾选`, row, checked)
        // // 更新数据中的checked状态
        // row.checked = checked
        // // 同步表格选择状态
        // nextTick(() => {
        //     rightSelected.value = rightData.value.filter((item) => item.checked)
        // })
    }

    // 右侧全选处理
    // const handleRightSelectAll = (selection) => {
    //     const validRows = selection.filter((row) => !row.isFixed)
    //     const tempArr = validRows.map((row) => row.id)
    //     // 更新数据中的checked状态
    //     rightData.value.forEach((item) => {
    //         item.checked = tempArr.includes(item.id)
    //     })
    //     rightSelected.value = rightData.value.filter((item) => item.checked)
    // }

    // 添加操作
    const handleAdd = () => {
        if (leftSelected.value.length === 0) return

        const validSelected = leftSelected.value.filter((row) => !row.isFixed)

        leftData.value = leftData.value.filter(
            (item) => !validSelected.some((row) => row.id === item.id)
        )

        rightData.value.push(...validSelected.map((row) => ({ ...row, checked: false })))

        leftPagination.currentPage = 1
        leftTableRef.value?.clearSelection()
    }

    // 删除操作
    const handleDelete = () => {
        if (rightSelected.value.length === 0) return

        const deleteIds = rightSelected.value.map((row) => row.id)

        rightData.value = rightData.value.filter((item) => !deleteIds.includes(item.id))

        leftData.value.push(
            ...rightSelected.value.map((row) => ({ ...row, checked: false }))
        )

        rightPagination.currentPage = 1
        rightTableRef.value?.clearSelection()
    }

    // 分页事件（左侧）
    const handleLeftPageSizeChange = (size) => {
        leftPagination.pageSize = size
        leftPagination.currentPage = 1
    }

    const handleLeftCurrentChange = (page) => {
        leftPagination.currentPage = page
    }

    // 分页事件（右侧）
    const handleRightPageSizeChange = (size) => {
        rightPagination.pageSize = size
        rightPagination.currentPage = 1
    }

    const handleRightCurrentChange = (page) => {
        rightPagination.currentPage = page
    }

    // 初始化数据中的checked状态
    const initCheckedStatus = () => {
        const temp = props.transData.map((e, i) => {
            return {
                id: i,
                ids: e.id,
                name: e.targetName,
                targetType: e.targetType,
                expectValue: +e.targetValue,
                targetValueType: e.targetValueType,
                unit: e.targetMeasurementUnit,
                checked: false,
                isFixed: !e.canEdit
            }
        })
        leftData.value = []
        rightData.value = []
        temp.forEach((item, i) => {
            if (!item.ids && !item.isFixed) {
                leftData.value.push(item)
            } else {
                rightData.value.push(item)
            }
        })
        console.log(leftData.value, rightData.value)
    }

    // 组件挂载后初始化
    // onMounted(() => {
    //     initCheckedStatus()
    // })
    watch(
        () => props.transData,
        () => {
            initCheckedStatus()
        }
    )
    // 向组件外抛出变量
    defineExpose({
        leftData,
        rightData
    })
</script>

<style scoped>
    .transfer-container {
        color: #000;
        display: flex;
        gap: 20px;
        padding: 20px;
    }

    .transfer-column {
        flex: 1;
        border: 1px solid #ccc;
        padding: 15px;
    }

    .el-table {
        margin-top: 10px;
    }

    .el-pagination {
        margin-top: 15px;
    }

    .ti {
        display: flex;
        justify-content: space-between;
    }
    /* 红色提示 */
    .tips {
        color: red;
    }
    :deep(.el-input__inner){
      text-align: center;
    }
</style>
