<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.productId_dictText" readonly placeholder="产品名称" clearable>
          <template #append>
            <el-button :icon="MoreFilled" @click="openModal('prod', 'search')" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="客户名称">
        <el-input v-model="formState.customerId_dictText" readonly placeholder="客户名称" clearable>
          <template #append>
            <el-button :icon="MoreFilled" @click="openModal('cust', 'search')" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="产品描述">
        <el-input v-model="formState.excelFiled" placeholder="产品描述" clearable />
      </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>
          <el-button type="primary" @click="openFormModal">新增</el-button>
          <el-button type="danger" @click="deleteRows">删除</el-button>
        </template>
      </vxe-toolbar>
      <vxe-table
        ref="xTable"
        size="mini"
        min-height="460"
        border
        show-overflow="tooltip"
        :loading="loading"
        :data="tableData"
      >
        <vxe-column type="checkbox" width="50"></vxe-column>
        <vxe-column field="productId_dictText" title="产品名称" width="200"></vxe-column>
        <vxe-column field="customerId_dictText" title="客户名称" width="200"></vxe-column>
        <vxe-column field="excelFiled" title="产品描述"></vxe-column>
        <vxe-column title="操作" width="90">
          <template #default="{ row }">
            <el-link type="primary" style="font-size: 12px" @click="toEdit(row)">修改</el-link>
          </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
      v-model="showEdit"
      width="400"
      title="编辑&保存"
      destroy-on-close
      esc-closable
      @hide="onHide"
      :z-index="1001"
    >
      <template #default>
        <el-form
          ref="formRef"
          size="small"
          inline
          label-width="80px"
          :model="formEdit"
          :rules="formRules"
        >
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="产品名称" prop="productId_dictText">
                <el-input v-model="formEdit.productId_dictText" disabled>
                  <template #append>
                    <el-button :icon="MoreFilled" @click="openModal('prod', 'edit')" />
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="客户名称" prop="customerId_dictText">
                <el-input v-model="formEdit.customerId_dictText" disabled>
                  <template #append>
                    <el-button :icon="MoreFilled" @click="openModal('cust', 'edit')" />
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="24">
              <el-form-item label="产品单位" prop="customerUnit">
                <el-input v-model="formEdit.customerUnit"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="单位" prop="unit">
                <el-input v-model="formEdit.unit"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="换算值" prop="unitRatio">
                <el-input type="number" v-model="formEdit.unitRatio"></el-input>
              </el-form-item>
            </el-col> -->
            <el-col :span="24">
              <el-form-item label="产品描述" prop="excelFiled">
                <el-input
                  style="width: 250px"
                  type="textarea"
                  :rows="5"
                  v-model="formEdit.excelFiled"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row type="flex" justify="center">
            <el-button size="default" type="primary" @click="onSubmit" :loading="saveLoading"
              >提交</el-button
            >
            <el-button size="default" @click="showEdit = false">取消</el-button>
          </el-row>
        </el-form>
      </template>
    </vxe-modal>

    <ProductModal v-model:visible="prodVisible" @confirm="(list) => confirmModal(list, 'prod')" />
    <CustomerModal
      v-model:visible="customerVisible"
      @confirm="(list) => confirmModal(list, 'customer')"
    />
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref, unref, watch } from 'vue'
import {
  deleteExcelProdFileConfByIds,
  getExcelProdFileConfPage,
  saveExcelProdFileConf,
  editExcelProdFileConf
} from '@/api/product'
import { ElMessage } from 'element-plus'
import type { VxeTableInstance } from 'vxe-table'
import { MoreFilled, Delete, Plus } from '@element-plus/icons-vue'
import ProductModal from '@/components/ProductModal/ProductModal.vue'
import CustomerModal from '@/components/CustomerModal/CustomerModal.vue'

const customerVisible = ref(false)
const prodVisible = ref(false)
const loading = ref(false)
const saveLoading = ref(false)
const showEdit = ref(false)
const optType = ref('add')
const formState = reactive({
  productId_dictText: '',
  productId: '',
  customerId: '',
  customerId_dictText: '',
  excelFiled: '',
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const formRef = ref()
const xTable = ref<VxeTableInstance>()
const formRules = reactive({
  productId_dictText: [{ required: true, message: '请输入产品名称', trigger: 'change' }],
  excelFiled: [{ required: true, message: '请输入产品描述', trigger: 'change' }]
})
const formEdit = reactive({
  productCompareId: null,
  customerId: '',
  customerId_dictText: '',
  productId_dictText: '',
  productId: '',
  excelFiled: '',
  customerUnit: '',
  unit: '',
  unitRatio: ''
})

const deleteRows = async () => {
  const ids = xTable.value
    ?.getCheckboxRecords()
    .map((item) => {
      return item.excelProductFiledConfId
    })
    .join(',')
  const { data } = await deleteExcelProdFileConfByIds(ids as string)
  if (data.code === 200) {
    ElMessage.success(data.message || '删除成功！')
    onQuery()
  } else {
    ElMessage.error(data.message || '删除失败！')
  }
}
const toEdit = (row: any) => {
  optType.value = 'edit'
  Object.assign(formEdit, row)
  showEdit.value = true
}
const modaltype = ref('search')
const openModal = (modal, type) => {
  if (modal == 'prod') {
    prodVisible.value = true
  } else {
    customerVisible.value = true
  }
  modaltype.value = type
}

const openFormModal = () => {
  optType.value = 'add'
  showEdit.value = true
}

const tableData = ref([])
const onHide = () => {
  // 重置表单
  Object.assign(formEdit, {
    productCompareId: null,
    excelProductFiledConfId: null,
    customerId: '',
    customerId_dictText: '',
    productId_dictText: '',
    productId: '',
    excelFiled: '',
    customerUnit: '',
    unit: '',
    unitRatio: ''
  })

  console.log(formEdit, 'formEdit--onhide')
}

const onReset = () => {
  Object.assign(formState, {
    customerId: '',
    customerId_dictText: '',
    productId: '',
    productId_dictText: '',
    excelFiled: ''
  })
}

// 表单提交
const onSubmit = async () => {
  await formRef.value.validate()
  saveLoading.value = true

  try {
    optType.value == 'add'
      ? await saveExcelProdFileConf(formEdit)
      : await editExcelProdFileConf(formEdit)
    ElMessage.success('操作成功！')
    showEdit.value = false
    onQuery()
  } catch {}
  saveLoading.value = false
}

const confirmModal = (list: any, type: 'prod' | 'customer') => {
  const [item] = list
  if (!item) return
  const form = unref(formEdit)
  if (type === 'prod') {
    if (modaltype.value == 'edit') {
      form.productId = item.productId
      form.productId_dictText = item.productName
    } else {
      formState.productId = item.productId
      formState.productId_dictText = item.productName
    }
  } else {
    if (modaltype.value == 'edit') {
      form.customerId = item.customerId
      form.customerId_dictText = item.customerName
    } else {
      formState.customerId = item.customerId
      formState.customerId_dictText = item.customerName
    }
  }
}

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

onMounted(() => {
  onQuery()
})
</script>
<style lang="scss" scoped></style>
