<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="队伍名称" prop="teamName">
        <el-input
          v-model="queryParams.teamName"
          placeholder="请输入队伍名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属单位" prop="belongOrgName">
        <el-input
          v-model="queryParams.belongOrgName"
          placeholder="请输入所属单位"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="队伍类型" prop="teamType">
        <el-select v-model="queryParams.teamType" placeholder="队伍类型" clearable style="width: 240px">
          <el-option
            v-for="dict in dict.type.team_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单位类型" prop="belongOrgType">
        <el-select v-model="queryParams.belongOrgType" placeholder="请选择单位类型" clearable style="width: 240px">
          <el-option
            v-for="dict in dict.type.team_org_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="外部单位" prop="externalFlag">
        <el-select v-model="queryParams.externalFlag" placeholder="外部单位" clearable style="width: 240px">
          <el-option
            v-for="item in externalFlagOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="队伍状态" clearable style="width: 240px">
          <el-option
            v-for="dict in dict.type.team_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="驻扎点" prop="locationName">
        <el-input
          v-model="queryParams.locationName"
          placeholder="请输入驻扎点"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['resource:team:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['resource:team:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete()"
          v-hasPermi="['resource:team:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="teamList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="队伍名称" align="center" prop="teamName" :show-overflow-tooltip="true" />
      <el-table-column label="所属单位" align="center" prop="belongOrgName" :show-overflow-tooltip="true" />
      <el-table-column label="单位类型" align="center" prop="belongOrgType" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ belongOrgTypeLabel(scope.row.belongOrgType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="外部单位" align="center" prop="externalFlag">
        <template slot-scope="scope">
          <el-tag :type="externalFlagTagType(scope.row.externalFlag)">
            {{ externalFlagLabel(scope.row.externalFlag) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="队伍类型" align="center" prop="teamType" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ teamTypeLabel(scope.row.teamType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="statusTagType(scope.row.status)">
            {{ statusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="联系人" align="center" prop="contactPerson" :show-overflow-tooltip="true" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" width="120" />
      <el-table-column label="能力标签" align="center" min-width="160">
        <template slot-scope="scope">
          <template v-if="formatCapabilities(scope.row.capabilities).length">
            <el-tag
              v-for="tag in formatCapabilities(scope.row.capabilities)"
              :key="tag"
              size="mini"
              class="capability-tag"
            >
              {{ tag }}
            </el-tag>
          </template>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="驻扎点" align="center" prop="locationName" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['resource:team:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['resource:team:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-user"
            @click="handleMemberManage(scope.row)"
            v-hasPermi="['resource:team:member:list']"
          >成员</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改队伍对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="队伍名称" prop="teamName">
              <el-input v-model="form.teamName" placeholder="请输入队伍名称" maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属单位" prop="belongOrgName">
              <el-input v-model="form.belongOrgName" placeholder="请输入所属单位" maxlength="128" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位类型" prop="belongOrgType">
              <el-select v-model="form.belongOrgType" placeholder="请选择单位类型" clearable style="width: 100%">
                <el-option
                  v-for="dict in dict.type.team_org_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="队伍类型" prop="teamType">
              <el-select v-model="form.teamType" placeholder="请选择队伍类型" clearable style="width: 100%">
                <el-option
                  v-for="dict in dict.type.team_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.team_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="外部单位" prop="externalFlag">
              <el-select v-model="form.externalFlag" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in externalFlagOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="驻扎点" prop="locationName">
              <el-input
                v-model="form.locationName"
                placeholder="请选择驻扎点"
                readonly
              >
                <template slot="append">
                  <el-button type="primary" @click="openLocationPicker">地图选择</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="form.contactPerson" placeholder="请输入联系人" maxlength="64" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="能力标签" prop="capabilities">
              <el-select
                v-model="form.capabilities"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请输入能力标签"
                style="width: 100%"
              >
                <el-option
                  v-for="item in capabilityOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="联系地址" prop="contactAddress">
              <el-input v-model="form.contactAddress" type="textarea" placeholder="请输入联系地址" maxlength="255" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" maxlength="500" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 成员管理弹窗 -->
    <team-member-dialog
      :team-id="currentTeamId"
      :team-name="currentTeamName"
      :visible.sync="memberDialogVisible"
      @refresh="handleMemberRefresh"
    />

    <LocationPickerDialog
      :visible.sync="locationPickerVisible"
      :initial-location="{
        longitude: form.longitude,
        latitude: form.latitude,
        locationName: form.locationName
      }"
      @confirm="handleLocationConfirm"
    />
  </div>
</template>

<script>
import { listTeam, getTeam, delTeam, addTeam, updateTeam } from "@/api/resource/team"
import TeamMemberDialog from "./components/TeamMemberDialog.vue"
import LocationPickerDialog from "@/components/location/LocationPickerDialog.vue"

export default {
  name: "ResourceTeam",
  components: {
    TeamMemberDialog,
    LocationPickerDialog
  },
  dicts: ['team_status', 'team_type', 'team_org_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      teamNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 队伍表格数据
      teamList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 成员管理弹窗
      memberDialogVisible: false,
      currentTeamId: undefined,
      currentTeamName: '',
      locationPickerVisible: false,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      externalFlagOptions: [
        { label: '内部单位', value: 'N' },
        { label: '外部联动单位', value: 'Y' }
      ],
      // 能力标签选项（可选，用于预定义标签）
      capabilityOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        teamName: undefined,
        belongOrgName: undefined,
        belongOrgType: undefined,
        externalFlag: undefined,
        teamType: undefined,
        status: undefined,
        locationName: undefined
      },
      // 表单校验
      rules: {
        teamName: [
          { required: true, message: "队伍名称不能为空", trigger: "blur" },
          { min: 2, max: 100, message: '队伍名称长度必须介于 2 和 100 之间', trigger: 'blur' }
        ],
        belongOrgName: [
          { max: 128, message: '所属单位长度不能超过128个字符', trigger: 'blur' }
        ],
        belongOrgType: [
          { max: 32, message: '单位类型长度不能超过32个字符', trigger: 'blur' }
        ],
        externalFlag: [
          { required: true, message: '请选择是否外部单位', trigger: 'change' }
        ],
        contactPhone: [
          {
            validator: (rule, value, callback) => {
              if (value && !/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(value)) {
                callback(new Error("请输入正确的手机号码"))
              } else {
                callback()
              }
            },
            trigger: "blur"
          }
        ],
        locationName: [
          { max: 128, message: '驻扎点名称长度不能超过128个字符', trigger: 'blur' }
        ],
        capabilities: [
          {
            validator: (rule, value, callback) => {
              if (!value || !Array.isArray(value) || value.length === 0) {
                callback()
                return
              }
              // 检查JSON字符串长度（模拟保存时的格式）
              const jsonString = JSON.stringify(value)
              if (jsonString.length > 500) {
                callback(new Error('能力标签总长度不能超过500个字符'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        longitude: [
          {
            validator: (rule, value, callback) => {
              if (value === undefined || value === null || value === '') {
                callback()
                return
              }
              if (value < -180 || value > 180) {
                callback(new Error("经度范围应在-180到180之间"))
              } else {
                callback()
              }
            },
            trigger: "blur"
          }
        ],
        latitude: [
          {
            validator: (rule, value, callback) => {
              if (value === undefined || value === null || value === '') {
                callback()
                return
              }
              if (value < -90 || value > 90) {
                callback(new Error("纬度范围应在-90到90之间"))
              } else {
                callback()
              }
            },
            trigger: "blur"
          }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询队伍列表 */
    getList() {
      this.loading = true
      listTeam(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.teamList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        teamName: undefined,
        belongOrgName: undefined,
        belongOrgType: undefined,
        externalFlag: 'N',
        teamType: undefined,
        status: 'available',
        contactPerson: undefined,
        contactPhone: undefined,
        capabilities: [],
        contactAddress: undefined,
        locationName: undefined,
        longitude: undefined,
        latitude: undefined,
        remark: undefined
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.teamNames = selection.map(item => item.teamName)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加队伍"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      getTeam(id).then(response => {
        this.form = response.data
        // 确保状态有默认值
        if (!this.form.status) {
          this.form.status = 'available'
        }
        if (!this.form.externalFlag) {
          this.form.externalFlag = 'N'
        }
        // 解析能力标签JSON字符串为数组
        this.form.capabilities = this.safeJsonArray(this.form.capabilities)
        this.open = true
        this.title = "修改队伍"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 转换能力标签数组为JSON字符串
          const payload = {
            ...this.form,
            capabilities: Array.isArray(this.form.capabilities) && this.form.capabilities.length > 0
              ? JSON.stringify(this.form.capabilities)
              : null
          }
          if (this.form.id != undefined) {
            updateTeam(payload).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addTeam(payload).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let ids = this.ids
      let curNames = [];
      if (row) {
        ids = row.id || this.ids;
        curNames.push(row.teamName)
      } else if (this.teamNames.length > 0) {
        curNames.push(...this.teamNames)
      }
      const quotedNames = curNames.map(item => `“${item}”`);
      const resNames = quotedNames.join('、');
      this.$modal.confirm('是否确认删除队伍名称为' + resNames + '的数据项？').then(function() {
        return delTeam(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 成员管理按钮操作 */
    handleMemberManage(row) {
      this.currentTeamId = row.id
      this.currentTeamName = row.teamName
      this.memberDialogVisible = true
    },
    /** 成员管理刷新回调 */
    handleMemberRefresh() {
      // 刷新队伍列表以更新成员数量
      this.getList()
    },
    openLocationPicker() {
      this.locationPickerVisible = true
    },
    handleLocationConfirm({ lng, lat, address }) {
      const longitude = Number(lng)
      const latitude = Number(lat)
      if (!Number.isNaN(longitude)) {
        this.form.longitude = Number(longitude.toFixed(6))
      }
      if (!Number.isNaN(latitude)) {
        this.form.latitude = Number(latitude.toFixed(6))
      }
      if (!this.form.locationName) {
        this.form.locationName = address
      }
      this.locationPickerVisible = false
    },
    /** 状态标签类型 */
    statusTagType(status) {
      const map = {
        'available': 'success',
        'busy': 'warning',
        'offline': 'danger'
      }
      return map[status] || 'info'
    },
    /** 状态标签文本 */
    statusLabel(status) {
      const dict = this.dict.type.team_status.find(item => item.value === status)
      return dict ? dict.label : status
    },
    /** 队伍类型标签文本 */
    teamTypeLabel(teamType) {
      if (!teamType) return ''
      const dict = this.dict.type.team_type.find(item => item.value === teamType)
      return dict ? dict.label : teamType
    },
    /** 单位类型标签文本 */
    belongOrgTypeLabel(orgType) {
      if (!orgType) return ''
      const dict = this.dict.type.team_org_type.find(item => item.value === orgType)
      return dict ? dict.label : orgType
    },
    /** 外部单位标签文本 */
    externalFlagLabel(flag) {
      const map = {
        Y: '外部联动单位',
        N: '内部单位'
      }
      return map[flag] || '-'
    },
    /** 外部单位标签类型 */
    externalFlagTagType(flag) {
      const map = {
        Y: 'warning',
        N: 'success'
      }
      return map[flag] || 'info'
    },
    /** 解析能力标签 */
    formatCapabilities(capabilities) {
      if (!capabilities) {
        return []
      }
      try {
        const result = JSON.parse(capabilities)
        if (Array.isArray(result)) {
          return result.map(item => item && item.toString()).filter(Boolean)
        }
      } catch (e) {
        // ignore parse error
      }
      return capabilities
        .split(/[,，\s]+/)
        .map(item => item.trim())
        .filter(item => !!item)
    },
    /** 安全解析JSON数组 */
    safeJsonArray(val) {
      if (!val) return []
      try {
        const arr = JSON.parse(val)
        return Array.isArray(arr) ? arr : []
      } catch (e) {
        return []
      }
    }
  }
}
</script>

<style scoped>
.capability-tag {
  margin-right: 4px;
  margin-bottom: 4px;
}
</style>