<!-- 装备类型管理 -->
<template>
  <Container :query-form="queryForm" class="three-model-container">
    <!-- 查询表单 -->
    <template #query-form>
      <el-form-item label="装备型号名称">
        <el-input
          v-model="queryForm.modelName"
          placeholder="输入装备型号名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
    </template>

    <!-- 顶部操作 -->
    <template #header-actions>
      <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
      <el-button @click="resetQuery">重置</el-button>
      <el-button type="primary" icon="el-icon-plus" @click="openAdd">新建</el-button>
    </template>

    <!-- 表格 -->
    <div class="table-container">
      <el-table
        ref="table"
        :data="tableData"
        border
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"/>
        <!--<el-table-column type="index" label="序号" width="60"/>-->
        <el-table-column prop="zbTypeName" label="所属装备类型" width="120" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.zbTypeId }}</span>
            <!--<span v-if="zbTypeList.length > 0">{{ zbTypeList.find(item => Number(item.id) === row.zbTypeId).typeName }}</span>-->
            <!--<span v-else>-</span>-->
          </template>
        </el-table-column>
        <el-table-column prop="zbModelName" label="装备型号名称" align="center"/>
        <el-table-column prop="zbModelRemark" label="装备型号备注" align="center"/>
        <el-table-column prop="zbModelIcon" label="美军标图标" align="center">
          <template slot-scope="{row}">
            <vab-icon :icon="['fas', row.zbModelIcon]" />
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="创建人" width="120" align="center" sortable/>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center" sortable/>
        <el-table-column label="操作" fixed="right" align="center" width="220">
          <template slot-scope="{ row }">
            <div class="action-bar">
              <el-button size="small" plain icon="el-icon-edit" @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" icon="el-icon-delete" @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增装备弹窗 -->
    <el-dialog
      :title="addOrUpdateTitle"
      :visible.sync="addVisible"
      width="720px"
      :close-on-click-modal="false"
      class="model-dialog"
      @closed="onAddClosed"
    >
      <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="110px" size="small">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="所属装备类型" prop="zbTypeId">
              <el-select v-model="addForm.zbTypeId" placeholder="请选择所属装备类型">
                <el-option v-for="(item, index) in zbTypeList" :key="index" :label="item.zbTypeName"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="装备型号名称" prop="zbModelName">
              <el-input v-model="addForm.zbModelName" placeholder="请输入装备型号名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="美军标图标" prop="zbModelIcon">
              <!--<el-select v-model="addForm.zbModelIcon" placeholder="请输入装备型号名称">-->
              <!--  <el-option label="图标1" :value="1"></el-option>-->
              <!--</el-select>-->
              <el-input
                v-model="addForm.zbModelIcon"
                autocomplete="off"></el-input>
              <el-button type="primary" icon="el-icon-search"
                         class="input-btn-choose" @click="showIcon"></el-button>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="装备类型可编辑参数" prop="zbModelJson">
              <el-table :data="addForm.zbModelJson" border>
                <el-table-column prop="sourceName" label="业务名称">
                  <template slot-scope="scope">
                    <el-input
                      v-if="scope.row.isEditing"
                      v-model="scope.row.sourceName"
                    ></el-input>
                    <span v-else>{{ scope.row.sourceName }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="sourceCode" label="英文名称">
                  <template slot-scope="scope">
                    <el-input
                      v-if="scope.row.isEditing"
                      v-model="scope.row.sourceCode"
                    ></el-input>
                    <span v-else>{{ scope.row.sourceCode }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="sourceType" label="类型">
                  <template slot-scope="scope">
                    <el-select v-if="scope.row.isEditing" v-model="scope.row.sourceType">
                      <el-option
                        v-for="(item, index) in $getDictList('zb_filed_type')"
                        :key="index"
                        :label="item.dictName"
                        :value="item.dictValue"
                      ></el-option>
                    </el-select>
                    <span v-else>{{ scope.row.sourceType }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="160">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      @click="dialogEdit(scope.row)"
                      v-if="!scope.row.isEditing"
                    >编辑
                    </el-button>
                    <el-button
                      size="mini"
                      type="success"
                      @click="dialogSave(scope.row)"
                      v-if="scope.row.isEditing"
                    >确定
                    </el-button>
                    <el-button
                      size="mini"
                      type="danger"
                      @click="dialogCancle(scope.row)"
                      v-if="scope.row.isEditing"
                    >取消
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="装备型号备注" prop="zbModelRemark">
              <el-input v-model="addForm.zbModelRemark" type="textarea" :rows="4" placeholder="请输入装备型号备注"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addVisible=false">取 消</el-button>
        <el-button type="primary" @click="handleAddSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <icon
      v-on:icon="closeIcon"
      ref="icon"
    ></icon>

  </Container>
</template>

<script>
import {
  equModelList,
  equModelAdd,
  equModelUpdate,
  equModelDel,
  getEquModelDetails,
  getAllEquTypes
} from '@/api/equipment'
import Icon from "@/components/opsli/icon/icon";

export default {
  name: 'equipmentModel',
  components: {Icon},
  data() {
    return {
      addOrUpdateTitle: '新建',
      // 查询
      queryForm: {modelName: ''},

      // 列表&分页
      tableData: [],
      allData: [],
      selectedRows: [],
      pagination: {currentPage: 1, pageSize: 10, total: 0},

      // 新增弹窗
      addVisible: false,
      addForm: {
        id: '',
        zbTypeId: '',
        zbModelName: '',
        zbModelRemark: '',
        zbModelIcon: '',
        zbModelJson: [
          {
            sourceName: "",
            sourceCode: "",
            sourceType: "",
            isEditing: false
          }
        ],
      },
      addRules: {
        zbTypeId: [ { required: true, message: '装备类型ID不能为空', trigger: 'change' }],
        zbModelName: [
          { required: true, message: '装备型号名称不能为空', trigger: 'blur' },
          // { max: 50, message: '装备型号名称长度不能超过 50 个字符', trigger: 'blur' }
        ],
        zbModelRemark: [{ required: true, max: 200, message: '装备型号备注长度不能超过 200 个字符', trigger: 'blur' }],
        // zbModelIcon 验证：选填
        zbModelIcon: [],
        // zbModelJson 验证：自定义验证，确保数组至少有一条数据，且每条数据的 sourceName、sourceCode、sourceType 不为空
        zbModelJson: [
          {
            validator: (rule, value, callback) => {
              if (!value || value.length === 0) {
                callback(new Error('请至少添加一条可编辑参数'));
              } else {
                let hasError = false;
                value.forEach((item, index) => {
                  if (!item.sourceName) {
                    callback(new Error(`第 ${index + 1} 条参数的业务名称不能为空`));
                    hasError = true;
                    return false;
                  }
                  if (!item.sourceCode) {
                    callback(new Error(`第 ${index + 1} 条参数的英文名称不能为空`));
                    hasError = true;
                    return false;
                  }
                  if (!item.sourceType) {
                    callback(new Error(`第 ${index + 1} 条参数的类型不能为空`));
                    hasError = true;
                    return false;
                  }
                });
                if (!hasError) {
                  callback();
                }
              }
            },
            trigger: 'blur'
          }
        ]
      },
      zbTypeList: [], // 所有装备类型
    }
  },
  created() {
    this.handleQuery()
    this.getTypes()
  },
  methods: {
    showIcon() {
      this.$refs["icon"].showIcon();
    },
    // 选择完 icon 监听事件
    closeIcon(icon){
      this.addForm.zbModelIcon = icon;
    },
    dialogEdit(row) {
      row.isEditing = true
    },
    dialogSave(row) {
      row.isEditing = false
    },
    dialogCancle(row) {
      row.sourceName = ''
      row.sourceCode = ''
      row.sourceType = ''
      row.isEditing = false
    },
    // 获取所有装备类型
    getTypes() {
      getAllEquTypes().then(res => {
        if (res.code !== 0) {
          return
        }
        this.zbTypeList = res.data
      })
    },
    /* ====== 查询&分页 ====== */
    handleQuery() {
      let param = {
        pageNo: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
        ...this.queryForm
      }
      equModelList(param).then(res => {
        if (res.code !== 0) {
          return
        }
        this.tableData = res.data.records || []
        this.pagination.total = res.data.total
        console.log(res)
      }).catch(() => {
      })
    },
    resetQuery() {
      this.queryForm = {modelName: ''}
      this.pagination.currentPage = 1
      this.handleQuery()
    },
    handleSizeChange(size) {
      this.pagination.pageSize = size
      this.pagination.currentPage = 1
      this.handleQuery()
    },
    handleCurrentChange(p) {
      this.pagination.currentPage = p
      this.handleQuery()
    },

    /* ====== 表格操作 ====== */
    handleSelectionChange(val) {
      this.selectedRows = val
    },
    handleEdit(row) {
      this.addForm = {...row}
      this.addForm.zbTypeId = Number(row.zbTypeId)
      if (typeof row.zbModelJson != 'string') {
        this.addForm.zbModelJson = JSON.parse(row.zbModelJson)
      }
      // getEquDetails(row.id).then(res => {
      //   console.log(res)
      // })
      this.addOrUpdateTitle = '编辑'
      this.addVisible = true
    },
    handleDelete(row) {
      // this.allData = this.allData.filter(r => r.code !== row.code)
      equModelDel(row.id).then(res => {
        if (res.code !== 0) {
          return
        }
        this.$message.success('删除成功')
        this.handleQuery()
      }).catch(() => {
      })
    },

    /* ====== 新增或修改弹窗 ====== */
    openAdd() {
      this.addForm = {
        id: '',               // 主键（编辑时必填）
        zbTypeId: '',
        zbModelName: '',
        zbModelRemark: '',
        zbModelIcon: '',
        zbModelJson: [
          {
            sourceName: "",
            sourceCode: "",
            sourceType: "",
            isEditing: false
          }
        ],
      }
      this.addOrUpdateTitle = '新建'
      this.addVisible = true
      this.$nextTick(() => {
        this.$refs.addFormRef && this.$refs.addFormRef.clearValidate()
        this.$refs.uploader && this.$refs.uploader.clearFiles()
      })
    },
    onAddClosed() {
      this.$refs.addFormRef && this.$refs.addFormRef.resetFields()
    },
    handleAddSubmit() {
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return
        let data = this.addForm
        if (typeof data.zbModelJson != 'string') {
          data.zbModelJson = JSON.stringify(this.addForm.zbModelJson)
        }
        (this.addOrUpdateTitle === '编辑' ? equModelUpdate : equModelAdd)(data).then(res => {
          if (res.code !== 0) {
            return
          }
          this.$message({
            message: '操作成功',
            type: 'info',
            duration: 500,
            onClose: () => {
              this.pagination.currentPage = 1
              this.addVisible = false
              this.handleQuery()
            }
          })
        })
      })
    },
  },
}
</script>

<style>
/* 统一表格暗色风格，消除白色条纹和容器 */
.three-model-container .el-table,
.three-model-container .el-table__fixed,
.three-model-container .el-table__fixed-right {
  background: rgba(15, 31, 56, 0.86) !important;
}

.three-model-container .el-table__body-wrapper,
.three-model-container .el-table__fixed-body-wrapper {
  background: rgba(15, 31, 56, 0.86) !important;
}

.three-model-container .el-table td,
.three-model-container .el-table th.is-leaf {
  background: rgba(15, 31, 56, 0.86) !important;
  border-color: rgba(255, 255, 255, 0.08) !important;
  color: #e6efff;
}

.three-model-container .el-table th {
  background: rgba(30, 55, 95, 0.85) !important;
  color: #cfd9e6 !important;
}

.three-model-container .el-table--striped .el-table__body tr.el-table__row--striped td {
  background: rgba(15, 31, 56, 0.9) !important;
}

.three-model-container .el-table__body tr:hover > td {
  background: rgba(30, 64, 175, 0.25) !important;
}

.three-model-container .el-table__current-row > td {
  background: rgba(64, 150, 255, 0.2) !important;
}

.three-model-container .el-table__fixed::before,
.three-model-container .el-table__fixed-right::before,
.three-model-container .el-table::before {
  background-color: rgba(255, 255, 255, 0.08) !important;
}

.three-model-container .el-table__gutter,
.three-model-container .el-table__fixed-right .el-table__fixed-header-wrapper,
.three-model-container .el-table__fixed-right .el-table__fixed-body-wrapper,
.three-model-container .el-table__fixed .el-table__fixed-header-wrapper,
.three-model-container .el-table__fixed .el-table__fixed-body-wrapper {
  background: rgba(15, 31, 56, 0.86) !important;
}

.pagination-container {
  margin-top: 14px;
  display: flex;
  justify-content: flex-end;
}

.action-bar {
  display: flex;
  justify-content: space-around;
  width: 100%;
}

.model-dialog .el-dialog {
  background: #0b254a;
  border: 1px solid #364a64;
}

.model-dialog .el-dialog__title {
  color: #e6efff;
}

.model-dialog .el-dialog__header,
.model-dialog .el-dialog__footer {
  border-color: #364a64;
}

.model-dialog .el-upload-list__item {
  background: rgba(255, 255, 255, 0.04);
  border-color: #364a64;
  color: #e6efff;
}

.footer-tips {
  color: #94a3b8;
  margin-left: 10px;
}
</style>
