<template>
  <div>
    <crud-template ref="crudRef" class="as-weight" :submit-state="false" :home-data="field" :tableData="tableData"
      @btnSearch="btnSearch" @CurrentChange="handleCurrentChange" @importData="importData" @refreshLeft="refreshLeft"
      @add="handleAdd" @cancel="cancel">
      <template #search>
        <el-input maxlength="60" v-trim clearable v-model="searchForm.name" style="width: 200px"
          placeholder="请输入网点名称" />
        <el-input maxlength="60" v-trim clearable v-model="searchForm.serviceHallId" style="width: 200px"
          placeholder="请输入网点编号" />
        <el-input maxlength="60" v-trim clearable v-model="searchForm.agencyId" style="width: 200px"
          placeholder="请输入渠道编号" />
      </template>
      <template #CustomButton>
        <!-- <el-button v-if="IsPermission(route, 'ADD_FIRST_DOT')" type="primary" @click="handleFirstDot" icon="Plus">
          添加一级网点
        </el-button> -->
        <el-button type="success" @click="getItmeLiet()">
          中心网点管理
        </el-button>
      </template>
      <template #operation="{ scope }">
        <el-button v-if="IsPermission(route, 'EDIT_LIST')" type="primary" @click="handleEdit(scope.row)" size="small">
          编辑
        </el-button>
        <!-- <el-button v-if="IsPermission(route, 'EDIT_LIST')" type="primary" @click="handleImport(scope.row)" size="small">
          导入
        </el-button> -->
        <el-upload style="display: inline-block; margin: 0 10px;vertical-align: middle;" ref="upload" :data="data"
          :action="uploadUrl" :on-success="handleAvatarSuccess" accept=".xls, .xlsx" :limit="1"
          :on-exceed="handleExceed" :show-file-list="false" :multiple="false">
          <el-button type="primary" class="btn" icon="Upload" @click="handleImport(scope.row)" size="small">
            导入
          </el-button>
        </el-upload>

        <el-button v-if="IsPermission(route, 'EDIT_LIST')" type="primary" @click="handleFileName()" size="small">
          下载模板
        </el-button>
        <el-button v-if="IsPermission(route, 'DEL_LIST')" :type="scope.row.state==='ENABLE'?'danger':'success'" @click="handleDetele(scope.row)" size="small">
          {{ scope.row.state === 'ENABLE' ? '禁用' : '启用' }}
        </el-button>
      </template>
      <template #dialog>
        <el-form label-position="right" label-width="150px" :model="addForm" :rules="rules"
          :ref="(el) => (dataFormRef = el)" :hide-required-asterisk="typeOption === 'view'" v-loading="formLoding">
          <el-form-item v-if="!isFirstDot" label="上级网点:" prop="superServiceHallId">
            <div style="width: 100%">
              <el-tree-select :load="load" lazy filterable style="width: 100%" placeholder="请选择上级网点编号"
                v-model="addForm.superServiceHallId" :props="{
                  label: 'servicehallName',
                  children: 'childrens',
                  value: 'servicehallId',
                  isLeaf: 'isLeaf',
                }" value-key="servicehallId" :check-strictly="true" :render-after-expand="false"
                node-key="servicehallId" show-checkbox />
            </div>
          </el-form-item>
          <el-form-item label="网点编号:" prop="serviceHallId">
            <div style="width: 100%">
              <el-input maxlength="60" v-trim clearable v-model="addForm.serviceHallId" placeholder="请输入网点编号" />
            </div>
          </el-form-item>
          <el-form-item label="网点名称:" prop="name">
            <div style="width: 100%">
              <el-input maxlength="60" v-trim clearable v-model="addForm.name" placeholder="请输入网点名称" />
            </div>
          </el-form-item>
          <el-form-item label="中心网点编号:" prop="mapChannelId">
            <div style="width: 100%">
              <el-select clearable filterable v-model="addForm.mapChannelId" style="width: 100%"
                @change="centerServiceHallIdChange" placeholder="请选择中心网点编号">
                <el-option v-for="item in centerServiceHallIdList" :key="item.centerServiceHallId" :label="item.centerServicehallName"
                  :value="item.centerServiceHallId" />
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="地址:" prop="address">
            <div style="width: 100%">
              <el-input maxlength="60" v-trim clearable v-model="addForm.address" placeholder="请输入地址" />
            </div>
          </el-form-item>
          <el-form-item label="联系人电话:" prop="tel">
            <div style="width: 100%">
              <el-input maxlength="60" v-trim clearable v-model="addForm.tel" placeholder="请输入联系人电话" />
            </div>
          </el-form-item>
          <el-form-item label="联系人:" prop="contact">
            <div style="width: 100%">
              <el-input maxlength="60" v-trim clearable v-model="addForm.contact" placeholder="请输入联系人" />
            </div>
          </el-form-item>
          <el-form-item label="经度:" prop="longitude">
            <div style="width: 100%">
              <el-input maxlength="60" v-trim clearable v-model="addForm.longitude" placeholder="请输入经度" />
            </div>
          </el-form-item>
          <el-form-item label="纬度:" prop="latitude">
            <div style="width: 100%">
              <el-input maxlength="60" v-trim clearable v-model="addForm.latitude" placeholder="请输入纬度" />
            </div>
          </el-form-item>
          <el-form-item label="半径距离(单位:米):" prop="radial">
            <div style="width: 100%">
              <el-input maxlength="60" v-trim clearable v-model="addForm.radial" placeholder="请输入半径距离(单位:米)" />
            </div>
          </el-form-item>

          <el-form-item label="所属渠道:" prop="agencyId">
            <div style="width: 100%">
              <el-select clearable filterable v-model="addForm.agencyId" style="width: 100%" @change="agencyIdChange"
                placeholder="请选择所属渠道">
                <el-option v-for="item in agencyList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="渠道编号:" prop="agencyId">
            <div style="width: 100%">
              <el-select clearable filterable v-model="addForm.agencyId" style="width: 100%" placeholder="请选择所属渠道"
                :disabled="true">
                <el-option v-for="item in agencyList" :key="item.value" :label="item.value" :value="item.value" />
              </el-select>
            </div>
          </el-form-item>
        </el-form>


        <div style="padding: 0 0 30px 0;text-align: right;">
          <el-button type="success" icon="Plus" @click="addBtn" style="margin-bottom: 10px;">
            添加
          </el-button>
          <div style="padding: 20px 50px;text-align: left;font-weight: 700;" v-if="addForm.locationModels.length > 0">
            办理点信息</div>
          <el-form v-for="(item, index) in addForm.locationModels" :key="index" label-width="150" :rules="rules" :model="item">
            <el-form-item label="名称:" prop="name">
              <div style="width: 100%">
                <el-input maxlength="60" v-trim clearable v-model="item.name" placeholder="请输入办理点名称" />
              </div>
            </el-form-item>
            <el-form-item label="地址:" prop="address">
              <div style="width: 100%">
                <el-input maxlength="60" v-trim clearable v-model="item.address" placeholder="请输入地址" />
              </div>
            </el-form-item>
            <el-form-item label="经度:" prop="longitude">
              <div style="width: 100%">
                <el-input maxlength="60" v-trim clearable v-model="item.longitude" placeholder="请输入经度" />
              </div>
            </el-form-item>
            <el-form-item label="纬度:" prop="latitude">
              <div style="width: 100%">
                <el-input maxlength="60" v-trim clearable v-model="item.latitude" placeholder="请输入纬度" />
              </div>
            </el-form-item>
            <el-form-item label="半径距离(单位:米):" prop="radial">
              <div style="width: 100%">
                <el-input maxlength="60" v-trim clearable v-model="item.radial" placeholder="请输入半径距离(单位:米)" />
              </div>
            </el-form-item>
            <el-button class="op-btn" type="danger" @click="deleteHandle(index)">
              删除
            </el-button>
          </el-form>
        </div>
      </template>

      <template #footer>
        <el-button type="default" @click="cancel" v-if="typeOption !== 'view'">
          取消
        </el-button>
        <el-button type="primary" @click="submitHandle()" v-if="typeOption !== 'view'">
          确定
        </el-button>
      </template>
    </crud-template>


    <el-dialog title="中心网点管理" v-model="vShowDoalog">
      <crud-template ref="crudRefTwo" :home-data="zxqdFind" @submit="itemAdd" @handleEdit="itemEdit" @add="Adds"
        :searchForm="searchForm" @CurrentChange="handleCurrentChangeTwo" @handleDelete="itemDelete"
        :tableData="tableItemData">
      </crud-template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, toRaw, onMounted, computed } from 'vue'
// @ts-ignore crudFrom模板
import CrudTemplate from '@/crud/index.vue'
import BaseService from '@/utils/baseService' //引入接口请求
import {
  ElMessage, ElMessageBox, UploadInstance, UploadProps,
  UploadRawFile,
  genFileId,
} from 'element-plus' //提示
import { getCache } from '@/utils/cache'
import { IObject } from '@/types/interface'
import { useDebounce } from '@/utils/utils'
import { useRoute } from 'vue-router'
import { IsPermission } from '@/router/routerUtil'
import { getZxqdFindConfig } from "./data.js";
const crudRef = ref()
const agencyIdC = ref()
const dataFormRef = ref()
const url = ref()
const serviceHallId = ref()
const data = { bucket: '' }
const parentSelectList = ref([] as IObject[])
const upload = ref<UploadInstance>()
//或取路由传入过来的对象数据
const route = useRoute()
const zxqdFind = ref(getZxqdFindConfig(route));;
const vShowDoalog = ref(false);
const crudRefTwo = ref();
const tableItemData = ref([]);
// 导入
const uploadUrl = '/minIo/upload'
let orderStep = ref('')
const itemStartValue = ref("1")

//查询参数
const searchForm = ref({
  name: '', //网点名称
  serviceHallId: '', //网点编号
  agencyId: '', //渠道编号
  agencyName: '', //机构
  orderSource: 'WEB',
})
let tableData: any = ref([])
const initItem = {
  name: '',
  superServiceHallId: '',
  serviceHallId: '',
  address: '',
  contact: '',
  mapChannelId: '',
  tel: '',
  orderSource: 'WEB',
  agencyId: '',
  locationModels: [

  ]
}
const addForm: any = ref(initItem)
const formLoding = ref(false)
const rules = reactive({
  // superServiceHallId: [{ required: true, message: '请输入', trigger: 'blur' }],
  serviceHallId: [{ required: true, message: '请输入', trigger: 'blur' }],
  name: [{ required: true, message: '请输入', trigger: 'blur' }],
  address: [{ required: true, message: '请输入', trigger: 'blur' }],
  tel: [{ required: true, message: '请输入', trigger: 'blur' }],
  contact: [{ required: true, message: '请输入', trigger: 'blur' }],
  longitude: [{ required: true, message: '请输入', trigger: 'blur' }],
  latitude: [{ required: true, message: '请输入', trigger: 'blur' }],
  radial: [{ required: true, message: '请输入', trigger: 'blur' }],
  agencyId: [{ required: true, message: '请选择', trigger: 'blur' }],
  mapChannelId: [{ required: true, message: '请输入', trigger: 'blur' }],
})
const typeOption = ref('')
const agencyId = computed(() => {
  let cacheAccessToken = getCache(
    'cacheAccessToken',
    { isSessionStorage: false },
    {}
  )
  return cacheAccessToken['agencyId']
})
onMounted(() => {
  getList()
  getAgencyList()
})
//新增
const itemAdd = (data: any) => {
  request(data, itemStartValue.value)
}
const Adds = () => {
  console.log(zxqdFind.value.field[0].form);
  zxqdFind.value.field[0].form.hideEdit = false;
  itemStartValue.value = 1
}
//表单编辑按钮
function itemEdit(idx: any, row: any) {
  console.log("我是编辑事件", idx, row);
  // request(row, 2)
  zxqdFind.value.field[0].form.hideEdit = true;
  itemStartValue.value = 2
}
//表单删除按钮
function itemDelete(idx: any, row: any) {
  console.log("删除事件", idx, row);
  BaseService.postN('/userw/centerServiceHall/delete', row).then((res: any) => {
    if (res && res.code === 0) {
      getItmeLiet()
      crudRefTwo.value.reset();
      crudRefTwo.value.dialogFormVisible = false;
    } else {
      ElMessage.error(res.message)
    }
  })
}
const request = (data: any, type: any) => {
  data.optType = type //操作类型 1新增 2修改 
  BaseService.postN('/userw/centerServiceHall/addOrUpDate', data).then((res: any) => {
    if (res && res.code === 0) {
      getItmeLiet()
      crudRefTwo.value.reset();
      crudRefTwo.value.dialogFormVisible = false;
    } else {
      ElMessage.error(res.message)
    }
  })
}
function handleCurrentChangeTwo(val: number) {
  console.log(val + '===');

  zxqdFind.value.paging.currentPage = val;
  getItmeLiet();
}
const getItmeLiet = () => {
  vShowDoalog.value = true
  if (crudRefTwo.value) {
    crudRefTwo.value.tableLoding = true;
  }
  let params: any = {
    methods: "page",
    pageNo: zxqdFind.value.paging.currentPage,
    pageSize: zxqdFind.value.paging.pageSize,
  }
  let searchFormList = { ...searchForm.value }
  for (let key in searchFormList) {
    if (searchFormList[key]) {
      params[key] = searchFormList[key]
    }
  }
  BaseService.postN('/userw/centerServiceHall/page', params).then((res: any) => {
    console.log(res, 'res')
    if (res && res.code === 0) {
      let bizContent = res.data
      let data = bizContent.result || [];
      data.forEach((item) => {
        if (item.models) item.models.forEach((i) => {
          if (i.agreementAnnex) i.fileList = [{ name: i.agreementAnnex }]
        })
      })
      console.log("bizContent12222", data)
      tableItemData.value = data;
      crudRefTwo.value.tableLoding = false;
      zxqdFind.value.paging.total = bizContent.totalCount;
    } else {
      crudRefTwo.value.tableLoding = false;
      ElMessage.error(res.message)
    }
  })
}
// 添加
const addBtn = () => {
  addForm.value.locationModels.push({
    address: '',
    latitude: '',
    longitude: '',
    name: '',
    radial: '',
  })
}
// 删除
const deleteHandle = (index) => {
  addForm.value.locationModels.splice(index, 1)
}
// 搜索按钮
function btnSearch() {
  field.value.paging.currentPage = 1
  getList()
}

//标签分页
function handleClick(tab, event) {
  orderStep.value = tab.props.name
  getList()
}

//分页
function handleCurrentChange(val: number) {
  field.value.paging.currentPage = val
  getList()
}
function handleAvatarSuccess(response: any, row) {
  console.log(22222222222);
  console.log(response, row, 22222222222);
  const { ossFilePath, originalFileName } = response.data
  url.value =  ossFilePath
  console.log(url.value, originalFileName)
  BaseService.postN('/userw/serviceHall/registerLocationBath', { excelFileUrl: url.value, serviceHallId: serviceHallId.value }).then((res: any) => {
    if (res && res.code === 0) {
      console.log(res)
      const errUrl = res.data?.path ?? ''
      if (errUrl) {
        ElMessage.error("导入失败，请查看下载到本地文件的具体错误信息");
        BaseService.getDownload(
          import.meta.env.VITE_APP_EXPORT_URL_NEW + errUrl,
          '错误信息文件'
        )
      } else {
        ElMessage.success("导入成功");
        url.value = ''
      }
    }
  })
}
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
  upload.value!.submit()
}
// 搜索重置
function refreshLeft() {
  searchForm.value = {
    name: '', //网点名称
    serviceHallId: '', //网点编号
    agencyId: '', //渠道编号
    agencyName: '', //机构
    orderSource: 'WEB',
  }
  field.value.paging.currentPage = 1
  getList()
}

//获取列表
function getList() {
  crudRef.value.tableLoding = true
  let params: any = {
    pageNo: field.value.paging.currentPage,
    pageSize: field.value.paging.pageSize,
  }
  //赋值查询参数
  let searchFormList = { ...searchForm.value }
  for (let key in searchFormList) {
    if (searchFormList[key]) {
      params[key] = searchFormList[key]
    }
  }
  BaseService.postN('/userw/serviceHall/serviceHallSelect', params).then((res: any) => {
    if (res && res.code === 0) {
      //数据转换
      let bizContent = res.data
      let data = bizContent.result || []
      //数据渲染
      tableData.value = data
      crudRef.value.tableLoding = false
      //分页总数
      field.value.paging.total = bizContent.totalCount
    } else {
      crudRef.value.tableLoding = false
      ElMessage.error(res.message)
    }
  })
}

let formLabelWidth = '130px'
let contentWidth = '100%'
//表单数据配置
let field = ref({
  tabSize: 'small', //Table 的尺寸 large / default /small (默认default)
  searchShow: IsPermission(route, 'QUERY_BASE'), //是否显示搜索模块(默认false)
  border: true, //是否添加边框(默认false)
  dialogCustom: true, //自定义Dialog (默认false)
  dialogFooter: true, //隐藏弹窗页脚显示 (默认false)
  dialogWidth: '40%', //dialog宽度 (默认40%)
  crudShow: true, //是否显示CURD操作栏 (默认true)
  crudChildShow: true, //是否显示CURD子操作栏 (默认true)
  paginStart: true, //是否显示分页查询 (默认false)
  titleDialog: '', //table 标题
  dataListLoading: false,
  operateTitle: '操作', //操作栏标题(默认为"")
  operateWidth: "350px", //操作栏宽度
  crud: {
    add: IsPermission(route, 'ADD_BASE'),
  },
  operate: {
    edit: false, //是否编辑(默认true)
    delete: false, //是否删除(默认true)
    remark: false, // 详情
    announcement: false, // 公告
    forbidden: false, // 禁用
    enable: false, // 启用
    authorization: false, // 授权
    cancel: false, // 取消订单
  },
  searchOperation: {
    isDownload: false,
    isAdd: false,
    isTransferMachine: false,
    isToLead: true, // 导入
    isTemplate: true,

    templateUrl:
      import.meta.env.VITE_APP_EXPORT_URL_NEW +
      'zhywpt-issuer/template/userw/网点信息导入模板.xlsx',
    templateFileName: '网点信息导入模板',
  },
  tableSize: -1,
  paging: {
    pageSize: 10,
    currentPage: 1,
    total: 0,
  },
  extend: [
    {
      label: '序号',
      type: 'index',
      width: '80px',
    },
  ],
  field: [
    {
      prop: 'agencyId',
      label: '渠道编号',
    },
    {
      prop: 'agencyName',
      label: '渠道名称',
    },
    {
      prop: 'superServiceHallId',
      label: '上级网点编号',
    },
    {
      prop: 'superServiceHallName',
      label: '上级网点名称',
    }, {
      prop: 'mapChannelId', //centerServiceHallId
      label: '中心网点编号',
    },
    {
      prop: 'serviceHallId',
      label: '网点编号',
    },
    {
      prop: 'name',
      label: '网点名称',
    },
    {
      prop: 'address',
      label: '网点地址',
    },
    {
      prop: 'tel',
      label: '联系人电话',
    },
    {
      prop: 'contact',
      label: '联系人',
    },
  ],
})
const isFirstDot = ref(false)
function getServiceHallId(e) {
  //获取网点编号
  BaseService.postN('/userw/serviceHall/getServiceHallId', {
    agencyId: e,
  }).then((res: any) => {
    console.log(res, 'resresres');
    addForm.value.serviceHallId = res.data
    // load({isLeaf: false,key: res.data},()=>{})
  })
}
function getCenterServiceHall() {
  //获取中心网点编号信息 /userw/centerServiceHall/getCenterServiceHall

  BaseService.postN('/userw/centerServiceHall/getCenterServiceHall', {

  }).then((res: any) => {
    console.log(res, 'resresres');
    centerServiceHallIdList.value = res.data
  })
}
//添加中心网点编号
const centerServiceHallIdChange = (value) => {
  console.log(value, 'eeee');
  addForm.value.mapChannelId = value
  // getServiceHallId(value)
}
function handleFirstDot() {
  //获取网点编号
  getCenterServiceHall()
  getServiceHallId(agencyId.value)
  isFirstDot.value = true
  crudRef.value.dialogFormVisible = true
  addForm.value.agencyId = agencyId.value
}
//添加一级网点切换所属渠道
const agencyIdChange = (value) => {
  if(value===''||value===null||value===undefined){
    ElMessage.error("渠道不能为空！")
    return;
  }
  agencyIdC.value = value
  addForm.value.agencyId = value
  getServiceHallId(value)
}
const agencyList = ref<any>([])
const centerServiceHallIdList = ref<any>([])
// 获取所有渠道
function getAgencyList() {
  BaseService.postN('/userw/agency/agencyqueryall').then((res: any) => {
    if (res && res.code === 0) {
      let bizContent = res.data
      console.log(bizContent, '------');

      let data = bizContent || []
      let list = [] as IObject[]
      data.map((item) => {
        list.push({
          label: item.name,
          value: item.agencyId,
        })
      })
      agencyList.value = list
    } else {
      ElMessage.error(res.message)
    }
  })
}
function importData(url) {
  // importFn('a8f9dac698cb4793bb15f26fd608d2b3', getList(), { excelFileUrl: url })
  BaseService.postN('/userw/serviceHall/registerFullBath', { excelFileUrl: url }).then((res: any) => {
    if (res && res.code === 0) {
      console.log(res)
      const errUrl = res.data?.path ?? ''
      if (errUrl) {
        ElMessage.error("导入失败，请查看下载到本地文件的具体错误信息");
        BaseService.getDownload(
          import.meta.env.VITE_APP_EXPORT_URL_NEW + errUrl,
          '错误信息文件'
        )
      } else {
        ElMessage.success("导入成功");
      }
      // //处理导入失败问题
      // if (res && res.code === 0) {
      //             let bizContent = res.data
      //             let url = bizContent.url || "";
      //             let fileName = bizContent.fileName ? `${bizContent.fileName}` : ''
      //             if (url) {
      //                 //window.open(url)
      //                 //处理下载有文件名
      //                 BaseService.getDownloadFileName(import.meta.env.VITE_APP_UPLOAD_URL + url, fileName)
      //                 // btnLoding.value = false;
      //                 // clearData();
      //                 // emit("refreshDataList");
      //                 // emit("closeHandle");
      //                 ElMessage.success("导入成功");
      //             } else {
      //                 ElMessage.error("导入失败");
      //             }

      //         } else {
      //             // btnLoding.value = false;
      //             ElMessage.error(res.message);
      //         }
    }
  });
}
function submitClick() {
  getCenterServiceHall()
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false
    }
    let api = ''
    let params = {
      ...addForm.value,
    }
    if (typeOption.value === 'edit') {
      api = '/userw/serviceHall/serviceHallUpdate'
    } else {
      if (isFirstDot.value === false) {
        api = '/userw/serviceHall/serviceHallInsert'
      } else {
        delete params.superServiceHallId
        api = '/userw/serviceHall/serviceHallInsertnelevel'
      }
    }
    // if (!isFirstDot.value) {
    //   params.agencyId = agencyId.value
    // }
    // agencyList.value.forEach(item => {
    //   if (item.value === params.agencyId) {
    //     params.agencyName = item.label
    //   }
    // });
    if (!params.superServiceHallId) {
      params.superServiceHallId = null
    }
    BaseService.postN(api, params).then((res: any) => {
      if (res && res.code === 0) {
        ElMessage.success('操作成功')
        getList()
        cancel()
      } else {
        ElMessage.error(res.message)
      }
    })
  })
}
function removeNullValues(obj) {
  Object.keys(obj).forEach(key => {
    if (obj[key] === null) {
      delete obj[key];
    }
  });
  return obj;
}
const submitHandle = useDebounce(submitClick)
function handleAdd() {
  console.log(1111);
  getServiceHallId(agencyId.value)
  getCenterServiceHall()
  isFirstDot.value = false
  addForm.value.agencyId = agencyId.value
}
const load = (node, resolve) => {
  // formLoding.value = true
  if (node.isLeaf) return resolve([])

  let serviceHallId = node.data.servicehallId
  console.log(node);

  if (!serviceHallId) { // 第一次获取数据
    let cacheAccessToken = getCache(
      'cacheAccessToken',
      { isSessionStorage: false },
      {}
    )
    serviceHallId = cacheAccessToken['serviceHallId']
    BaseService.postN('/userw/serviceHall/serviceHallSonSelect', { serviceHallId })
      .then((res: any) => {
        if (res && res.code === 0) {
          let data = res.data || {}
          data.forEach(item => {
            if (item.childrens && item.childrens.length === 0) {
              item.isLeaf = true
            }
          })
          setTimeout(() => {
            resolve(data)
          }, 400)
        } else {
          ElMessage.error(res.message)
        }
      })
      .finally(() => {
        formLoding.value = false
      })
  } else {
    formLoding.value = false
    const children = node.data?.childrens ?? []
    children.forEach(item => {
      if (item.childrens && item.childrens.length === 0) {
        item.isLeaf = true
      }
    })
    setTimeout(() => {
      resolve(children)
    }, 400)
  }
}
// 树形数据处理
function selectDataHandle(data: IObject[]): IObject[] {
  if (data === null || typeof data === 'undefined') return []
  let newData = [] as IObject[]
  data.map((item) => {
    let children = [] as IObject[]
    if (
      !(item.childrens === null || typeof item.childrens === 'undefined') &&
      item.childrens.length > 0
    ) {
      children = selectDataHandle(item.children)
    }
    newData.push({
      label: item.servicehallName,
      value: item.serviceHallId,
      children: children,
    })
  })
  return newData
}
//导入
function handleImport(row) {
  serviceHallId.value = row.serviceHallId
}
//模板下载
function handleFileName() {
  BaseService.getDownload(
    import.meta.env.VITE_APP_EXPORT_URL_NEW + 'zhywpt-issuer/template/userw/办理地址信息导入模板.xlsx',
    '办理地址信息导入模板'
  )
}
//编辑
function handleEdit(row: IObject) {
  getCenterServiceHall()
  console.log('每项数据', row)
  let params = {
    orderSource: 'WEB',
    serviceHallId: row.serviceHallId
  }
  BaseService.postN('/userw/serviceHall/queryLocations', params).then((res: any) => {
    if (res && res.code === 0) {
      // ElMessage.success('操作成功')
      // getList()
      // cancel()
      addForm.value.locationModels = res.data
    } else {
      ElMessage.error(res.message)
    }
  })
  if (row.superServiceHallId) {
    isFirstDot.value = false
  } else {
    isFirstDot.value = true
  }
  const data = toRaw(row)
  typeOption.value = 'edit'
  addForm.value = {
    ...addForm.value,
    ...data,
    serviceHallId: row.serviceHallId,
  }
  crudRef.value.title = '编辑'
  crudRef.value.dialogFormVisible = true
}
// 删除
function handleDetele(row: IObject) {  
  if (row.superServiceHallId) {
    isFirstDot.value = false
  } else {
    isFirstDot.value = true
  }
  ElMessageBox.confirm('确定要操作么？', '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error',
  })
    .then(() => {
      BaseService.postN('/userw/serviceHall/serviceHallDelete', {
        status: row.state==='ENABLE'?'DISABLE':'ENABLE',
        serviceHallId: row.serviceHallId,
        orderSource: 'WEB',
        id: row.id,
      }).then((res: any) => {
        if (res && res.code === 0) {
          getList()
          ElMessage.success(row.state==='ENABLE'?'禁用成功':'启用成功')
        } else {
          ElMessage.error(res.message)
        }
      })
    })
    .catch(() => {
      console.log('====取消')
    })
}

// 取消
function cancel() {
  addForm.value = JSON.parse(JSON.stringify(initItem)) //清空数据
  dataFormRef.value.resetFields()
  crudRef.value.reset()
  crudRef.value.dialogFormVisible = false
  typeOption.value = ''
  crudRef.value.title = ''
  parentSelectList.value = []
}
</script>
<style lang="scss" scoped></style>
