<script setup>
import { CirclePlus } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'
import { getOrganizationList, postOrganization, putOrganization, delOrganization, getRegion } from '@/api/client/manage'

const { proxy } = getCurrentInstance();

const loading = ref(false);
const tableLoading = ref(false);
const tableData = ref([]);
const queryParams = ref({
  pageNum: 1,
  pageSize: 1000,
  name: '',
  provinceCode: '',
  type: 0,
  status: '',
  regionList: []
});

const typeEmun = {
  0: '集团',
  1: '水厂'
}

const formData = ref({});
const formRef = ref(null);

const dialogVisible = ref(false);

const rules = {
  name: [
    { required: true, message: '请输入机构名称', trigger: 'blur' },
  ],
  regionList: [
    { type: 'array', required: true, message: '请选择省市区', trigger: 'change' }
  ]
}

const regionOptions = ref([]);
const typeOptions = [
  { value: 0, label: '集团'},
  { value: 1, label: '水厂'},
]
const statusOptions = [
  { value: '', label: '全部'},
  { value: 0, label: '正常'},
  { value: 1, label: '停用'},
]

const cascaderProps = {
  lazy: true,
  lazyLoad(node, resolve) {
    const { level } = node
    getRegion({ regionLevel: level + 1, parentId: node.data.regionId, pageSize: 100 }).then(({ rows }) => {

      console.log( "rows", rows );

      const nodes = rows.map(item => {
        return {
          value: item.regionCod,
          label: item.regionName,
          regionId: item.regionId,
          leaf: level >= 2,
        }
      })
      resolve(nodes)
    })
  },
}

// 新增机构
const handleAddOrganization = () => {
  formData.value = { ...formData.value, type: 0, title: "新增机构", isAdd: true }
  dialogVisible.value = true;
}

// 添加水厂
const handleAddWaterFactory = (row) => {
  formData.value = { ...formData.value, parentId: row.id, parentName: row.name, type: 1, title: "添加水厂", isAdd: true };
  dialogVisible.value = true;
}

// 编辑水厂
const handleEditOrganizationOrFactory = (row) => {
  const { parentId, name: parentName, type, provinceCode, cityCode, countryCode }  = row;
  formData.value = {
    ...row,
    parentId: type == 0 ? 0 : parentId,
    parentName,
    type,
    title: type == 0 ? "编辑机构" : "编辑水厂",
    regionList: [provinceCode, cityCode, countryCode]
  };
  dialogVisible.value = true;
}

// 删除机构or水厂
const handleDelete = async ({ id }) => {
  await delOrganization(id);
  proxy.$modal.msgSuccess("删除成功");
  initPageData();
}

const initPageData = async () => {
  tableLoading.value = true;

  const { rows } = await getOrganizationList(queryParams.value);

  tableData.value = rows.map(item => ({
    ...item,
    typeText: typeEmun[item.type],
    children: item.children ? item.children.map(child => ({
      ...child,
      typeText: typeEmun[child.type],
      parentId: item.id
    })) : [],
  }));
  tableLoading.value = false;
}

// 查询
const handleQuery = async() => {
  initPageData();
}

// 重置
const handleReset = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10000,
    name: '',
    provinceCode: '',
    type: 0,
    status: '',
    regionList: []
  }
  initPageData();
}

// 重置dialog表单
const handleDialogReset = () => {
  formRef.value.resetFields();
  formData.value = {};
}

// 切换table - 状态
const onChangeTag= (row) => {
  const content = `请确认，是否要${row.status == 0 ? '停用' : '启用'}该${row.type == 0 ? '机构' : '水厂'}？`
  ElMessageBox.confirm(
    content,
    '状态变更提醒',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    const params = {
      id: row.id,
      status: row.status == 0 ? 1 : 0
    }
    await putOrganization(params);
    initPageData();
    proxy.$modal.msgSuccess("状态变更成功");
  }).catch(() => {})
}

// 新增机构 - 保存
const handleDialogConfirm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      const [provinceCode, cityCode, countryCode] = formData.value.regionList || [];
      const params = {
        ...formData.value,
        provinceCode,
        cityCode,
        countryCode
      }
      params.isAdd ? await postOrganization(params) : await putOrganization(params);
      initPageData();
      formRef.value.resetFields();
      dialogVisible.value = false;
      proxy.$modal.msgSuccess("操作成功");
    } else {
      console.log('error submit!', fields)
    }
  })
}

onMounted(() => {
  getRegion({ regionLevel: 1 }).then(({ rows }) => {
    regionOptions.value = rows.map(item => ({ value: item.regionCod, label: item.regionName}));
  })
  initPageData();
})
</script>

<template>
  <div>
    <el-card shadow="never" :body-style="{ border: '0px' }" style="margin-bottom: 10px;">
      <template #header>
        <p class="space-x-[10px]">
          <span class="font-bold">数据筛选</span>
        </p>
      </template>
      <el-row class="pt-[5px]" justify="space-between" :gutter="20">
        <el-col :span="6">
          <el-form-item label="机构名称">
            <el-input placeholder="请输入机构名称" v-model.trim="queryParams.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属省份">
            <el-select v-model="queryParams.provinceCode" placeholder="请选择所属省份" filterable clearable>
              <el-option v-for="item in regionOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="机构类型">
            <el-select v-model="queryParams.type" placeholder="请选择类型" filterable clearable>
              <el-option v-for="item in typeOptions" :key="item.label" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="请选择状态" filterable clearable>
              <el-option v-for="item in statusOptions" :key="item.label" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="18">
          <div class="flex justify-end">
            <el-button type="primary" @click="handleQuery" :loading="loading">查询</el-button>
            <el-button @click="handleReset" :loading="loading">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-card shadow="never" :body-style="{ padding: '20px' }">
      <div class="flex justify-between items-center mb-[10px]">
        <el-button type="primary" @click="handleAddOrganization" :loading="loading" :icon="CirclePlus">新增机构</el-button>
      </div>
      <el-table :data="tableData" style="width: 100%" v-loading="tableLoading" row-key="id" border>
        <el-table-column prop="name" label="机构名称" width="280" fixed/>
        <el-table-column prop="code" label="机构编号" width="180" />
        <el-table-column prop="typeText" label="机构类型" width="180"/>
        <el-table-column prop="provinceName" label="省份" width="180"/>
        <el-table-column prop="lxjcCounts" label="连续检测设备总数" width="180"/>
        <el-table-column prop="robotCounts" label="实验室设备总数" width="180"/>
        <el-table-column prop="concat" label="联系人" width="180"/>
        <el-table-column prop="phone" label="联系电话" width="180"/>
        <el-table-column prop="status" label="状态" width="180">
          <template #default="{ row }">
            <el-check-tag :checked="row.status == 0" type="success" @change="onChangeTag(row)">
              {{ row.status == 0 ? '正常' : '停用' }}
            </el-check-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createUser.nickName" label="创建人" width="180"/>
        <el-table-column prop="createTime" label="创建时间" width="180"/>
        <el-table-column prop="address" label="操作" fixed="right" width="220">
          <template #default="{ row }">
            <el-button text type="primary" size="small" @click="handleAddWaterFactory(row)" :disabled="row.type == 1">添加水厂</el-button>
            <el-button text type="primary" size="small" @click="handleEditOrganizationOrFactory(row)">编辑</el-button>
            <el-popconfirm title="请确认是否删除?" @confirm="handleDelete(row)" width="200">
              <template #reference>
                <el-button text type="primary" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="formData.title" width="900" @closed="handleDialogReset">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="80px" label-position="left" require-asterisk-position="right">
        <el-row justify="space-between">
          <el-col :span="11">
            <el-form-item label="名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="formData.sort" :min="1" :step="1" step-strictly placeholder="请输入排序序号" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="编号" prop="code">
              <el-input v-model="formData.code" placeholder="请输入编号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11" v-if="formData.type == 1" prop="parentId">
            <el-form-item label="上级机构" prop="parentName">
              <span>{{ formData.parentName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="11" prop="regionList">
            <el-form-item label="省市区" prop="regionList">
              <el-cascader
                v-model="formData.regionList"
                :props="cascaderProps"
                placeholder="请选择省市区"
                class="w-full"
              /> 
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="formData.address" placeholder="请输入详细地址" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="formData.longitude" placeholder="请输入经度" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="formData.latitude" placeholder="请输入纬度" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态" clearable>
                <el-option label="正常" :value="0" />
                <el-option label="停用" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="联系人" prop="concat">
              <el-input v-model="formData.concat" placeholder="请输入联系人" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入联系电话" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" >取 消</el-button>
          <el-button @click="handleDialogConfirm" type="primary">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    
  </div>
</template>