<template>
  <div class="w-full h-full bg-white p-4">
    <p class="font-bold text-lg leading-10 border-b-2">负责客户配置</p>
    <el-form class="pt-4" :inline="true" :model="formState">
      <el-form-item label="客户">
        <el-input v-model="formState.customerId_dictText" placeholder="" readonly>
          <template #append>
            <el-button :icon="MoreFilled" @click="openModal('search')"></el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="用户">
        <el-input v-model="formState.userId_dictText" placeholder="">
          <template #append>
            <el-button :icon="MoreFilled" @click="openUserModal('search')"></el-button>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="default" @click="onReset">重置</el-button>
        <el-button type="primary" @click="onQuery">查询</el-button>
      </el-form-item>
    </el-form>

    <div class="">
      <vxe-toolbar>
        <template #buttons>
          <!-- <vxe-button @click="allAlign = 'left'">居左</vxe-button> -->
          <el-button type="primary" @click="showEdit = true">新增</el-button>
          <el-button type="danger" @click="removeRows">删除</el-button>
        </template>
      </vxe-toolbar>
      <vxe-table
        ref="xTable"
        size="small"
        min-height="460"
        border
        :loading="loading"
        :data="tableData"
      >
        <vxe-column type="checkbox" width="50"></vxe-column>
        <vxe-column field="customerId_dictText" title="客户名称"></vxe-column>
        <vxe-column field="userId_dictText" title="用户名称"></vxe-column>
        <vxe-column field="action" title="操作" width="100">
          <template #default="{ row }">
            <el-button type="primary" text size="small" @click="editRow(row)">修改</el-button>
          </template>
        </vxe-column>
      </vxe-table>

      <vxe-pager
        size="small"
        background
        v-model:current-page="formState.currentPage"
        v-model:page-size="formState.pageSize"
        :total="formState.total"
        @page-change="onQuery"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes', 'FullJump', 'Total']"
      >
      </vxe-pager>
    </div>

    <vxe-modal
      :z-index="1005"
      v-model="showEdit"
      title="编辑&保存"
      destroy-on-close
      esc-closable
      @hide="onHide"
    >
      <template #default>
        <el-form ref="formRef" label-width="90px" :model="formEdit" :rules="formRules">
          <el-form-item label="客户" prop="customerId_dictText">
            <el-input v-model="formEdit.customerId_dictText" disabled>
              <template #append>
                <el-button :icon="MoreFilled" @click="openModal('edit')"></el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="用户" prop="userId_dictText">
            <el-input v-model="formEdit.userId_dictText" disabled>
              <template #append>
                <el-button :icon="MoreFilled" @click="openUserModal('edit')"></el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit" :loading="saveLoading">提交</el-button>
            <el-button @click="showEdit = false">取消</el-button>
          </el-form-item>
        </el-form>
      </template>
    </vxe-modal>

    <CustomerModal v-model:visible="visibleModal" @confirm="confirmCustomer" />
    <UserModal v-model:visible="visibleUserModal" @confirm="confirmUser" />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { VxeTableInstance } from 'vxe-table'

import { MoreFilled } from '@element-plus/icons-vue'
import CustomerModal from '@/components/CustomerModal/CustomerModal.vue'
import UserModal from '@/components/UserModal/UserModal.vue'
import { useRoute } from 'vue-router'
import {
  getUserOrderFileConfPage,
  editUserOrderFileConf,
  addUserOrderFileConf,
  deleteUserOrderFileConfByIds
} from '@/api/customer'

const visibleModal = ref(false)
const loading = ref(false)
const saveLoading = ref(false)
const showEdit = ref(false)
const visibleUserModal = ref(false)
const formState = reactive({
  customerId_dictText: '',
  userId_dictText: '',
  customerId: '',
  userId: '',
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const modalType = ref('')
const formRef = ref()
const xTable = ref<VxeTableInstance>()
const formRules = reactive({
  userId_dictText: [{ required: true, message: '请选择邮箱客户', trigger: 'change' }],
  customerId_dictText: [{ required: true, message: '请选择邮箱客户', trigger: 'change' }]
})
const formEdit = reactive<Record<string, any>>({
  customerId_dictText: '',
  customerId: '',
  userId: '',
  userId_dictText: ''
})

const tableData = ref([])
const onHide = () => {
  // 重置表单
  Object.assign(formEdit, {
    customerId_dictText: '',
    userId_dictText: '',
    userId: '',
    customerId: ''
  })
}

const onReset = () => {
  Object.assign(formState, {
    customerId: '',
    customerId_dictText: '',
    userId: '',
    userId_dictText: ''
  })
}

const openModal = (type: string) => {
  visibleModal.value = true
  modalType.value = type
}
const openUserModal = (type: string) => {
  visibleUserModal.value = true
  modalType.value = type
}

const editRow = (row) => {
  Object.assign(formEdit, row)
  showEdit.value = true
}

const removeRows = async () => {
  const list = xTable.value?.getCheckboxRecords()
  if (list?.length) {
    const ids = list.map((item) => item.userOrderFileId).join(',')
    await deleteUserOrderFileConfByIds(ids)
    ElMessage.success('删除成功！')
    onQuery()
  }
}

// 表单提交
const onSubmit = async () => {
  await formRef.value.validate()
  saveLoading.value = true
  try {
    formEdit?.userOrderFileId
      ? await editUserOrderFileConf(formEdit)
      : await addUserOrderFileConf(formEdit)
    ElMessage.success('操作成功！')
    showEdit.value = false
    onQuery()
  } catch {}
  saveLoading.value = false
}
const confirmCustomer = (list: any) => {
  const [item] = list
  if (!item) return
  if (modalType.value === 'search') {
    formState.customerId = item.customerId
    formState.customerId_dictText = item.customerName
  } else {
    formEdit.customerId = item.customerId
    formEdit.customerId_dictText = item.customerName
  }
}

const confirmUser = (list: any) => {
  const [item] = list
  if (!item) return
  if (modalType.value == 'edit') {
    formEdit.userId = item.userId
    formEdit.userId_dictText = item.nickName
  } else {
    formState.userId = item.userId
    formState.userId_dictText = item.nickName
  }
}

const onQuery = async () => {
  loading.value = true
  try {
    const { data } = await getUserOrderFileConfPage(formState)
    tableData.value = data.result.records
    formState.total = +data.result.total
  } catch {}
  loading.value = false
}

onMounted(() => {
  // Object.assign(formState, route.query)
  onQuery()
})
</script>
<style lang="scss" scoped></style>
