<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.productName" placeholder="产品名称" clearable />
      </el-form-item>
      <el-form-item label="客户名称">
        <el-input v-model="formState.customerName" 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>
          <!-- <vxe-button @click="allAlign = 'left'">居左</vxe-button> -->
          <el-button type="primary" @click="showEdit = true">新增</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="productCompareId" title="产品对照id" width="200"></vxe-column> -->
        <vxe-column field="productName" title="产品名称" width="200"></vxe-column>
        <vxe-column field="customerName" title="客户名称" width="200"></vxe-column>

        <vxe-column field="fileds" title="产品对照字段配置">
          <template #default="{ row }">
            <span
              class="inline-block mr-2"
              v-for="item in row.fileds"
              :key="item.productCompareFiledId"
            >
              {{ `${item.productFiledTitle}=${item.productFiledValue}` }}
            </span>
          </template>
        </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
      v-model="showEdit"
      width="700"
      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="12">
              <el-form-item label="产品名称" prop="productName">
                <el-input v-model="formEdit.productName" disabled>
                  <template #append>
                    <el-button :icon="MoreFilled" @click="prodVisible = true" />
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户名称" prop="customerName">
                <el-input v-model="formEdit.customerName" disabled>
                  <template #append>
                    <el-button :icon="MoreFilled" @click="customerVisible = true" />
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <p class="font-bold border-b-2 mb-2 text-base">对照字段配置</p>

          <el-scrollbar height="300" class="no-rule-container">
            <template v-for="(item, idx) in formEdit.fileds">
              <el-row>
                <el-form-item label="产品字段">
                  <el-select
                    v-model="item.productFiled"
                    @change="(v) => productFiledChange(v, item)"
                  >
                    <template v-for="field in orderFields">
                      <el-option
                        :disabled="!!field.disabled"
                        :label="field.fliedTitle"
                        :value="field.filedName"
                      ></el-option>
                    </template>
                  </el-select>
                </el-form-item>

                <el-form-item label="字段值">
                  <el-input v-model="item.productFiledValue"></el-input>
                </el-form-item>

                <el-form-item>
                  <el-button
                    v-if="idx === 0"
                    type="primary"
                    :icon="Plus"
                    circle
                    @click="addField"
                  ></el-button>
                  <el-button
                    v-else-if="idx !== 0"
                    type="danger"
                    :icon="Delete"
                    circle
                    @click="removeField(idx)"
                  ></el-button>
                </el-form-item>
              </el-row>
            </template>
          </el-scrollbar>

          <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 { getProductCompareList, saveProductCompare } from '@/api/product'
import { apiGetOrderField } from '@/api/excel'
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 formState = reactive({
  productName: '',
  customerName: '',
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const orderFields = ref<Record<string, any>>([])

const formRef = ref()
const xTable = ref<VxeTableInstance>()
const formRules = reactive({
  productName: [{ required: true, message: '请输入产品名称', trigger: 'change' }]
})
const formEdit = reactive({
  productCompareId: null,
  customerId: '',
  customerName: '',
  productName: '',
  productId: '',
  fileds: [
    {
      productCompareFiledId: null,
      productCompareId: null,
      productFiled: '',
      productFiledTitle: '',
      productFiledValue: ''
    }
  ]
})

const selectedFields = computed(() => {
  return formEdit.fileds.map((v) => v.productFiled)
})

watch(
  selectedFields,
  (val) => {
    orderFields.value.forEach((item: any) => {
      if (val.includes(item.filedName)) {
        item.disabled = true
      } else {
        item.disabled = false
      }
    })
  },
  { deep: true }
)

const tableData = ref([])
const onHide = () => {
  // 重置表单
  Object.assign(formEdit, {
    productCompareId: null,
    customerId: '',
    customerName: '',
    productName: '',
    productId: '',
    fileds: [
      {
        productCompareFiledId: null,
        productCompareId: null,
        productFiled: '',
        productFiledTitle: '',
        productFiledValue: ''
      }
    ]
  })
}

const addField = () => {
  formEdit.fileds.splice(1, 0, {
    productCompareFiledId: null,
    productCompareId: null,
    productFiled: '',
    productFiledTitle: '',
    productFiledValue: ''
  })
}
const removeField = (idx: number) => formEdit.fileds.splice(idx, 1)
const productFiledChange = (v: string | undefined, item: any) => {
  if (v) {
    item.productFiledTitle = orderFields.value.find((_) => _.filedName == v)?.fliedTitle || ''
  }
}

const onReset = () => {}

// 表单提交
const onSubmit = async () => {
  await formRef.value.validate()
  saveLoading.value = true
  const params = {
    productCompare: {
      productCompareId: formEdit.productCompareId,
      customerId: formEdit.customerId,
      productId: formEdit.productId
    },
    fileds: formEdit.fileds
  }
  try {
    await saveProductCompare(params)
    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') {
    console.log('type', type, item)
    form.productId = item.productId
    form.productName = item.productName
  } else {
    form.customerId = item.customerId
    form.customerName = item.customerName
  }
}

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

onMounted(() => {
  onQuery()
  apiGetOrderField().then(({ data }) => {
    orderFields.value = data.result
  })
})
</script>
<style lang="scss" scoped></style>
