<template>
  <div class="mod-config">
    <!-- 查询表单 - rqrq -->
    <el-form :inline="true" label-position="top" style="margin-top: 1px; margin-left: 0px;">
      <el-form-item label="站点ID">
        <el-input v-model="queryData.searchStationId" style="width: 120px" placeholder="站点ID" clearable @keyup.enter.native="getDataList()"></el-input>
      </el-form-item>
      <el-form-item label="RCS站点编码">
        <el-input v-model="queryData.searchStationCode" style="width: 120px" placeholder="站点编码" clearable @keyup.enter.native="getDataList()"></el-input>
      </el-form-item>

      <el-form-item label="站点名称">
        <el-input v-model="queryData.searchStationName" style="width: 120px" placeholder="站点名称" clearable @keyup.enter.native="getDataList()"></el-input>
      </el-form-item>

      <el-form-item label=" ">
        <el-button type="primary" @click="getDataList()">查询</el-button>
        <el-button @click="resetQuery()">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 - rqrq -->
    <el-table
      :data="dataList"
      :height="height"
      border
      highlight-current-row
      v-loading="dataListLoading"
      style="width: 100%;">
      <el-table-column
        v-for="(item,index) in columnList" :key="index"
        :sortable="item.columnSortable"
        :prop="item.columnProp"
        :header-align="item.headerAlign"
        :show-overflow-tooltip="item.showOverflowTooltip"
        :align="item.align"
        :fixed="item.fixed==''?false:item.fixed"
        :min-width="item.columnWidth"
        :label="item.columnLabel">
        <template slot-scope="scope">
          <span v-if="item.columnProp === 'active'">
            <el-tag
              :type="scope.row.active === 'Y' ? 'success' : 'danger'"
              size="small">
              {{ scope.row.active === 'Y' ? '启用' : '禁用' }}
            </el-tag>
          </span>
          <span v-else-if="item.columnProp === 'autoCallBlankPallet'">
            {{ scope.row.autoCallBlankPallet === 'Y' ? '是' : '否' }}
          </span>
          <!-- 站点状态根据statusDb映射显示 - rqrq -->
          <span v-else-if="item.columnProp === 'statusDb'">
            <el-tag
              :type="getStatusType(scope.row.statusDb)"
              size="small">
              {{ getStatusText(scope.row.statusDb) }}
            </el-tag>
          </span>
          <span v-else>{{ scope.row[item.columnProp] }}</span>
        </template>
      </el-table-column>

      <!-- 操作列 - rqrq -->
      <el-table-column
        header-align="center"
        align="center"
        fixed="right"
        width="220"
        label="操作">
        <template slot-scope="scope">
          <a type="text" @click="correctStatus(scope.row)" v-if="!scope.row.correctLoading&&scope.row.stationCode!=='D1'&&scope.row.stationCode!=='D2'">纠正状态</a>
          <span v-if="scope.row.correctLoading" style="color: #999;">处理中...</span>
          <a type="text" @click="viewPallets(scope.row)" style="margin-left: 10px;" v-if="scope.row.stationCode!=='D1'&&scope.row.stationCode!=='D2'">查看栈板</a>
          <a type="text" @click="openAutoCallSetting(scope.row)" style="margin-left: 10px;" v-if="scope.row.stationCode!=='D1'&&scope.row.stationCode!=='D2'
&&scope.row.stationCode!=='R1'&&scope.row.stationCode!=='R2'&&scope.row.stationCode!=='R3'&&scope.row.stationCode!=='R4'
&&scope.row.stationCode!=='J1'&&scope.row.stationCode!=='J2'&&scope.row.stationCode!=='J3'&&scope.row.stationCode!=='J4'">续盘设置</a>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 - rqrq -->
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[20, 50, 100, 1000]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <!-- 查看栈板弹窗 - rqrq -->
    <el-dialog
      :title="'站点【' + currentStation.stationCode + '】栈板列表'"
      :visible.sync="palletDialogVisible"
      :close-on-click-modal="false"
      v-drag
      width="700px">

      <el-table
        :data="palletList"
        height="300"
        border
        v-loading="palletLoading"
        style="width: 100%;">
        <el-table-column
          prop="palletId"
          header-align="center"
          align="center"
          label="栈板编码"
          min-width="150">
        </el-table-column>
        <el-table-column
          prop="callingFlag"
          header-align="center"
          align="center"
          label="是否调用"
          width="100">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.callingFlag === 'Y' ? 'warning' : 'info'"
              size="small">
              {{ scope.row.callingFlag === 'Y' ? '调用中' : '未调用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="palletType"
          header-align="center"
          align="center"
          label="托盘类型"
          width="100">
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          label="操作"
          width="100">
          <template slot-scope="scope">
            <a type="text" style="color: #F56C6C;" @click="removePallet(scope.row)" v-if="!scope.row.removeLoading">手工移出</a>
            <span v-if="scope.row.removeLoading" style="color: #999;">移出中...</span>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="palletDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 续盘设置弹窗 - rqrq -->
    <el-dialog
      :title="'站点【' + currentStation.stationCode + '】续盘设置'"
      :visible.sync="autoCallDialogVisible"
      :close-on-click-modal="false"
      v-drag
      width="400px">
      <el-form :model="autoCallForm" label-position="top" style="margin-top: 1px; margin-left: 0px;">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="是否续盘">
              <el-select v-model="autoCallForm.autoCallBlankPallet" placeholder="请选择" style="width: 100%">
                <el-option label="是" value="Y"></el-option>
                <el-option label="否" value="N"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="续什么盘">
              <el-select v-model="autoCallForm.autoCallBlankPalletType" placeholder="请选择托盘类型" style="width: 100%" clearable>
                <el-option
                  v-for="item in palletTypeOptions"
                  :key="item.palletType"
                  :label="item.typeDesc"
                  :value="item.palletType">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveAutoCallSetting" :disabled="saveAutoCallLoading">
          {{ saveAutoCallLoading ? '保存中...' : '确定' }}
        </el-button>
        <el-button @click="autoCallDialogVisible = false" :disabled="saveAutoCallLoading">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAgvStationList,
  correctAgvStationStatus,
  getPalletsByStation,
  removePalletFromStation,
  getPalletTypeOptions,
  updateAutoCallSetting
} from '@/api/wcsSystem/agvStationSpecialAction.js'

export default {
  data() {
    return {
      // 查询条件 - rqrq
      queryData: {
        searchStationCode: '',
        searchStationName: '',
        searchStationId: '',
        stationType: '正式站点',
        active: 'Y',
        page: 1,
        limit: 20
      },
      // 表格高度 - rqrq
      height: 450,
      // 表格列配置 - rqrq
      columnList: [
        {
          columnProp: "stationCode",
          headerAlign: "center",
          align: "center",
          columnLabel: "站点编码",
          columnWidth: 120,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "stationName",
          headerAlign: "center",
          align: "center",
          columnLabel: "站点名称",
          columnWidth: 120,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "areaType",
          headerAlign: "center",
          align: "center",
          columnLabel: "区域类型",
          columnWidth: 100,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "stationArea",
          headerAlign: "center",
          align: "center",
          columnLabel: "站点区域",
          columnWidth: 120,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "statusDb",
          headerAlign: "center",
          align: "center",
          columnLabel: "站点状态",
          columnWidth: 100,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "autoCallBlankPallet",
          headerAlign: "center",
          align: "center",
          columnLabel: "自动续盘",
          columnWidth: 80,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "autoCallBlankPalletTypeDesc",
          headerAlign: "center",
          align: "center",
          columnLabel: "续盘类型",
          columnWidth: 100,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "stationType",
          headerAlign: "center",
          align: "center",
          columnLabel: "站点类型",
          columnWidth: 100,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "warehouseCode",
          headerAlign: "center",
          align: "center",
          columnLabel: "仓库编码",
          columnWidth: 100,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "locationCode",
          headerAlign: "center",
          align: "center",
          columnLabel: "库位编码",
          columnWidth: 120,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "remark",
          headerAlign: "center",
          align: "left",
          columnLabel: "备注",
          columnWidth: 200,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        }
      ],
      // 数据列表 - rqrq
      dataList: [],
      // 分页参数 - rqrq
      pageIndex: 1,
      pageSize: 20,
      totalPage: 0,
      dataListLoading: false,
      // 栈板弹窗相关 - rqrq
      palletDialogVisible: false,
      palletLoading: false,
      palletList: [],
      currentStation: {},
      // 续盘设置弹窗相关 - rqrq
      autoCallDialogVisible: false,
      saveAutoCallLoading: false,
      autoCallForm: {
        autoCallBlankPallet: '',
        autoCallBlankPalletType: ''
      },
      palletTypeOptions: []
    }
  },
  mounted() {
    this.$nextTick(() => {
      // 计算表格高度 - rqrq
      this.height = window.innerHeight - 220;
    })
  },
  activated() {
    this.getDataList()
  },
  methods: {
    // 获取数据列表 - rqrq
    getDataList() {
      this.dataListLoading = true
      this.queryData.page = this.pageIndex
      this.queryData.limit = this.pageSize

      getAgvStationList(this.queryData).then(({data}) => {
        this.dataListLoading = false
        if (data && data.code === 0) {
          // 给每条数据添加loading状态 - rqrq
          let list = data.page.list || []
          list.forEach(item => {
            item.correctLoading = false
          })
          this.dataList = list
          this.totalPage = data.page.totalCount || 0
        } else {
          this.dataList = []
          this.totalPage = 0
          this.$alert(data.msg || '查询失败', '错误', { confirmButtonText: '确定' })
        }
      }).catch(error => {
        this.dataListLoading = false
        console.error('查询AGV站点列表失败:', error)
        this.$alert('查询失败', '错误', { confirmButtonText: '确定' })
      })
    },

    // 重置查询条件 - rqrq
    resetQuery() {
      this.queryData = {
        searchStationCode: '',
        searchStationName: '',
        searchStationId: '',
        stationType: '正式站点',
        active: 'Y',
        page: 1,
        limit: 20
      }
      this.pageIndex = 1
      this.getDataList()
    },

    // 每页数量变化 - rqrq
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },

    // 当前页变化 - rqrq
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },

    // 纠正站点状态 - rqrq
    correctStatus(row) {
      this.$confirm('确定要纠正站点【' + row.stationCode + '】的状态吗？系统将根据栈板实际情况更新站点状态。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.correctLoading = true

        correctAgvStationStatus({
          stationId: row.stationId,
          stationCode: row.stationCode
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message.success(data.msg || '纠正成功')
            this.getDataList()
          } else {
            this.$alert(data.msg || '纠正失败', '错误')
          }
        }).catch(error => {
          console.error('纠正站点状态失败:', error)
          this.$alert('纠正失败', '错误', { confirmButtonText: '确定' })
        }).finally(() => {
          row.correctLoading = false
        })
      }).catch(() => {
        // 取消操作
      })
    },

    // 查看栈板 - rqrq
    viewPallets(row) {
      this.currentStation = row
      this.palletDialogVisible = true
      this.loadPalletList()
    },

    // 加载栈板列表 - rqrq
    loadPalletList() {
      this.palletLoading = true
      this.palletList = []

      getPalletsByStation({
        stationCode: this.currentStation.stationCode
      }).then(({data}) => {
        if (data && data.code === 0) {
          // 给每条数据添加loading状态 - rqrq
          let list = data.rows || []
          list.forEach(item => {
            item.removeLoading = false
          })
          this.palletList = list
        } else {
          this.palletList = []
          this.$alert(data.msg || '查询栈板失败', '错误', { confirmButtonText: '确定' })
        }
      }).catch(error => {
        console.error('查询站点栈板失败:', error)
        this.$alert('查询栈板失败', '错误', { confirmButtonText: '确定' })
      }).finally(() => {
        this.palletLoading = false
      })
    },

    // 手工移出栈板 - rqrq
    removePallet(row) {
      this.$confirm('确定要将栈板【' + row.palletId + '】从站点移出吗？移出后该栈板将不再关联任何站点。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.removeLoading = true

        removePalletFromStation({
          palletId: row.palletId,
          stationCode: this.currentStation.stationCode
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message.success(data.msg || '移出成功')
            // 刷新栈板列表 - rqrq
            this.loadPalletList()
            // 刷新站点列表 - rqrq
            this.getDataList()
          } else {
            this.$alert(data.msg || '移出失败', '错误')
          }
        }).catch(error => {
          console.error('移出栈板失败:', error)
          this.$alert('移出失败', '错误', { confirmButtonText: '确定' })
        }).finally(() => {
          row.removeLoading = false
        })
      }).catch(() => {
        // 取消操作
      })
    },

    // 打开续盘设置弹窗 - rqrq
    openAutoCallSetting(row) {
      this.currentStation = row
      this.autoCallForm = {
        autoCallBlankPallet: row.autoCallBlankPallet || 'N',
        autoCallBlankPalletType: row.autoCallBlankPalletType || ''
      }
      this.autoCallDialogVisible = true
      this.loadPalletTypeOptions()
    },

    // 加载托盘类型选项 - rqrq
    loadPalletTypeOptions() {
      getPalletTypeOptions({}).then(({data}) => {
        if (data && data.code === 0) {
          this.palletTypeOptions = data.rows || []
        } else {
          this.palletTypeOptions = []
        }
      }).catch(error => {
        console.error('获取托盘类型选项失败:', error)
        this.palletTypeOptions = []
      })
    },

    // 获取站点状态文本 - rqrq
    getStatusText(statusDb) {
      const statusMap = {
        0: '空闲',
        1: '有货',
        2: '待放货',
        3: '待取货'
      }
      return statusMap[statusDb] !== undefined ? statusMap[statusDb] : '未知'
    },

    // 获取站点状态标签类型 - rqrq
    getStatusType(statusDb) {
      const typeMap = {
        0: 'success',   // 空闲 - 绿色
        1: 'warning',   // 有货 - 橙色
        2: 'primary',   // 待放货 - 蓝色
        3: 'danger'     // 待取货 - 红色
      }
      return typeMap[statusDb] !== undefined ? typeMap[statusDb] : 'info'
    },

    // 保存续盘设置 - rqrq
    saveAutoCallSetting() {
      this.saveAutoCallLoading = true

      updateAutoCallSetting({
        stationCode: this.currentStation.stationCode,
        autoCallBlankPallet: this.autoCallForm.autoCallBlankPallet,
        autoCallBlankPalletType: this.autoCallForm.autoCallBlankPalletType
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.$message.success('保存成功')
          this.autoCallDialogVisible = false
          this.getDataList()
        } else {
          this.$alert(data.msg || '保存失败', '错误')
        }
      }).catch(error => {
        console.error('保存续盘设置失败:', error)
        this.$alert('保存失败', '错误', { confirmButtonText: '确定' })
      }).finally(() => {
        this.saveAutoCallLoading = false
      })
    }
  }
}
</script>

<style scoped>
/* 表格样式优化 - rqrq */
.mod-config {
  padding: 10px;
}
</style>
