<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="位置类型" prop="positionType">
        <el-select v-model="queryParams.positionType" placeholder="请选择位置类型" @change="onPositionTypeChange" clearable style="width: 150px">
          <el-option
            v-for="dict in base_position_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="通道类型" prop="channelType">
        <el-select v-model="queryParams.channelType" placeholder="请选择通道类型" clearable style="width: 150px">
          <el-option
            v-for="dict in base_channel_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @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="Plus"
          @click="handleAdd"
          v-hasPermi="['system:position:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Sort"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="positionList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="编码" align="center" prop="code" />
      <el-table-column label="名称" align="center" prop="name" />
      <!-- <el-table-column label="层级" align="center" prop="level" /> -->
      <el-table-column label="显示顺序" align="center" prop="orderNum" />
      <el-table-column label="位置类型" align="center" prop="positionType">
        <template #default="scope">
          <dict-tag :options="base_position_type" :value="scope.row.positionType"/>
        </template>
      </el-table-column>
      <el-table-column label="通道类型" align="center" prop="channelType">
        <template #default="scope">
          <dict-tag :options="base_channel_type" :value="scope.row.channelType"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:position:edit']">修改</el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['system:position:add']">新增</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:position:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改位置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="positionRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="编码" prop="code" v-if="form.id">
          <el-input v-model="form.code" placeholder="请输入编码"  disabled/>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="上级位置" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="positionOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            value-key="id"
            placeholder="请选择上级位置"
            check-strictly
          />
        </el-form-item>
        <!-- <el-form-item label="层级" prop="level">
          <el-input v-model="form.level" placeholder="请输入层级" />
        </el-form-item> -->
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入显示顺序" />
        </el-form-item>
        <el-form-item label="位置类型" prop="positionType">
          <el-select v-model="form.positionType" placeholder="请选择位置类型" @change="onPositionTypeChange">
            <el-option
              v-for="dict in base_position_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="通道类型" prop="channelType" v-if="form.positionType === 'CHANNEL'">
          <el-select v-model="form.channelType" placeholder="请选择通道类型" >
            <el-option
              v-for="dict in base_channel_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="位置类型名称" prop="positionTypeDesc">
          <el-input v-model="form.positionTypeDesc" placeholder="请输入位置类型名称" />
        </el-form-item>
        <el-form-item label="通道类型名称" prop="channelTypeDesc">
          <el-input v-model="form.channelTypeDesc" placeholder="请输入通道类型名称" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Position">
import { listPosition, getPosition, delPosition, addPosition, updatePosition } from "@/api/system/position"

const { proxy } = getCurrentInstance()
const { base_position_type, base_channel_type } = proxy.useDict('base_position_type', 'base_channel_type')

const positionList = ref([])
const positionOptions = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const title = ref("")
const isExpandAll = ref(true)
const refreshTable = ref(true)

const data = reactive({
  form: {},
  queryParams: {
    name: null,
    level: null,
    orderNum: null,
    positionType: null,
    channelType: null,
    code: null,
    positionTypeDesc: null,
    channelTypeDesc: null
  },
  rules: {
    name: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    parentId: [
      { required: true, message: "上级位置不能为空", trigger: "blur" }
    ],
    ancestors: [
      { required: true, message: "祖级列表不能为空", trigger: "blur" }
    ],
    level: [
      { required: true, message: "层级不能为空", trigger: "blur" }
    ],
    orderNum: [
      { required: true, message: "显示顺序不能为空", trigger: "blur" }
    ],
    positionType: [
      { required: true, message: "位置类型不能为空", trigger: "change" }
    ],
    channelType: [
      { required: true, message: "通道类型不能为空", trigger: "change" }
    ],
    code: [
      { required: true, message: "编码不能为空", trigger: "blur" }
    ],
    positionTypeDesc: [
      { required: true, message: "位置类型名称不能为空", trigger: "blur" }
    ],
    channelTypeDesc: [
      { required: true, message: "通道类型名称不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询位置列表 */
function getList() {
  loading.value = true
  listPosition(queryParams.value).then(response => {
    positionList.value = proxy.handleTree(response.data, "id", "parentId")
    loading.value = false
  })
}

/** 查询位置下拉树结构 */
function getTreeselect() {
  listPosition().then(response => {
    positionOptions.value = []
    const data = { id: 0, name: '顶级节点', children: [] }
    data.children = proxy.handleTree(response.data, "id", "parentId")
    positionOptions.value.push(data)
  })
}
	
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    tenantId: null,
    revision: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    id: null,
    name: null,
    parentId: null,
    ancestors: null,
    level: null,
    orderNum: null,
    positionType: null,
    channelType: null,
    code: null,
    positionTypeDesc: null,
    channelTypeDesc: null
  }
  proxy.resetForm("positionRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset()
  getTreeselect()
  if (row != null && row.id) {
    form.value.parentId = row.id
  } else {
    form.value.parentId = 0
  }
  open.value = true
  title.value = "添加位置"
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset()
  await getTreeselect()
  if (row != null) {
    form.value.parentId = row.parentId
  }
  getPosition(row.id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改位置"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["positionRef"].validate(valid => {
    if (valid) {
      // 类型名称转换
      form.value.positionTypeDesc = base_position_type.value.find(item => item.value === form.value.positionType).label;
      if(form.value.channelType){
        form.value.channelTypeDesc = base_channel_type.value.find(item => item.value === form.value.channelType).label;
      }
      if (form.value.id != null) {
        updatePosition(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPosition(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

function onPositionTypeChange(val) {
  // 只要不是 CHANNEL，就清空通道类型
  if (val !== 'CHANNEL') {
    form.value.channelType = null
    form.value.channelTypeDesc = ''
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除数据项？').then(function() {
    return delPosition(row.id)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

getList()
</script>
