<template>
  <div class="app-container">
     <!-- 步骤条 -->
    <el-row style="margin-bottom: 30px">
      <el-col :span="24">
        <Step :stepList="stepList"></Step>
      </el-col>
    </el-row>
    <!-- 条件查询 -->
    <el-row>
      <el-col :span="24">
        <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
          label-width="70px"
        >
          <el-form-item
            ><el-button type="primary" icon="Plus" @click="handleAdd"
              >新建FNA</el-button
            ></el-form-item
          >

          <el-form-item label="创建时间" style="width: 300px">
            <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="FNA编号" prop="tenantName">
            <el-input
              v-model="queryParams.tenantName"
              placeholder="请输入FNA编号"
              clearable
              style="width: 150px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="姓名" prop="contactName">
            <el-input
              v-model="queryParams.contactName"
              placeholder="请输入姓名"
              clearable
              style="width: 100px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="租户状态"
              clearable
              style="width: 100px"
            >
              <el-option
                v-for="dict in sys_status"
                :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-form-item>
        </el-form>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="tenantList"
      @selection-change="tableSelect"
      :default-sort="{ prop: 'createTime', order: 'descending' }"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="FNA编号" align="center" prop="tenantName" />
      <el-table-column label="预约编号" align="center" prop="tenantName" />
      <el-table-column label="新单编号" align="center" prop="contactName" />
      <el-table-column label="保单号" align="center" prop="contactPhone" />

      <el-table-column label="客户姓名" align="center" prop="maxProject" />

      <el-table-column label="状态" align="center">
        <template #default="scope">
          <span v-if="scope.row.status == 0">
            <span style="color: #ff7d00" class="iconfont icon-yanqiweiwancheng"></span> 未完成
          </span>
          <span v-if="scope.row.status == 1"
            ><span style="color: #43cf7c" class="iconfont icon-yiwancheng"></span> 已完成
          </span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" sortable align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button link type="primary" @click="handlePermission(scope.row)">查看</el-button>
          <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total >= 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 下一步到预约 -->
    <div class="bottomBtn">
      <el-button type="primary" @click="goToAppointment">下一步</el-button>
    </div>
    <!-- 添加或修改租户对话框 -->
    <el-dialog :title="title" v-model="open" width="650px" append-to-body>
      <el-form :model="form" :rules="rules" ref="tenantRef" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="租户名称" prop="tenantName">
              <el-input v-model="form.tenantName" placeholder="请输入租户名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人姓名" prop="contactName">
              <el-input v-model="form.contactName" placeholder="请输入联系人姓名" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系邮箱" prop="contactEmail">
              <el-input v-model="form.contactEmail" placeholder="请输入联系邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属行业" prop="industry">
              <el-input v-model="form.industry" placeholder="请输入所属行业" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入联系地址" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="最大项目数" prop="maxProject">
              <el-input v-model="form.maxProject" placeholder="请输入最大项目数" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大用户数" prop="maxUser">
              <el-input v-model="form.maxUser" placeholder="请输入最大用户数" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="服务到期时间" prop="expireTime">
              <el-date-picker
                v-model="form.expireTime"
                type="datetime"
                placeholder="选择到期日期"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <!--                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>-->
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="租户LOGO">
              <el-input v-model="form.logoUrl" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </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="Appointment">
import Step from '@/views/components/moduleStep'
import { getToken } from '@/utils/auth'
import useAppStore from '@/store/modules/app'
import {
  changeUserStatus,
  listTenant,
  resetUserPwd,
  delUser,
  getTenant,
  updateTenant,
  addTenant,
  changeTenantStatus
} from '@/api/system/tenant'
import useUserStore from '@/store/modules/user'

const stepList = ref([
  { title: 'FNA', id: 1, finish: true, todo: false, unFinish: false },
  { title: '预约', id: 2, todo: true, finish: false, unFinish: false },
  { title: '新单跟进', id: 3, finish: false, todo: false, unFinish: true }
])
const userStore = useUserStore()
const router = useRouter()
const appStore = useAppStore()
const { proxy } = getCurrentInstance()
const { sys_status, sys_scope, sys_no_yes } = proxy.useDict('sys_status', 'sys_scope', 'sys_no_yes')

const tenantList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const dateRange = ref([])
const deptName = ref('')
const deptOptions = ref(undefined)
const enabledDeptOptions = ref(undefined)
const initPassword = ref(undefined)
const postOptions = ref([])
const roleOptions = ref([])
const selectIdsList = ref([])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 8,
    loginTenantBizId: userStore.currentTenant.apiLoginTenantInfoResponse.tenantBizId,
    tenantName: undefined,
    contactName: undefined,
    contactPhone: undefined,
    status: undefined
  },
  rules: {
    tenantName: [{ required: true, message: '租户名称不能为空', trigger: 'blur' }],
    contactEmail: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
    contactPhone: [
      { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ]
  }
})

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

/** 多选框选中数据 */
function tableSelect(selection) {
  selectIdsList.value = selection.map(item => item.projectBizId)
}
/** 查询租户列表 */
function getList() {
  loading.value = true
  listTenant(queryParams.value).then(response => {
    tenantList.value = response.data.records
    total.value = response.data.total
    loading.value = false
  })
}

/** 过滤禁用的部门 */
function filterDisabledDept(deptList) {
  return deptList.filter(dept => {
    if (dept.disabled) {
      return false
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children)
    }
    return true
  })
}

/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.deptId = data.id
  handleQuery()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm('queryRef')
  handleQuery()
}

/** 删除按钮操作 */
function handleDelete(row) {
  const userIds = row.userId || ids.value
  proxy.$modal
    .confirm('是否确认删除用户编号为"' + userIds + '"的数据项？')
    .then(function () {
      return delUser(userIds)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'system/user/export',
    {
      ...queryParams.value
    },
    `user_${new Date().getTime()}.xlsx`
  )
}

/** 租户状态修改  */
function handleStatusChange(row, event) {
  let text = row.status === 0 ? '停用' : '启用'
  const tenantName = row.tenantName
  proxy.$modal
    .confirm(`确认要${text}"${tenantName}"租户吗?`)
    .then(() => changeTenantStatus({ tenantBizId: row.tenantBizId, status: row.status }))
    .then(() => proxy.$modal.msgSuccess(`${text}成功`))
    .catch(() => {
      // 操作取消时恢复原状态
      row.status = row.status === 0 ? 1 : 0
    })
}

/** 更多操作 */
function handleCommand(command, row) {
  switch (command) {
    case 'handleResetPwd':
      handleResetPwd(row)
      break
    case 'handleAuthRole':
      handleAuthRole(row)
      break
    default:
      break
  }
}

/** 跳转角色分配 */
function handleAuthRole(row) {
  const userId = row.userId
  router.push('/system/user-auth/role/' + userId)
}

/** 重置密码按钮操作 */
function handleResetPwd(row) {
  proxy
    .$prompt('请输入"' + row.userName + '"的新密码', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: '用户密码长度必须介于 5 和 20 之间',
      inputValidator: value => {
        if (/<|>|"|'|\||\\/.test(value)) {
          return '不能包含非法字符：< > " \' \\\ |'
        }
      }
    })
    .then(({ value }) => {
      resetUserPwd(row.userId, value).then(response => {
        proxy.$modal.msgSuccess('修改成功，新密码是：' + value)
      })
    })
    .catch(() => {})
}

/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.userId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`)
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs['uploadRef'].handleRemove(file)
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      '</div>',
    '导入结果',
    { dangerouslyUseHTMLString: true }
  )
  getList()
}

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs['uploadRef'].submit()
}

/** 重置操作表单 */
function reset() {
  form.value = {
    tenantBizId: undefined,
    tenantName: undefined,
    logoUrl: undefined,
    contactName: undefined,
    contactPhone: undefined,
    contactEmail: undefined,
    industry: undefined,
    address: undefined,
    status: '0',
    expireTime: undefined,
    maxProject: undefined,
    maxUser: undefined
  }
  proxy.resetForm('tenantRef')
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加租户'
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const tenantBizId = row.tenantBizId
  getTenant(tenantBizId).then(response => {
    form.value = response.data
    open.value = true
    title.value = '修改用户'
  })
}

/** 分配权限 */
function handlePermission(row) {
  router.push(`/system/tenant/permission?tenantBizId=` + row.tenantBizId)
}

/** 新增或者修改租户提交按钮 */
function submitForm() {
  proxy.$refs['tenantRef'].validate(valid => {
    if (valid) {
      if (form.value.tenantBizId != undefined) {
        updateTenant(form.value).then(response => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addTenant(form.value).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

getList()
</script>
<style lang="scss" scoped>
/* ::v-deep .el-step__head.is-success {
  color: none !important;
  background-color: #e8f3ff !important;
  border: none !important;
} */
/* ::v-deep .el-step__icon {
 background-color: #e8f3ff !important;
} */
.bottomBtn {
  width: 100%;
  text-align: right;
  margin-top: 20px;
}
</style>
