<template>
  <div class='app-container'>
    <el-form inline>
      <el-form-item label="企业ID：">
        <el-input v-model="data.form.id" placeholder="请输入企业ID" clearable />
      </el-form-item>
      <el-form-item label="企业名称：">
        <el-input v-model="data.form.name" placeholder="请输入企业名称" clearable />
      </el-form-item>
      <el-form-item label="行业：">
        <el-select v-model="data.form.organizationIndustryId" placeholder="请选择行业" clearable>
          <el-option v-for="item in classOptions" :key="item.id" :value="item.id" :label="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getSearch">搜索</el-button>
        <el-button icon="Refresh" @click="getRefresh">重置</el-button>
        <el-button type="warning" plain icon="Download" @click="getExport" :disabled="ids === ''">导出</el-button>
        <el-button type="primary" plain icon="Plus" @click="getDialog()"
          v-hasPermi="['business:list:add']">新增</el-button>
      </el-form-item>
    </el-form>
    <!-- 列表 -->
    <el-table :data="data.tableData" ref="tableData" v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="企业ID" prop="id" align="center"></el-table-column>
      <el-table-column label="企业名称" prop="name" align="center"></el-table-column>
      <el-table-column label="企业管理员" prop="userName" align="center"></el-table-column>
      <el-table-column label="联系方式" prop="phone" align="center"></el-table-column>
      <el-table-column label="上级企业" prop="parentName" align="center"></el-table-column>
      <el-table-column label="当前状态" prop="status" align="center">
        <template #default="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
            :before-change="() => beforeChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="行业" prop="organizationIndustryName" align="center" />
      <el-table-column label="创建时间" prop="createTimeStr" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="getDialog(scope.row.id, '编辑')"
            v-hasPermi="['business:list:edit']">编辑</el-button>
          <el-button type="primary" link @click="getReset(scope.row)"
            v-hasPermi="['business:list:refresh']">重置密码</el-button>
          <el-button type="danger" link @click="getDelete(scope.row)"
            v-hasPermi="['business:list:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="data.form.pageNum" v-model:limit="data.form.pageSize"
      @pagination="getList" />
    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="500" :before-close="getClose">
      <el-form ref="dialogForm" :model="data.dialogForm" :rules="data.rules" label-width="100px">
        <el-form-item label="公司名称：" prop="name">
          <el-input v-model="data.dialogForm.name" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="营业执照：" prop="businessLicense">
          <CustomUpload listType="picture-card" :src="data.dialogForm.businessLicense" @upload="upload" />
        </el-form-item>
        <el-form-item label="行业：" prop="organizationIndustryId">
          <el-select v-model="data.dialogForm.organizationIndustryId" placeholder="请选择行业">
            <el-option v-for="item in classOptions" :key="item.id" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式：" prop="phone">
          <el-input v-model="data.dialogForm.phone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="账号名称：" prop="userName">
          <el-input v-model="data.dialogForm.userName" placeholder="<企业名>@<用户名>，例如：yundong@admin" />
        </el-form-item>
        <el-form-item label="所属企业：" prop="parentId">
          <el-select v-model="data.dialogForm.parentId" placeholder="请选择所属企业" filterable remote
            :remote-method="businessRemote" remote-show-suffix>
            <el-option v-for="item in businessData.options" :key="item.id" :value="item.id" :label="item.name"
              :disabled="disabledBusiness(item)" />
          </el-select>
        </el-form-item>
        <el-form-item label="菜单权限：">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll">全选/全不选</el-checkbox>
          <el-checkbox v-model="menuCheckStrictly" @change="handleCheckedTreeConnect">父子联动</el-checkbox>
          <el-tree class="tree-border" :data="data.treeOptions" show-checkbox ref="menuRef" node-key="id"
            :check-strictly="!menuCheckStrictly" empty-text="加载中，请稍候"
            :props="{ label: 'label', children: 'children' }" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="getClose">取消</el-button>
        <el-button type="primary" @click="getSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { list, detail, remove, submit, edit, change, reset, treeselect } from '@/api/business/list'
import { useBusinessClass, useBusinessSelect } from '@/hooks/index'
import { ElMessageBox } from 'element-plus';
import { nextTick } from 'vue';

let { proxy } = getCurrentInstance();

const { classOptions } = useBusinessClass()
const { businessData, getBusiness, businessRemote } = useBusinessSelect()
getBusiness()

const reg = ref(/1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}/)
const checkPhone = (rule, value, callback) => {
  if (value) {
    if (!reg.value.test(value)) {
      callback(new Error('请输入正确的手机号'))
    } else {
      callback()
    }
  }
}
// 遮罩层
const loading = ref(false)

const data = reactive({
  // 父表单
  form: {
    pageNum: 1,
    pageSize: 10
  },
  // 列表
  tableData: [],
  // 菜单权限
  deptOptions: [],
  // 弹窗表单
  dialogForm: {},
  // 校验
  rules: {
    name: [{
      required: true, message: "请输入公司名称", trigger: "blur"
    }],
    businessLicense: [{
      required: true, message: "请上传营业执照", trigger: "change"
    }],
    organizationIndustryId: [{
      required: true, message: '请选择行业', trigger: 'change'
    }],
    phone: [{
      required: true, message: '请输入手机号', trigger: 'blur'
    }, {
      validator: checkPhone, trigger: 'blur'
    }],
    userName: [{
      required: true, message: '请输入账号名称', trigger: 'blur'
    }],
    parentId: [{
      required: true, message: '请选择归属企业', trigger: 'change'
    }]
  }
})

const menuExpand = ref(false)
const menuNodeAll = ref(false)
const menuCheckStrictly = ref(true)

// 总数据
const total = ref(0)

// 多选
const ids = ref('')

// 列表
function getList() {
  loading.value = true
  list(data.form).then(res => {
    if (res.code === 0) {
      data.tableData = res.data
      total.value = res.total
      loading.value = false
    }
  })
}
getList()

// 搜索
function getSearch() {
  data.form.pageNum = 1
  getList()
}

// 重置
function getRefresh() {
  data.form = {
    pageNum: 1,
    pageSize: 10
  }
  getList()
}

// 列表多选
function handleSelectionChange(val) {
  let arr = []
  val.map(i => arr.push(i.id))
  ids.value = arr.join(',')
}

// 导出
function getExport() {
  proxy.download("/organization/organization/export",
    { ids: ids.value }, `business_${new Date().getTime()}.xlsx`);
}

// 修改状态
function beforeChange(row) {
  let status = row.status == 0 ? 1 : 0
  return new Promise((resolve, reject) => {
    change({ id: row.id, status: status }).then(res => {
      if (res.code === 0) {
        return resolve(true)
      }
    }).catch(() => {
      return reject()
    })
  })
}

// 弹窗
const dialogVisible = ref(false)
// 弹窗标题
const title = ref("新增")

// 打开弹窗
const getDialog = async (id, key) => {
  await getTree()
  dialogVisible.value = true
  title.value = '新增'
  if (id) {
    getDetail(id)
  }
}

// 详情
function getDetail(id) {
  title.value = '编辑'
  detail(id).then(res => {
    if (res.code === 0) {
      data.dialogForm = res.data
      let checkedKeys = res.data.menuIds
      checkedKeys.forEach(i => {
        nextTick(() => {
          proxy.$refs.menuRef.setChecked(i, true, false)
        })
      })
    }
  })
}

// 新增的菜单权限
const getTree = async () => {
  await treeselect().then(res => {
    if (res.code === 0) {
      data.treeOptions = res.data
    }
  })
}

// 上传
function upload(e) {
  data.dialogForm.businessLicense = e.file
}

// 关闭弹窗
function getClose() {
  dialogVisible.value = false
  data.dialogForm = {}
  if (proxy.$refs.menuRef != undefined) {
    proxy.$refs.menuRef.setCheckedKeys([]);
  }
  menuExpand.value = false
  menuNodeAll.value = false
  menuCheckStrictly.value = true
  proxy.$refs.dialogForm.resetFields()
}

// 提交
function getSubmit() {
  proxy.$refs.dialogForm.validate(valid => {
    if (valid) {
      data.dialogForm.menuIds = getMenuAllCheckedKeys()
      if (data.dialogForm.id) {
        edit(data.dialogForm).then(res => {
          if (res.code === 0) {
            proxy.$modal.msgSuccess("提交成功！");
            getClose()
            getList()
          }
        })
      } else {
        submit(data.dialogForm).then(res => {
          if (res.code === 0) {
            ElMessageBox.alert(`密码将通过短信方式生成！`, '提示', {
              type: 'warning',
              callback: () => {
                proxy.$modal.msgSuccess("提交成功！");
                getClose()
                getList()
              }
            })
          }
        })
      }
    } else {
      return false
    }
  })
}

// 删除
function getDelete(row) {
  proxy.$modal.confirm(`是否删除企业名称为：${row.name}的数据?`).then(() => {
    remove({ id: row.id }).then(res => {
      if (res.code === 0) {
        proxy.$modal.msgSuccess('删除成功！')
        getList()
      }
    })
  }).catch(() => { })
}

/** 所有菜单节点数据 */
function getMenuAllCheckedKeys() {
  // 目前被选中的菜单节点
  let checkedKeys = proxy.$refs.menuRef.getCheckedKeys();
  // 半选中的菜单节点el-
  let halfCheckedKeys = proxy.$refs.menuRef.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}

/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value) {
  let treeList = data.treeOptions;
  for (let i = 0; i < treeList.length; i++) {
    proxy.$refs.menuRef.store.nodesMap[treeList[i].id].expanded = value
  }
}

/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value) {
  proxy.$refs.menuRef.setCheckedNodes(value ? data.treeOptions : []);
}

/** 树权限（父子联动） */
function handleCheckedTreeConnect(value) {
  menuCheckStrictly.value = value ? true : false;
}

// 禁止选择自己为归属企业
function disabledBusiness(item) {
  if (data.dialogForm.id) {
    return data.dialogForm.id === item.value ? true : false
  }
}

// 重置密码
function getReset(row) {
  proxy.$modal.confirm(`是否要重置账号为：${row.userName}的密码?`).then(() => {
    reset({
      userId: row.userId
    }).then(res => {
      if (res.code === 0) {
        proxy.$modal.msgSuccess('短信已发送！')
      }
    })
  }).catch(() => { })
}
</script>

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