<template>
  <div>
    <template v-if="!isMobile">
      <el-row>
        <el-col :span="24" class="searchStyle">
          <el-col :span="2" style="text-align: center">标题：</el-col>
          <el-col :span="7">
            <el-input
              v-model="subject"
              size="small"
              clearable
              placeholder="请输入标题"
              prefix-icon="el-icon-search"
            ></el-input>
          </el-col>
          <!-- <el-col :span="2" style="text-align: center">审批状态：</el-col>
          <el-col :span="7">
            <ht-select
              v-model="statusStr"
              :options="statusArray"
              :props="{ key: 'value', value: 'text' }"
              placeholder="请选择"
            ></ht-select>
          </el-col> -->

          <el-button
            style="margin-left: 20px"
            size="mini"
            icon="el-icon-refresh"
            @click="reset"
          >
            重置
          </el-button>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-search"
            @click="search"
          >
            搜索
          </el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-button size="mini" type="primary" @click="handleMultipleChoice">
            批量添加关联
          </el-button>
        </el-col>
      </el-row>
    </template>
    <div v-else class="mobile-search">
      <el-input
        v-model="subject"
        class="mobile-search_input"
        clearable
        placeholder="请输入流程标题"
        prefix-icon="el-icon-search"
      ></el-input>
      <el-button
        style="margin-left: 10px"
        size="mini"
        type="primary"
        icon="el-icon-search"
        @click="search"
      >
        查询
      </el-button>
      <el-button size="mini" icon="el-icon-refresh" @click="reset">
        重置
      </el-button>
    </div>

    <div class="record-content">
      <el-table
        ref="flowTable"
        v-loading="loading"
        :data="rows"
        style="width: 100%"
        stripe
        border
        header-cell-class-name="todo-header-row"
        row-class-name="todo-row"
        size="medium"
        :default-sort="{ prop: 'createTime', order: 'descending' }"
        :height="isMobile ? tableHeight : 450"
        @selection-change="handleChecked"
        @select="onTableSelect"
      >
        <el-table-column
          type="selection"
          width="60"
          align="center"
          sortable
        ></el-table-column>
        <el-table-column
          type="index"
          align="center"
          width="70"
          label="序号"
        ></el-table-column>
        <el-table-column prop="subject" label="标题" align="center">
          <template slot-scope="scope">
            <span
              class="subject"
              style="cursor: pointer; color: #409eff"
              @click.stop="handleRowClick(scope.row)"
            >
              {{ scope.row.subject }}
            </span>
          </template>
        </el-table-column>

        <el-table-column
          prop="creator"
          width="120"
          label="发起人"
          align="center"
        ></el-table-column>
        <el-table-column
          width="200"
          prop="createTime"
          label="发起时间"
          align="center"
          sortable
        ></el-table-column>
        <el-table-column
          width="100"
          prop="status"
          label="审批状态"
          align="center"
        >
          <template v-slot="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template v-slot="{ row, $index }">
            <el-button
              type="text"
              @click.stop="handleSingleChoice(row, $index)"
            >
              添加关联
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="relevant-flow_page" :class="isMobile ? 'mobile' : ''">
        <el-pagination
          :current-page="pagination.page"
          :page-sizes="[10, 20, 50, 100, 300, 500]"
          :page-size="pagination.pageSize"
          :layout="
            isMobile
              ? 'prev, pager, next'
              : 'total, sizes, prev, pager, next, jumper'
          "
          :total="total"
          :pager-count="5"
          :small="isMobile"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </div>

    <div
      slot="footer"
      class="dialog-footer"
      style="text-align: right; margin-top: 20px"
    >
      <el-button type="primary" size="small" @click="confirm">确 定</el-button>
      <el-button size="small" @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
  import mobileMode from '@/mixins/mobileMode.js'

  export default {
    name: 'RelevantFlowDialogContent',
    mixins: [mobileMode],
    props: {
      searchConfig: {
        type: Object,
        default: () => ({
          isPaging: true,
          pageSize: 10,
        }),
      },
      flowRangeKey: String,
      initialCheckBoxData: {
        type: Array,
        default: () => [],
      },
      initialDataTable: {
        type: Array,
        default: () => [],
      },
      // 新增：实例ID，用于过滤当前流程实例
      instId: {
        type: [String, Number],
        default: '',
      },
      statusStr: {
        type: String,
        default: 'end',
      },
      flowDefineDefKeyStr: {
        type: String,
        default: '',
      },
      flowTypeIdStr: {
        type: String,
        default: '',
      },
    },
    data() {
      return {
        // 弹窗自己的数据
        pagination: {
          page: 1,
          pageSize: 10,
        },
        rows: [],
        total: 0,
        loading: false,
        subject: '',
        checkBoxData: [],
        checkBoxDataAll: [],
        dataTable: [],
        statusArray: [
          {
            text: '待审批',
            value: 'running',
            valueArr: ['running', 'revoke', 'revokeToStart'],
            type: 'primary',
          },
          {
            text: '审批通过',
            value: 'end',
            valueArr: ['end', 'adminmanualend', 'manualend'],
            type: 'success',
          },
          {
            text: '审批驳回',
            value: 'back',
            valueArr: ['back', 'backToStart'],
            type: 'danger',
          },
          { text: '草稿', value: 'draft', valueArr: ['draft'], type: 'info' },
        ],
      }
    },
    computed: {
      tableHeight() {
        return window.innerHeight - 250
      },
    },
    watch: {
      tableLoading(newVal, oldVal) {
        console.log('RelevantFlowDialogContent: tableLoading 变化', {
          from: oldVal,
          to: newVal,
        })
      },
    },
    mounted() {
      console.log('RelevantFlowDialogContent mounted')
      this.initializeComponent()
    },
    activated() {
      // 如果使用了 keep-alive，在激活时也重新初始化
      console.log('RelevantFlowDialogContent activated')
      this.initializeComponent()
    },
    methods: {
      // 初始化组件
      initializeComponent() {
        console.log('初始化弹窗组件，传入的数据:', {
          initialCheckBoxData: this.initialCheckBoxData,
          initialDataTable: this.initialDataTable,
        })

        // 重置基本数据
        this.subject = ''
        this.statusStr = this.statusStr || 'end'
        this.rows = []
        this.total = 0
        this.loading = false
        this.pagination = {
          page: 1,
          pageSize: this.searchConfig.isPaging
            ? this.searchConfig.pageSize
            : 10,
        }

        // 初始化选择数据 - 关键部分
        this.checkBoxData = [...(this.initialCheckBoxData || [])]
        this.checkBoxDataAll = [...(this.initialCheckBoxData || [])]
        this.dataTable = [...(this.initialDataTable || [])]

        console.log('初始化后的选中数据:', {
          checkBoxData: this.checkBoxData,
          checkBoxDataAll: this.checkBoxDataAll,
          dataTable: this.dataTable,
        })

        // 加载初始数据
        this.loadData()

        this.$nextTick(() => {
          if (this.$refs.flowTable) {
            this.$refs.flowTable.doLayout()
          }
        })
      },

      // 加载数据的核心方法
      loadData(query) {
        this.loading = true
        const finalQuery = query || this.buildQuery()

        this.$requestConfig
          .getRelevantFlow(finalQuery)
          .then((data) => {
            this.rows = data.rows || []
            this.total = data.total || 0
            this.pagination = {
              page: data.page || 1,
              pageSize: data.pageSize || this.pagination.pageSize || 10,
              showTotal: true,
            }

            // 延迟执行选择检查
            setTimeout(() => {
              this.checkSelections()
            }, 100)
          })
          .finally(() => {
            this.loading = false
          })
      },

      // 构建查询条件
      buildQuery() {
        let querys = []
        let pageBean = { pageBean: this.pagination }
        // let NotEqualArray = [
        //   'manualend',
        //   'adminmanualend',
        //   'revokeToStart',
        //   'revoke',
        // ]
        // NotEqualArray.forEach((status) => {
        //   querys.push({
        //     property: 'STATUS_',
        //     value: status,
        //     group: 'main',
        //     operation: 'NOT_EQUAL',
        //     relation: 'AND',
        //   })
        // })

        if (this.subject) {
          querys.push({
            property: 'SUBJECT_',
            value: this.subject,
            group: 'main',
            operation: 'LIKE',
            relation: 'AND',
          })
        }
        if (this.instId) {
          querys.push({
            property: 'id_',
            value: this.instId || '',
            group: 'main',
            operation: 'NOT_EQUAL',
            relation: 'AND',
          })
        }
        const userId = this.$requestConfig.getUserId()
        if (userId) {
          querys.push({
            property: 'createBy',
            value: userId || '',
            group: 'main',
            operation: 'EQUAL',
            relation: 'AND',
          })
        }

        if (this.statusStr) {
          // 查找选中的状态配置
          const statusConfig = this.statusArray.find(
            (item) => item.value === this.statusStr
          )
          if (statusConfig && statusConfig.valueArr) {
            // 如果有多个状态值，使用 IN 操作符
            if (statusConfig.valueArr.length > 1) {
              querys.push({
                property: 'STATUS_',
                value: statusConfig.valueArr,
                group: 'main',
                operation: 'IN',
                relation: 'AND',
              })
            } else {
              // 单个状态值使用 EQUAL 操作符
              querys.push({
                property: 'STATUS_',
                value: statusConfig.valueArr[0],
                group: 'main',
                operation: 'EQUAL',
                relation: 'AND',
              })
            }
          }
        }

        if (this.flowDefineDefKeyStr && this.flowDefineDefKeyStr != '') {
          if (this.flowDefineDefKeyStr.indexOf(',') > 1) {
            querys.push({
              property: 'defKey',
              value: this.flowDefineDefKeyStr,
              group: 'main',
              operation: 'IN',
              relation: 'AND',
            })
          } else {
            querys.push({
              property: 'defKey',
              value: this.flowDefineDefKeyStr,
              group: 'main',
              operation: 'EQUAL',
              relation: 'AND',
            })
          }
        }
        if (this.flowTypeIdStr && this.flowTypeIdStr != '') {
          if (this.flowTypeIdStr.indexOf(',') > 1) {
            querys.push({
              property: 'typeId',
              value: this.flowTypeIdStr,
              group: 'main',
              operation: 'IN',
              relation: 'AND',
            })
          } else {
            querys.push({
              property: 'typeId',
              value: this.flowTypeIdStr,
              group: 'main',
              operation: 'EQUAL',
              relation: 'AND',
            })
          }
        }

        if (this.flowRangeKey) {
          querys.push({
            property: 'procDefKey',
            value: this.flowRangeKey,
            group: 'main',
            operation: 'IN',
            relation: 'AND',
          })
        }

        if (querys.length > 0) {
          if (this.searchConfig.isPaging) {
            return {
              pageBean: {
                page: this.pagination.page,
                pageSize: this.pagination.pageSize,
                showTotal: 'true',
              },
              querys,
            }
          } else {
            return { pageBean: {} }
          }
        } else {
          return pageBean
        }
      },

      // 检查选择状态
      checkSelections() {
        if (this.checkBoxDataAll && Array.isArray(this.checkBoxDataAll)) {
          this.checkBoxDataAll.forEach((row) => {
            let res = this.indexArray(this.rows, row)
            if (res !== -1) {
              this.$refs.flowTable.toggleRowSelection(this.rows[res], true)
            }
          })
        }
      },

      // 工具方法
      getStatusText(status) {
        const statusMap = {
          running: '待审批',
          end: '审批通过',
          back: '审批驳回',
          backToStart: '审批驳回',
          revoke: '已撤回',
          revokeToStart: '已撤回',
          manualend: '已撤回',
          adminmanualend: '已撤回',
          draft: '草稿',
        }
        return statusMap[status] || status || '-'
      },

      getStatusType(status) {
        const typeMap = {
          running: 'primary',
          end: 'success',
          back: 'danger',
          backToStart: 'danger',
          revoke: 'warning',
          revokeToStart: 'warning',
          manualend: 'warning',
          adminmanualend: 'warning',
          draft: 'info',
        }
        return typeMap[status] || 'info'
      },

      indexArray(array, item) {
        if (!Array.isArray(array) || !item || !item.id) {
          return -1
        }
        for (let i = 0; i < array.length; i++) {
          if (array[i].id === item.id) {
            return i
          }
        }
        return -1
      },

      search() {
        console.log('弹窗内搜索')
        this.pagination.page = 1
        this.loadData()
      },

      reset() {
        console.log('弹窗内重置')
        this.subject = ''
        this.statusStr = ''
        this.pagination.page = 1
        this.loadData()
      },
      handleMultipleChoice() {
        if (!this.checkBoxData.length) {
          this.$message.warning('请选择关联流程')
          return
        }
        this.confirmSelection()
      },

      handleSingleChoice(row, index) {
        this.confirmSelection(row, index, true)
      },

      confirmSelection(paramRow, paramIndex, isSingle) {
        const SYNC_FIELDS = ['id', 'subject', 'creator', 'createTime', 'status']

        if (isSingle) {
          const existIndex = this.indexArray(this.checkBoxDataAll, paramRow)
          if (existIndex === -1) {
            this.checkBoxDataAll.push(paramRow)
          } else {
            console.error('该流程已关联，无需重复添加')
          }
        } else {
          this.checkBoxData.forEach((row) => {
            let res = this.indexArray(this.checkBoxDataAll, row)
            if (res === -1) {
              this.checkBoxDataAll.push(row)
            }
          })
        }

        // 更新数据表
        this.dataTable = this.checkBoxDataAll

        // 准备同步数据
        const syncData = []
        this.dataTable.forEach((row) => {
          const obj = {}
          syncData.push(obj)
          SYNC_FIELDS.forEach((field) => {
            obj[field] = row[field]
          })
        })

        // 发送确认事件，传递选中的数据
        this.$emit('confirm', {
          dataTable: this.dataTable,
          syncData: syncData,
        })

        if (!this.isMobile) {
          this.$message.success('关联成功')
        }
      },

      handleChecked(value) {
        this.checkBoxData = value
      },

      onTableSelect(rows, row) {
        let selected = rows.length && rows.indexOf(row) !== -1
        if (!selected) {
          let res = this.indexArray(this.checkBoxDataAll, row)
          this.checkBoxDataAll.splice(res, 1)
          if (this.checkBoxDataAll.length == 0) {
            this.checkBoxData = []
          }
        }
      },

      RowClick(row) {
        this.$refs.flowTable.toggleRowSelection(row)
      },

      handleRowClick(row) {
        if (this.isMobile) {
          this.$root.$emit('click-relevant-flow', row)
        } else {
          this.$requestConfig.handleRelevantFlowClick(row)
        }
      },

      handleSizeChange(size) {
        this.pagination.pageSize = size
        this.loadData()
      },

      handleCurrentChange(currentPage) {
        // 保存当前页的选择
        if (this.checkBoxData && this.checkBoxData.length > 0) {
          this.checkBoxData.forEach((row) => {
            let res = this.indexArray(this.checkBoxDataAll, row)
            if (res == -1) {
              this.checkBoxDataAll.push(row)
            }
          })
        }

        this.pagination.page = currentPage
        this.loadData()
      },

      confirm() {
        // 直接确认当前选择的数据
        this.confirmSelection()
      },

      cancel() {
        this.$emit('cancel')
      },
    },
  }
</script>

<style lang="scss" scoped>
  .searchStyle {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 20px;
  }

  .subject {
    cursor: pointer;
    color: $base-color-blue;
  }

  .record-content {
    margin-top: 20px;
  }

  .relevant-flow_page {
    text-align: right;
    margin-top: 20px;
    &.mobile {
      text-align: center;
    }
  }

  .mobile-search {
    display: flex;
    align-items: center;
    padding-top: 20px;
    .mobile-search_input {
      flex: 1;
    }
  }
</style>
