<template>
  <div class="app-container">
    <!-- 合并id -->
    <div style="margin-bottom: 20px">
      <el-button v-loading="isSubmit" type="primary" @click="submit">保存</el-button>
    </div>
    <el-row :gutter="20">
      <el-col :span="11" :offset="0">
        <el-form :model="queryParams" ref="queryForm" size="small" inline @submit.native.prevent>
          <el-form-item label="" prop="proName">
            <el-input
              v-model="queryParams.proName"
              placeholder="请输入工程名称"
              clearable
              @keyup.enter.native="handleQuery(1)"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="" prop="proCode">
            <el-input
              v-model="queryParams.proCode"
              placeholder="请输入工程编码"
              clearable
              @keyup.enter.native="handleQuery(1)"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="" prop="extendId">
            <el-input
              v-model="queryParams.extendId"
              placeholder="请输入皖送平台id"
              clearable
              @keyup.enter.native="handleQuery(1)"
              style="width: 240px"
            />
          </el-form-item>

          <!-- 表单按钮 -->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery(1)">查询</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset(1)">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table
          ref="table1"
          v-loading="isLoading"
          :data="tableList1"
          :highlight-current-row="false"
          :max-height="300"
          @selection-change="handleSelectChange1"
          style="width: 100%"
        >
          <!-- 多选 -->
          <el-table-column type="selection" width="55" align="center" :selectable="selectableTable" />
          <el-table-column
            type="index"
            width="55"
            label="序号"
            align="center"
            :index="index => (queryParams.pageNum - 1) * queryParams.pageSize + index + 1"
          />
          <el-table-column
            v-for="(column, index) in tableColumns"
            :show-overflow-tooltip="false"
            :key="index"
            :label="column.label"
            :prop="column.prop"
            align="center"
          ></el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getProList"
        />
      </el-col>

      <el-col :span="2" :offset="0" class="row-box">
        <div class="item-center">
          <div>
            <el-button
              type="primary"
              @click="handleAdd1"
              :disabled="selectedList1.length == 0"
              style="width: 70px; margin-bottom: 20px"
            >
              <i class="el-icon-arrow-right"></i>
            </el-button>
          </div>
          <div>
            <el-button type="primary" @click="handleDelete1" :disabled="selectedList2.length == 0" style="width: 70px">
              <i class="el-icon-arrow-left"></i>
            </el-button>
          </div>
        </div>
      </el-col>

      <el-col :span="11" :offset="0">
        <el-form :model="queryParams2" ref="queryForm2" size="small" inline @submit.native.prevent>
          <el-form-item label="" prop="proName">
            <el-input
              v-model="queryParams2.proName"
              placeholder="请输入工程名称"
              clearable
              @keyup.enter.native="handleQuery(2)"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="" prop="proCode">
            <el-input
              v-model="queryParams2.proCode"
              placeholder="请输入工程编码"
              clearable
              @keyup.enter.native="handleQuery(2)"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="" prop="extendId">
            <el-input
              v-model="queryParams2.extendId"
              placeholder="请输入皖送平台id"
              clearable
              @keyup.enter.native="handleQuery(2)"
              style="width: 240px"
            />
          </el-form-item>

          <!-- 表单按钮 -->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery(2)">查询</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset(2)">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table
          :data="searchResult2 !== null ? searchResult2 : tableList2"
          :highlight-current-row="false"
          :max-height="300"
          @selection-change="handleSelectChange2"
          style="width: 100%"
        >
          <!-- 多选 -->
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" width="55" label="序号" align="center" />
          <el-table-column
            v-for="(column, index) in tableColumns"
            :show-overflow-tooltip="false"
            :key="index"
            :label="column.label"
            :prop="column.prop"
            align="center"
          ></el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 保存id -->
    <el-row :gutter="20" style="margin-top: 30px">
      <el-col :span="11" :offset="0">
        <el-form :model="queryParams3" ref="queryForm3" size="small" inline @submit.native.prevent>
          <el-form-item label="" prop="proName">
            <el-input
              v-model="queryParams3.proName"
              placeholder="请输入工程名称"
              clearable
              @keyup.enter.native="handleQuery(3)"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="" prop="proCode">
            <el-input
              v-model="queryParams3.proCode"
              placeholder="请输入工程编码"
              clearable
              @keyup.enter.native="handleQuery(3)"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="" prop="extendId">
            <el-input
              v-model="queryParams3.extendId"
              placeholder="请输入皖送平台id"
              clearable
              @keyup.enter.native="handleQuery(3)"
              style="width: 240px"
            />
          </el-form-item>

          <!-- 表单按钮 -->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery(3)">查询</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset(3)">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table
          v-loading="isLoading"
          :data="searchResult3 !== null ? searchResult3 : tableList3"
          :highlight-current-row="false"
          :max-height="300"
          @selection-change="handleSelectChange3"
          style="width: 100%"
        >
          <!-- 多选 -->
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" width="55" label="序号" align="center" />
          <el-table-column
            v-for="(column, index) in tableColumns"
            :show-overflow-tooltip="false"
            :key="index"
            :label="column.label"
            :prop="column.prop"
            align="center"
          ></el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
          v-show="total3 > 0"
          :total="total3"
          :page.sync="queryParams3.pageNum"
          :limit.sync="queryParams3.pageSize"
          @pagination="getProList2"
        />
      </el-col>

      <el-col :span="2" :offset="0" class="row-box">
        <div class="item-center">
          <div>
            <el-button
              type="primary"
              @click="handleAdd2"
              :disabled="selectedList3.length == 0"
              style="width: 70px; margin-bottom: 20px"
            >
              <i class="el-icon-arrow-right"></i>
            </el-button>
          </div>
          <div>
            <el-button type="primary" @click="handleDelete2" :disabled="selectedList4.length == 0" style="width: 70px">
              <i class="el-icon-arrow-left"></i>
            </el-button>
          </div>
        </div>
      </el-col>

      <el-col :span="11" :offset="0">
        <el-form :model="queryParams4" ref="queryForm4" size="small" inline @submit.native.prevent>
          <el-form-item label="" prop="proName">
            <el-input
              v-model="queryParams4.proName"
              placeholder="请输入工程名称"
              clearable
              @keyup.enter.native="handleQuery(4)"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="" prop="proCode">
            <el-input
              v-model="queryParams4.proCode"
              placeholder="请输入工程编码"
              clearable
              @keyup.enter.native="handleQuery(4)"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="" prop="extendId">
            <el-input
              v-model="queryParams4.extendId"
              placeholder="请输入皖送平台id"
              clearable
              @keyup.enter.native="handleQuery(4)"
              style="width: 240px"
            />
          </el-form-item>

          <!-- 表单按钮 -->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery(4)">查询</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset(4)">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table
          :data="searchResult4 !== null ? searchResult4 : tableList4"
          :highlight-current-row="false"
          :max-height="300"
          @selection-change="handleSelectChange4"
          style="width: 100%"
        >
          <!-- 多选 -->
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" width="55" label="序号" align="center" />
          <el-table-column
            v-for="(column, index) in tableColumns"
            :show-overflow-tooltip="false"
            :key="index"
            :label="column.label"
            :prop="column.prop"
            align="center"
          ></el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getProListApi, combineProjectApi } from '@/api/basic/basic'

export default {
  data() {
    return {
      isLoading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        proName: '',
        proCode: '',
        extendId: ''
      },
      queryParams2: {
        proName: '',
        proCode: '',
        extendId: ''
      },
      queryParams3: {
        pageNum: 1,
        pageSize: 10,
        proName: '',
        proCode: '',
        extendId: ''
      },
      queryParams4: {
        proName: '',
        proCode: '',
        extendId: ''
      },
      tableColumns: [
        { label: '工程名称', prop: 'proName' },
        { label: '工程编码', prop: 'proCode' },
        { label: '工程id', prop: 'id' },
        { label: '皖送平台id', prop: 'extendId' }
      ],
      tableList1: [],
      tableList2: [],
      tableList3: [],
      tableList4: [],
      total: 0,
      total3: 0,
      selectedList1: [],
      selectedList2: [],
      selectedList3: [],
      selectedList4: [],

      // 查询结果（只在点击查询时更新）
      searchResult1: null,
      searchResult2: null,
      searchResult3: null,
      searchResult4: null,
      isSubmit: false
    }
  },
  created() {
    this.getProList()
    this.getProList2()
  },
  methods: {
    selectableTable(row) {
      // 如果 tableList2 非空，所有行禁用
      if (this.tableList2.length > 0) return false

      // 如果没有选中任何行，所有行可选
      if (this.selectedList1.length === 0) return true

      // 已经选中一行，只能继续选择这一行
      return this.selectedList1.includes(row)
    },

    // 通用过滤方法
    filterList(list, queryParams) {
      return list.filter(item => {
        const nameOk = !queryParams.proName || (item.proName || '').includes(queryParams.proName)
        const codeOk = !queryParams.proCode || (item.proCode || '').includes(queryParams.proCode)
        const extendIdOk = !queryParams.extendId || String(item.extendId || '').includes(queryParams.extendId)
        return nameOk && codeOk && extendIdOk
      })
    },
    handleQuery(type) {
      if (type === 1) {
        this.queryParams.pageNum = 1
        this.getProList()
      } else if (type === 2) {
        this.searchResult2 = this.filterList(this.tableList2, this.queryParams2)
      } else if (type === 3) {
        this.queryParams3.pageNum = 1
        this.getProList2()
      } else if (type === 4) {
        this.searchResult4 = this.filterList(this.tableList4, this.queryParams4)
      }
    },

    handleReset(type) {
      if (type === 1) {
        this.$refs.queryForm.resetFields()
        this.searchResult1 = null
        this.getProList()
      } else if (type === 2) {
        this.$refs.queryForm3.resetFields()
        this.searchResult2 = null
      } else if (type === 3) {
        this.$refs.queryForm3.resetFields()
        this.searchResult3 = null
        this.getProList2()
      } else if (type === 4) {
        this.$refs.queryForm4.resetFields()
        this.searchResult4 = null
      }
    },

    async getProList() {
      try {
        this.isLoading = true
        const res = await getProListApi(this.queryParams)
        console.log('🚀 ~ getProList ~ res:', res)
        this.tableList1 = res.rows || []
        this.total = res.total || 0
      } catch (error) {
        console.log('🚀 ~ getProList ~ error:', error)
      } finally {
        this.isLoading = false
      }
    },
    async getProList2() {
      try {
        this.isLoading = true
        const res = await getProListApi(this.queryParams3)
        console.log('🚀 ~ getProList ~ res:', res)
        this.tableList3 = res.rows || []
        this.total3 = res.total || 0
      } catch (error) {
        console.log('🚀 ~ getProList ~ error:', error)
      } finally {
        this.isLoading = false
      }
    },
    handleSelectChange1(e) {
      console.log('🚀 ~ handleSelectChange1 ~ e:', e)
      if (e.length > 1) {
        const first = e[0]
        this.$refs.table1.clearSelection()
        this.$refs.table1.toggleRowSelection(first, true)
        this.selectedList1 = [first]
        this.$message.warning('只能选择一个工程')
      } else {
        this.selectedList1 = e
      }
    },
    handleSelectChange2(e) {
      console.log('🚀 ~ handleSelectChange1 ~ e:', e)
      this.selectedList2 = e
    },
    handleSelectChange3(e) {
      console.log('🚀 ~ handleSelectChange1 ~ e:', e)
      this.selectedList3 = e
    },
    handleSelectChange4(e) {
      console.log('🚀 ~ handleSelectChange1 ~ e:', e)
      this.selectedList4 = e
    },
    handleAdd1() {
      this.tableList2.unshift(...this.selectedList1)
      this.tableList1 = this.tableList1.filter(item => !this.selectedList1.includes(item))
      if (this.searchResult1 !== null) {
        this.searchResult1 = this.searchResult1.filter(item => !this.selectedList1.includes(item))
      }
    },
    handleDelete1() {
      this.tableList1.unshift(...this.selectedList2)
      this.tableList2 = this.tableList2.filter(item => !this.selectedList2.includes(item))
      if (this.searchResult1 !== null) {
        this.searchResult1.unshift(...this.selectedList2)
      }
      if (this.searchResult2 !== null) {
        this.searchResult2 = this.searchResult2.filter(item => !this.selectedList2.includes(item))
      }
    },
    handleAdd2() {
      this.tableList4.unshift(...this.selectedList3)
      this.tableList3 = this.tableList3.filter(item => !this.selectedList3.includes(item))
      if (this.searchResult3 !== null) {
        this.searchResult3 = this.searchResult3.filter(item => !this.selectedList3.includes(item))
      }
    },
    handleDelete2() {
      this.tableList3.unshift(...this.selectedList4)
      this.tableList4 = this.tableList4.filter(item => !this.selectedList4.includes(item))
      if (this.searchResult3 !== null) {
        this.searchResult3.unshift(...this.selectedList4)
      }
      if (this.searchResult4 !== null) {
        this.searchResult4 = this.searchResult4.filter(item => !this.selectedList4.includes(item))
      }
    },
    submit() {
      if (this.tableList2.length == 0 || this.tableList4.length == 0) {
        this.$message.error('请选择要合并的工程！')
        return
      }
      // 弹框确认
      this.$confirm('是否确认提交？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const loading = this.$loading()
        try {
          if (this.isSubmit) return
          this.isSubmit = true
          const oldProIds = this.tableList4.map(item => item.id)
          console.log('🚀 ~ submit ~ oldProIds:', oldProIds)
          const newProId = this.tableList2[0].id
          console.log('🚀 ~ submit ~ newProId:', newProId)
          await combineProjectApi({ oldProIds, newProId })
          this.tableList1 = []
          this.tableList2 = []
          this.tableList3 = []
          this.tableList4 = []
          this.selectedList1 = []
          this.selectedList2 = []
          this.selectedList3 = []
          this.selectedList4 = []
          // 确定
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.getProList()
          this.getProList2()
        } catch (error) {
          console.log('🚀 ~ submit ~ error:', error)
        } finally {
          this.isSubmit = false
          loading.close()
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.row-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.item-center {
  align-items: center;
  display: flex;
  flex-direction: column;
  gap: 20px;
}
</style>
