<template>
  <div class="page">
    <div class="page-top-bar flex items-center">
      <div class="title mr-50">
        {{ title }} <span v-if="postForm.id">({{ postForm.id }})</span>
      </div>
      <div v-if="postForm.checkState === 'A055_A'" class="status fs-20 flex items-center c-warning">
        <span class="fs-80 lh-60">·</span>
        <span class="text">{{ postForm.checkState_dictText }}</span
        ><span class="fw-400">（等待工作人员审核，约1-2个工作日）</span>
      </div>
      <div v-if="postForm.checkState === 'A055_B'" class="status fs-20 flex items-center c-success">
        <span class="fs-80 lh-60">·</span><span class="text">{{ postForm.checkState_dictText }}</span>
      </div>
      <div v-if="postForm.checkState === 'A055_C'" class="status fs-20 flex items-center c-danger">
        <span class="fs-80 lh-60">·</span><span class="text">{{ postForm.checkState_dictText }}</span>
        <span class="fw-400">（原因：{{ postForm.reject }}）</span>
      </div>
    </div>
    <div class="inner-page-content bg-white py-24 px-30 rounded-4">
      <a-form
        layout="vertical"
        ref="postFormRef"
        :model="postForm"
        :rules="postFormRules"
        :disabled="isPage('detail') || postForm.checkState === 'A055_A'"
      >
        <div class="part-1">
          <div class="mini-title c-333 fs-16 mb-20 font-700">基本信息</div>
          <div class="grid grid-cols-3 gap-col-100">
            <a-form-item ref="brandName" label="品牌名称（建议英文填写）" name="brandName">
              <a-input v-model:value="postForm.brandName" size="large" />
            </a-form-item>
            <a-form-item ref="registrationCode" label="注册地" name="registrationCode">
              <a-select placeholder="请选择" size="large" v-model:value="postForm.registrationCode" show-search>
                <!-- <a-select-option value="key" v-for="(label, key) in statusMap">{{label}}</a-select-option> -->
                <a-select-option :value="item.value" v-for="item in commonStore.dict[DICT_CODE.EN_COUNTRY]" :key="item.value">{{
                  item.text
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item ref="productionPlaceCode" label="产地" name="productionPlaceCode">
              <a-select placeholder="请选择" size="large" v-model:value="postForm.productionPlaceCode" show-search>
                <a-select-option :value="item.value" v-for="item in commonStore.dict[DICT_CODE.EN_COUNTRY]" :key="item.value">{{
                  item.text
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="成立时间" name="establishedDate">
              <a-date-picker
                class="w-full"
                size="large"
                v-model:value="postForm.establishedDate"
                valueFormat="YYYY-MM-DD"
                placeholder="请选择创立日期"
              />
            </a-form-item>
            <a-form-item ref="brandType" label="品牌分类" name="brandType">
              <!-- <a-select placeholder="请选择" size="large" v-model:value="postForm.brandType" mode="multiple">
                <a-select-option :value="item.key" v-for="item in commonStore.category" :key="item.key">{{
                  item.title
                }}</a-select-option>
              </a-select> -->
              <a-cascader
                v-model:value="postForm.brandType"
                style="width: 100%"
                multiple
                size="large"
                :options="commonStore.category"
                :fieldNames="{label: 'title', value: 'key'}"
                placeholder="请选择"
                :show-checked-strategy="Cascader.SHOW_CHILD"
              ></a-cascader>
              {{ postForm.brandType }}
            </a-form-item>
            <a-form-item ref="brandTag" label="品牌标签（建议英文填写）" name="brandTag">
              <a-select size="large" v-model:value="postForm.brandTag" mode="tags" placeholder="请输入"></a-select>
            </a-form-item>
            <a-form-item ref="brandTag" label="是否启用" name="brandTag">
              <a-switch
                v-model:checked="postForm.brandState"
                :disabled="isPage('add') || disabled"
                checked-children="开"
                checkedValue="A053_A"
                un-checked-children="关"
                unCheckedValue="A053_B"
              />
            </a-form-item>
          </div>
        </div>
        <div class="part-2">
          <div class="mini-title c-333 fs-16 mb-20 font-700">品牌介绍</div>
          <a-form-item ref="address" label="品牌故事（建议英文填写）" name="brandStory">
            <a-textarea v-model:value="postForm.brandStory" size="large" />
          </a-form-item>
        </div>
        <div class="part-3">
          <div class="mini-title c-333 fs-16 mb-20 font-700">图片/视频信息</div>

          <div class="flex">
            <a-form-item class="mr-100" label="品牌LOGO" name="brandLogo" extra="上传1张,最佳尺寸:100*100" tooltip="与品牌名称一起展示">
              <UploadFile :disabled="disabled" v-model:url="postForm.brandLogo"></UploadFile>
            </a-form-item>
            <a-form-item class="mr-100" label="品牌页头图" name="headeImage" extra="上传1张,最佳尺寸: 2122*480" tooltip="在品牌页详情顶部展示">
              <UploadFile :disabled="disabled" v-model:url="postForm.headeImage"></UploadFile>
            </a-form-item>
            <a-form-item
              class="mr-100"
              label="品牌缩略图"
              name="thumbnail"
              extra="上传1张,最佳尺寸: 200*200"
              tooltip="客户搜到您的品牌时在品牌列表中展示"
            >
              <UploadFile :disabled="disabled" v-model:url="postForm.thumbnail"></UploadFile>
            </a-form-item>
            <a-form-item class="mr-100" label="商标证书" name="trademarkCertificate" extra="上传1张">
              <UploadFile :disabled="disabled" v-model:url="postForm.trademarkCertificate"></UploadFile>
            </a-form-item>
          </div>

          <a-form-item
            class="mr-100"
            label="品牌图片"
            name="otherImage"
            extra="最多上传5张，最佳尺寸:500*500，单张最大为5M"
            tooltip="用于在品牌介绍页面展示"
          >
            <UploadFile :disabled="disabled" v-model:list="postForm.otherImage" fileType="image" :limit="5" :limitSize="5"></UploadFile>
          </a-form-item>

          <a-form-item label="品牌视频" name="otherVideo" extra="主图视频大小不超过50M" tooltip="用于在品牌介绍页面展示">
            <UploadFile :disabled="disabled" v-model:url="postForm.otherVideo" :limit-size="50"></UploadFile>
          </a-form-item>
        </div>

        <!-- {{ postForm }} -->
      </a-form>
      <div class="btn-footer text-center" v-if="!disabled">
        <a-button @click="submit">取消</a-button>
        <a-button type="primary" class="ml-50" @click="submit">提交</a-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { UnwrapRef } from 'vue'
import type { Rule } from 'ant-design-vue/es/form'
import type { BrandItem } from 'Types/api'
import { apiBrandAdd, apiBrandDetail, apiBrandEdit, apiToggleStatus } from '@/api/brand'
import { DICT_CODE } from '@/utils/const'
import { isPage, deepClone, mergeObj } from '@/utils'
import useCommonStore from '@/store/modules/common'
import useUserStore from '@/store/modules/user'
import { message, notification, Modal, Cascader } from 'ant-design-vue'
import type { CascaderProps } from 'ant-design-vue';
const commonStore = useCommonStore()
const userStore = useUserStore()
commonStore.getDict(DICT_CODE.EN_COUNTRY)
commonStore.getDict(DICT_CODE.BRAND_CLASS)
const router = useRouter()
const route = useRoute()

const title = computed(() => {
  if (isPage('add')) {
    return '新增品牌'
  } else if (isPage('edit')) {
    return '编辑品牌'
  } else if (isPage('detail')) {
    return '品牌详情'
  }
})
const disabled = computed(() => {
  return isPage('detail') || postForm.value.checkState === 'A055_A'
})

const postForm = ref({} as BrandItem)
postForm.value = {
  id: '',
  brandName: '',
  registrationCode: '',
  productionPlaceCode: '',
  establishedDate: '',
  brandType: [],
  brandTag: [],

  brandStory: '',

  brandLogo: '',
  headeImage: '',
  thumbnail: '',
  trademarkCertificate: '',
  otherImage: '',
  otherVideo: '',

  brandState: '',
  checkState_dictText: '',
  reject: '',
  checkState: '',
  supplierAffiliationId: userStore.userInfo.id,
  // checkState: '',
  // createType: '',
  // reject: '',
  // supplierAffiliationId: '',
  // supplierAffiliationName: '',
  // productionPlaceName: '',
  // onOrOffTime: '',
}
const postFormRules: Record<string, Rule[]> = {
  brandName: [{ required: true, message: '品牌名称未输入', trigger: 'change' }],
  registrationCode: [{ required: true, message: '注册地未输入', trigger: 'change' }],
  productionPlaceCode: [{ required: true, message: '产地未输入', trigger: 'change' }],
  establishedDate: [{ required: true, message: '成立日期未输入', trigger: 'change' }],
  brandType: [{ required: true, message: '品牌分类未选择', trigger: 'change' }],
  brandTag: [{ required: true, message: '品牌标签未输入', trigger: 'change' }],
  brandStory: [{ required: true, message: '品牌故事未输入', trigger: 'change' }],
  brandLogo: [{ required: true, message: '品牌logo未上传', trigger: 'change' }],
  headeImage: [{ required: true, message: '品牌页头图未上传', trigger: 'change' }],
  thumbnail: [{ required: true, message: '品牌缩略图未上传', trigger: 'change' }],
  trademarkCertificate: [{ required: true, message: '商标证书未上传', trigger: 'change' }],
}
onMounted(() => {
  init()
})
const init = () => {
  route.query.id && getInfo()
}

const getInfo = () => {
  apiBrandDetail({ id: route.query.id }).then((res) => {
    console.log('---- 获取详情 ----', res)
    const data = res.data.result
    mergeObj(postForm.value, data)
    postForm.value.brandType = data.brandType.split(',')
    postForm.value.brandTag = data.brandTag.split(',')
  })
}

// const handleUploadSuccess = (data) => {
//   // postForm.address = data.address
//   // postForm.name = data.companyName
//   // postForm.legalMan = data.legalMan
//   // postForm.regCode = data.regCode
// }

const postFormRef = ref()
const submit = () => {
  postFormRef.value.validate().then(async () => {
    const params = deepClone(postForm.value)
    console.log('---- postForm ----', params)
    params.brandTag = params.brandTag.join(',')
    params.brandType = params.brandType.join(',')
    if (isPage('add')) {
      apiBrandAdd(params).then((res) => {
        if (res.data.code === 200) {
          notification.success({
            message: '提示',
            description: '添加成功!',
          })
          router.push('/brand/index')
        }
      })
    } else if (isPage('edit')) {
      const doEdit = () => {
        apiBrandEdit(params).then((res) => {
          console.log(res)
          // message.success('编辑成功')
          if (res.data.code === 200) {
            notification.success({
              message: '提示',
              description: '编辑成功!',
            })
            router.push('/brand/index')
          }
        })
      }
      // 审核中 不允许编辑
      // 审核通过 提交编辑弹提示 - 要重新审核
      // 被驳回 直接提交编辑
      if (params.checkState === 'A055_B') {
        Modal.confirm({
          title: '提示',
          centered: true,
          // icon: createVNode(ExclamationCircleOutlined),
          content: '提交后此品牌需要重审核，是否继续？',
          onOk() {
            doEdit()
          },
        })
      } else {
        doEdit()
      }
    }
  })
}
</script>
<style scoped lang="less">
.status {
  .icon {
    width: 10px;
    height: 10px;
    margin-right: 5px;
    border-radius: 50%;
    display: block;
  }
  .text {
  }
}
</style>

