<script setup lang="ts">
import { onBeforeUnmount, reactive, ref, inject } from 'vue'
import emitter from '/@/utils/emitter'
import type { FormInstance, FormRules } from 'element-plus'
import ProductDialogList from './ProductDialogList.vue'
import { postCreateProductLine, getProductDetail, postUpdateProductLine } from '/@/views/productCenter/productList/api'
import { ElMessage } from 'element-plus'

const profile = <any>inject('profile')

const createProductDialog = ref(false)
const load = ref(false)
let asinList = []
let productlineId = ''
const isUpdate = ref(false)

emitter.on('open-productLine-dialog', (value: any) => {
  createProductDialog.value = value.isVisible
})

emitter.on('ProductList-asinList', (value: any) => {
  asinList = value
})

emitter.on('ProductTab-editProductCard', (value: any) => {
  productlineId = value.data.productlineId
  fetchProductDetail()

  isUpdate.value = true
  createProductDialog.value = value.isVisible
  ruleForm.productLineName = value.data.productlineName
})

async function fetchProductDetail() {
  const query = {
    profileId: profile.value.profile_id,
    productlineId: productlineId,
  }
  try {
    const response = await getProductDetail(query)
    emitter.emit('ProductLineDialog-sendDetailData', { data: response.data })
  } catch (error) {
    console.log('error:', error)
  }
}

async function updateProductLine() {
  const body = {
    profileId: profile.value.profile_id,
    productLineName: ruleForm.productLineName,
    asinList: asinList,
  }
  try {
    const response = await postUpdateProductLine(body)
    if (response.data.code == 'success') {
      ElMessage.success('更新成功')
    } else if (response.data.code == 'error') {
      ElMessage.warning(`${response.data.description}`)
    } else {
      ElMessage.error('更新失败')
    }
  } catch (error) {
    console.log('error:', error)
  }
}
let isClose = false
function closeDialog() {
  isClose = true
  isUpdate.value = false
  ruleForm.productLineName = ''
  emitter.emit('ProductLineDialog-closeDialog', { clear: true })
}

// 表单相关
interface RuleForm {
  productLineName: string
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  productLineName: '',
})

const rules = reactive<FormRules<RuleForm>>({
  productLineName: [{ required: true, message: '请输入产品线名称', trigger: 'blur' }],
})

const updateForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      updateProductLine()
    } else {
      console.log('error submit!', fields)
    }
  })
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log('submit!')
      await createProductLine()
      emitter.emit('ProductLineDialog-reloading', { reloading: true })
    } else {
      console.log('error submit!', fields)
    }
  })
}

async function createProductLine() {
  load.value = true
  const body = {
    profileId: profile.value.profile_id,
    productLineName: ruleForm.productLineName,
    asinList: asinList,
  }
  try {
    const response = await postCreateProductLine(body)
    if (response.data.code == 'success') {
      ElMessage.success('创建成功')
    } else if (response.data.code == 'error') {
      ElMessage.warning(`${response.data.description}`)
    } else {
      ElMessage.error('创建失败')
    }
  } catch (error) {
    console.log('error:', error)
  } finally {
    load.value = false
  }
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

onBeforeUnmount(() => {
  emitter.all.clear()
})
</script>

<template>
  <el-dialog v-model="createProductDialog" @close="closeDialog" title="新建产品线" width="1300">
    <el-form
      v-loading="load"
      ref="ruleFormRef"
      class="custom-ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      size="default"
      label-position="top"
      status-icon>
      <el-form-item prop="productLineName">
        <template #label>
          <span class="form-label"> 产品线名称: </span>
        </template>
        <el-input v-model="ruleForm.productLineName" show-word-limit placeholder="请输入产品线名称" maxlength="150" style="width: 500px" />
      </el-form-item>
      <el-form-item required>
        <template #label>
          <span class="form-label"> 商品: </span>
        </template>
        <ProductDialogList></ProductDialogList>
      </el-form-item>
      <el-form-item>
        <div style="display: flex; flex-direction: row-reverse">
          <el-button v-if="!isUpdate" style="margin-left: 10px" color="#3c59b0" @click="submitForm(ruleFormRef)"> 创建 </el-button>
          <el-button v-if="isUpdate" style="margin-left: 10px" color="#3c59b0" @click="updateForm(ruleFormRef)"> 确定 </el-button>
          <el-button plain @click="createProductDialog = false">取消</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped>
/* 不要删除, 否则ProductList组件的样式会错乱 */
::v-deep(.el-form-item__content) {
  display: block !important;
}
.form-label {
  font-weight: 500;
  color: #505968;
}
</style>
