<!-- 部门管理 -->
<template>
  <basic-container>
    <el-form>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="部门名称">
            <el-input v-model="searchList.deptName" placeholder="请输入部门名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" :icon="Search" @click="getList">查询</el-button>
          <el-button type="primary" :icon="Plus" @click="addOrUpdateHandle(false)">新增</el-button>
        </el-col>
      </el-row>
    </el-form>
    <div>
      <el-table v-loading="tableLoading" border :data="tableData" row-key="id" :expand-row-keys="['9']">
        <el-table-column prop="name" label="部门名称" :show-overflow-tooltip="true" />
        <el-table-column prop="abbreviationName" label="部门简称" align="center" />
        <el-table-column prop="deptType" label="部门类型" align="center">
          <template #default="{ row }">
            {{ getValueLabel(dept_type, row.deptType) }}
          </template>
        </el-table-column>
        <el-table-column prop="warehouseType" label="仓库类型" align="center">
          <template #default="{ row }">
            {{ getValueListLabel(warehouse_type, row.warehouseType) }}
          </template>
        </el-table-column>
        <el-table-column prop="delFlag" label="状态" align="center">
          <template #default="{ row }">
            {{ getValueLabel(del_type, row.delFlag) }}
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="排序" align="center" />
        <el-table-column prop="createTime" label="创建时间" align="center">
          <template #default="{ row }">
            {{ timestampToTime(+row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center" class-name="small-padding fixed-width">
          <template #default="{ row }">
            <div class="table_btn">
              <el-button size="small" :icon="Plus" @click="addOrUpdateHandle(false, row.id)"> 新增 </el-button>
              <el-button size="small" :icon="Edit" @click="addOrUpdateHandle(true, row.id)">编辑</el-button>
              <el-button size="small" :icon="Delete" @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- <pagination
        v-show="tablePage.total > 0"
        v-model:page="tablePage.currentPage"
        v-model:limit="tablePage.pageSize"
        :total="tablePage.total"
        @pagination="getList"
      /> -->

      <el-dialog v-model="dialogVisible" :title="title" width="50%" :before-close="dialogClose">
        <el-form :model="form" ref="formRef" :rules="formRules" label-width="80px" class="whole_form">
          <el-row>
            <el-col :span="8">
              <el-form-item label="上级部门" prop="parentId">
                <el-tree-select
                  placeholder="选择上级部门"
                  v-model="form.parentId"
                  :data="deptOptions"
                  check-strictly
                  :render-after-expand="false"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="法人信息">
                <el-input v-model="form.legalPerson" placeholder="请输入负责人" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话">
                <el-input v-model="form.deptPhone" placeholder="请输入联系电话" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="部门名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入部门名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门简称" prop="abbreviationName">
                <el-input v-model="form.abbreviationName" placeholder="请输入部门简称" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="部门类型" prop="deptType">
                <el-select v-model="form.deptType" clearable @change="deptTypeChange">
                  <el-option v-for="item in dept_type" :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="地址">
                <el-cascader
                  clearable
                  v-model="form.deptMergeAddress"
                  placeholder="请选择"
                  :options="addressOption"
                  :props="{ value: 'code', label: 'name' }"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="详细地址">
                <el-input v-model="form.deptAddress" placeholder="请输入详细地址" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="经度" prop="longitude">
                <el-input v-model="form.longitude" placeholder="请输入部门经度" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="维度" prop="dimension">
                <el-input v-model="form.dimension" placeholder="请输入部门维度" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="仓库类型" prop="warehouseType">
                <el-select v-model="form.warehouseType" clearable multiple>
                  <el-option v-for="item in warehouse_type" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <!--
          <el-row>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="邮箱">
                <el-input v-model="form.roleDesc" placeholder="请输入角色描述" clearable />
              </el-form-item>
            </el-col>
          </el-row> -->
          <!-- <el-row>
            <el-col :span="8">
              <el-form-item label="状态">
                <el-input v-model="form.createTime" />
              </el-form-item>
            </el-col>
          </el-row> -->
          <el-row>
            <el-col :span="8">
              <el-form-item label="显示排序" prop="sortOrder">
                <el-input-number v-model="form.sortOrder" controls-position="right" :min="0" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <uploadFile title="库区图" v-model:fileList="form.fileList" />
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-row class="btn_center">
            <el-button v-if="title === '新增'" type="primary" @click="addDept">新 增</el-button>
            <el-button v-if="title === '修改'" type="primary" @click="saveDept">保 存</el-button>
            <el-button @click="dialogVisible = false">取 消</el-button>
          </el-row>
        </template>
      </el-dialog>
    </div>
  </basic-container>
</template>

<script setup lang="ts">
import uploadFile from "@/components/uploadFile/index.vue";

import { nextTick, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { Search, EditPen, Plus, Edit, Delete } from "@element-plus/icons-vue";

import { useDict } from "@/hooks/dict";
import { ITablePage } from "@/const/interface_type";
import { timestampToTime, getValueLabel, getValueListLabel } from "@/utils/util";
import { getAddress } from "@/api/basicInfo/index";
import { getDeptList, getDeptObj, addDeptObj, putDeptObj, delDeptObj } from "@/api/admin";

interface ISearchList {
  deptName: string;
}

const searchList = ref<ISearchList>({
  deptName: ""
}); // 搜索数据
const tableData = ref([]); // 表格数据
const tablePage = ref<ITablePage>({
  currentPage: 1,
  pageSize: 10,
  total: 0
});
const tableLoading = ref(false); // 表格loading

const dialogVisible = ref(false); // 新增/修改/查看 弹窗是否展示
const title = ref(""); // 新增/修改/查看 弹窗标题
const form = ref<any>({
  parentId: "",
  name: "",
  abbreviationName: "",
  sortOrder: undefined,
  deptType: "",
  longitude: "",
  dimension: "",
  warehouseType: [],
  fileList: []
});
const formRef = ref<FormInstance>();
const formRules = ref<FormRules>({
  parentId: [{ required: true, message: "上级部门不能为空", trigger: "change" }],
  name: [{ required: true, message: "部门名称不能为空", trigger: "blur" }],
  deptType: [{ required: true, message: "部门类型不能为空", trigger: "change" }],
  sortOrder: [{ required: true, message: "请选择排序", trigger: "blur" }]
});

const addressOption = ref([]); // 地址
const deptOptions = ref<any>([]); // 部门目录

const { dept_type, del_type, warehouse_type } = useDict("dept_type", "del_type", "warehouse_type");

getAddress().then((res: any) => {
  if (res.code === 0) {
    addressOption.value = res.data;
  }
});

// 搜索/获取列表
const getList = () => {
  tableLoading.value = true;
  const payload = {
    // current: tablePage.value.currentPage,
    // size: tablePage.value.pageSize,
    ...searchList.value
  };
  getDeptList(payload).then((res: any) => {
    if (res.code === 0) {
      tableData.value = res.data;
      // tablePage.value.total = res.data.total;
      tableLoading.value = false;
    }
  });
};

getList();

//
const deptTypeChange = (val: string) => {
  if (val === "3") {
    formRules.value.warehouseType = [{ required: true, message: "仓库类型不能为空", trigger: "change" }];
    formRules.value.longitude = [{ required: true, message: "经度不能为空", trigger: "blur" }];
    formRules.value.dimension = [{ required: true, message: "维度不能为空", trigger: "blur" }];
  } else {
    formRules.value.warehouseType = [];
    formRules.value.longitude = [];
    formRules.value.dimension = [];
  }
  nextTick(() => {
    formRef.value?.clearValidate();
  });
};

// 添加/查看/编辑 列表数据
const addOrUpdateHandle = (isEdit: boolean, id?: string) => {
  // 获取菜单信息
  getDeptList().then((res: any) => {
    if (res.data[0].parentId === "0") {
      const menu = [{ id: "0", name: "根菜单", children: res.data }];
      deptOptions.value = filterList(menu);
    } else {
      deptOptions.value = filterList(res.data);
    }
  });
  if (isEdit && id) {
    title.value = "修改";
    getDeptObj(id).then((res: any) => {
      if (res.code === 0) {
        form.value = res.data;
        form.value.warehouseType = JSON.parse(form.value.warehouseType);
      }
    });
  } else {
    title.value = "新增";
    if (id) {
      form.value.parentId = id;
    }
  }
  dialogVisible.value = true;
};

const filterList = (arr: any) => {
  const filterData = arr.map((item: any) => {
    return {
      label: item.name,
      value: item.id,
      children: item.children?.length ? filterList(item.children) : []
    };
  });
  return filterData;
};

// 处理参数
const trimParam = () => {
  const data = {
    ...form.value
  };
  data.warehouseType = data.warehouseType ? JSON.stringify(data.warehouseType) : "[]";
  if (data.deptMergeAddress?.length > 0) {
    data.deptProvince = data.deptMergeAddress[0];
    data.deptCity = data.deptMergeAddress[1];
    data.deptArea = data.deptMergeAddress[2];
    data.deptMergeAddress = JSON.stringify(data.deptMergeAddress);
  }
  data.fileList = JSON.stringify(data.fileList);
  return data;
};

// 保存添加
const addDept = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      addDeptObj(trimParam()).then((res: any) => {
        if (res.code === 0) {
          ElMessage.success("创建成功");
          clearDialogData();
          dialogVisible.value = false;
          getList();
        }
      });
    } else {
      return false;
    }
  });
};

// 保存编辑
const saveDept = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      putDeptObj(trimParam()).then((res: any) => {
        if (res.code === 0) {
          ElMessage.success("编辑成功");
          clearDialogData();
          dialogVisible.value = false;
          getList();
        }
      });
    } else {
      return false;
    }
  });
};

// 删除数据
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`是否确认删除名称为 “${row.name}” 的数据项?`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    delDeptObj(row.id).then(() => {
      ElMessage({
        type: "success",
        message: `删除 “${row.name}” 成功`
      });
      getList();
    });
  });
};

// 添加/查看/编辑 弹窗关闭前
const dialogClose = (done: () => void) => {
  clearDialogData();
  done();
};

// 清空弹窗数据
const clearDialogData = () => {
  form.value = {
    parentId: "",
    name: "",
    sortOrder: undefined,
    deptType: "",
    longitude: "",
    dimension: "",
    warehouseType: [],
    fileList: []
  };
  formRef.value?.clearValidate();
};
</script>

<style lang="scss" scoped></style>
