<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 === 'A03'" 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 === 'A01'" 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 === 'A02'" 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="disabled">
        <div class="part-1">
          <div class="mini-title c-333 fs-16 mb-20 font-700">基本信息</div>

          <a-form-item ref="merchandiseEnglishName" label="产品英文名" name="merchandiseEnglishName">
            <a-input placeholder="请输入" v-model:value="postForm.merchandiseEnglishName" size="large" />
          </a-form-item>
          <div class="grid grid-cols-3 gap-col-100">
            <a-form-item ref="twoTitle" label="产品副标题" name="twoTitle">
              <a-input placeholder="请输入" v-model:value="postForm.twoTitle" size="large" />
            </a-form-item>
            <a-form-item ref="affiliationBrandCode" label="所属品牌">
              <a-select placeholder="请选择" size="large" v-model:value="postForm.affiliationBrandCode">
                <a-select-option :value="item.billNo" v-for="item in brandList" :key="item.id">{{ item.brandName }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item ref="category" label="产品分类" name="categoryTemporaryArr">
              <a-cascader
                size="large"
                change-on-select
                v-model:value="postForm.categoryTemporaryArr"
                :options="options"
                expand-trigger="hover"
                :fieldNames="{ label: 'title', value: 'key' }"
                :showCheckedStrategy="Cascader.SHOW_CHILD"
              />
            </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="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="sellPrice">
              <a-input-number v-model:value="postForm.sellPrice" size="large" class="w-full" :min="1" />
            </a-form-item>
            <a-form-item ref="unit" label="计量单位" name="unit">
              <a-select placeholder="请选择" size="large" v-model:value="postForm.unit">
                <a-select-option :value="item.value" v-for="item in commonStore.dict[DICT_CODE.PRODUCT_UNIT]" :key="item.value">{{
                  item.text
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item ref="moq" label="MOQ" name="moq">
              <a-input-number placeholder="请输入" v-model:value="postForm.moq" size="large" :min="1" style="width: 100%" />
            </a-form-item>
            <a-form-item ref="color" label="颜色" name="color">
              <a-input placeholder="请输入" v-model:value="postForm.color" size="large" />
            </a-form-item>
            <a-form-item ref="texture" label="材质" name="texture">
              <a-input placeholder="请输入" v-model:value="postForm.texture" size="large" />
            </a-form-item>
            <a-form-item ref="cartonQuantity" label="装箱数" name="cartonQuantity">
              <a-input-number v-model:value="postForm.cartonQuantity" size="large" class="w-full" :min="1" />
            </a-form-item>
            <a-form-item ref="suttle" label="净重">
              <a-input-group compact>
                <a-input-number placeholder="请输入" v-model:value="postForm.suttle" size="large" :min="0" style="width: 75%" />
                <a-select placeholder="请选择" size="large" v-model:value="postForm.suttleUnit" style="width: 25%" disabled>
                  <a-select-option :value="item.value" v-for="item in commonStore.dict[DICT_CODE.PRODUCT_NET_WEIGHT]" :key="item.value">{{
                    item.text
                  }}</a-select-option>
                </a-select>
              </a-input-group>
            </a-form-item>
            <a-form-item label="规格（长*宽*高）">
              <a-input-group compact>
                <a-input-number placeholder="长" v-model:value="postForm.length" size="large" :min="0" style="width: 25%" />
                <a-input-number placeholder="宽" v-model:value="postForm.width" size="large" :min="0" style="width: 25%" />
                <a-input-number placeholder="高" v-model:value="postForm.height" size="large" :min="0" style="width: 25%" />
                <a-select placeholder="请选择" size="large" v-model:value="postForm.lwhUnit" style="width: 25%" disabled>
                  <a-select-option :value="item.value" v-for="item in commonStore.dict[DICT_CODE.PRODUCT_L_W_H]" :key="item.value">{{
                    item.text
                  }}</a-select-option>
                </a-select>
              </a-input-group>
            </a-form-item>
            <a-form-item ref="name" label="体积">
              <a-input-group compact>
                <a-input-number placeholder="请输入" v-model:value="postForm.volume" size="large" :min="0" style="width: 75%" />
                <a-select placeholder="请选择" size="large" v-model:value="postForm.volumeUnit" style="width: 25%" disabled>
                  <a-select-option :value="item.value" v-for="item in commonStore.dict[DICT_CODE.PRODUCT_SIZE]" :key="item.value">{{
                    item.text
                  }}</a-select-option>
                </a-select>
              </a-input-group>
            </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="address">
            <a-textarea placeholder="请输入" v-model:value="postForm.merchandiseDescribe" 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="mock-table text-center">
            <a-row class="mock-table-header py-16">
              <a-col :span="7">最小数量</a-col>
              <a-col :span="7">最大数量(不填表示无上限)</a-col>
              <a-col :span="7">单价</a-col>
              <a-col :span="3">操作</a-col>
            </a-row>
            <a-row class="pt-24" v-for="(item, index) in postForm.quotes" :key="item.id" :class="index % 2 === 1 ? 'bg-gray-1' : ''">
              <a-col :span="7">
                <a-form-item :name="['quotes', index, 'minimum']" :rules="{ required: true, message: '请输入最小数量' }">
                  <a-input-number
                    placeholder="请输入最小数量"
                    v-model:value="item.minimum"
                    size="large"
                    :min="postForm.moq"
                    style="width: 50%"
                    class="centered-input-number"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="7">
                <a-form-item :name="['quotes', index, 'maximum']">
                  <a-input-number
                    placeholder="请输入最大数量"
                    v-model:value="item.maximum"
                    size="large"
                    :min="0"
                    style="width: 50%"
                    class="centered-input-number"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="7">
                <a-form-item :name="['quotes', index, 'price']" :rules="{ required: true, message: '请输入单价' }">
                  <a-input-number
                    placeholder="请输入单价"
                    v-model:value="item.price"
                    size="large"
                    :min="0"
                    style="width: 50%"
                    class="centered-input-number"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="3">
                <a-button type="primary" danger :disabled="postForm.quotes.length <= 1" @click="delQuote(index)">删除</a-button>
              </a-col>
            </a-row>
          </div>
          <a-form-item class="mt-20" v-if="postForm.quotes.length < 8">
            <a-button type="dashed" block @click="addQuote"> + 新增一列 </a-button>
          </a-form-item> -->

        <!-- <a-table
            class="theme-table"
            :columns="columns"
            :data-source="postForm.quotes"
            :pagination="false"
            :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : '')"
          >
            <template #bodyCell="{ column, value, record }">
              <div class="fs-16 c-primary fw-700" v-if="column.dataIndex === 'name'">
                {{ value }}
              </div>
              <div class="fs-16 c-primary fw-700" v-if="column.dataIndex === 'brandQuantityLimit'">
                {{ value }}
              </div>
              <div class="fs-16 c-primary fw-700" v-if="column.dataIndex === 'singleBrandProductLimit'">
                {{ value }}
              </div>
              <div class="fs-16 c-primary fw-700" v-if="column.dataIndex === 'operation'">
                <div class="c-danger">删除</div>
              </div>
            </template>
          </a-table> -->
        <!-- </div> -->
        <div class="part-4">
          <div class="mini-title c-333 fs-16 mb-20 font-700">图片/视频信息</div>
          <a-form-item label="产品图片" name="otherImage" extra="最多上传5张，最佳尺寸:500*500，单张最大为5M">
            <UploadFile :disabled="disabled" v-model:url="postForm.otherImage" fileType="image" :limit="5" :limitSize="5"></UploadFile>
          </a-form-item>

          <a-form-item label="产品视频" name="otherVideo" extra="主图视频大小不超过50M">
            <!-- <UploadFile :disabled="disabled" v-model:url="postForm.otherVideo" :limit-size="50"></UploadFile> -->
            <UploadFile :disabled="disabled" fileType="video" v-model:url="postForm.otherVideo" :limit-size="50"></UploadFile>
          </a-form-item>
        </div>
      </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 { ProductItem, BrandItem, QuoteItem } from 'Types/api'
import { apiProductAdd, apiProductDetail, apiProductEdit, apiProductLimit } from '@/api/product'
import { apiBrandList } 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 { getProductCategoryApi } from 'API/common'
import { message, notification, Modal, Cascader } from 'ant-design-vue'
const commonStore = useCommonStore()
const userStore = useUserStore()
// 获取指定类型字典（带缓存）
commonStore.getDict(DICT_CODE.EN_COUNTRY)
commonStore.getDict(DICT_CODE.PRODUCT_SIZE)
commonStore.getDict(DICT_CODE.PRODUCT_L_W_H)
commonStore.getDict(DICT_CODE.PRODUCT_NET_WEIGHT)
commonStore.getDict(DICT_CODE.PRODUCT_UNIT)
// commonStore.getDict(DICT_CODE.BRAND_CLASS)

// commonStore.getCategory()

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 === 'A03'
})

const columns = [
  {
    title: '最小数量',
    dataIndex: 'name',
    align: 'center',
  },
  {
    title: '最大数量(不输入即为无上限)',
    dataIndex: 'brandQuantityLimit',
    align: 'center',
  },
  {
    title: '单价',
    dataIndex: 'singleBrandProductLimit',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    align: 'center',
  },
]
const options = ref([])
const postForm = ref({} as ProductItem)

postForm.value = {
  // affiliationBrandCode	所属品牌Code	string
  // affiliationBrandName	所属品牌名称	string
  // billNo	编码	string
  // cartonQuantity	装箱数	integer(int32)
  // category	分类	string
  // categoryText	产品分类	string
  // checkState	审核状态字典	string
  // color	颜色	string
  // createBy	创建人	string
  // createTime	创建时间	string(date-time)
  // createType	创建渠道	string
  // firstCategory	一级产品分类	string
  // height	高	number
  // id	id	string
  // length	长	number
  // lwhUnit	长宽高单位字典code	string
  // masterImage	产品主图	string
  // merchandiseChinaName	产品中文名称 暂时用不上 忽略	string
  // merchandiseDescribe	产品描述	string
  // merchandiseEnglishName	产品英文名称	string
  // merchandiseType	产品分类字典code 暂时用不上	string
  // minMaxPrice	价格区间	string
  // moq	MOQ	string
  // onOrOffTime	上架时间	string(date-time)
  // otherImage	其他图片/视频	string
  // otherVideo	其他视频	string
  // productCode	产品code	string
  // productName	产品名称	string
  // quotes	supplier_merchandise_quote	array	supplier_merchandise_quote对象
  // registrationCode	产地字典code	string
  // reject	拒绝理由	string
  // secondCategory	二级产品分类	string
  // state	产品上下架状态字典	string
  // supplierCode	供应商code	string
  // supplierName	供应商name	string
  // suttle	净重	string
  // suttleUnit	净重单位字典code	string
  // tag	标签 多个用逗号拼接	string
  // texture	材质	string
  // thirdCategory	三级产品分类	string
  // twoTitle	副标题	string
  // unit	计量单位字典code	string
  // updateBy	更新人	string
  // updateTime	更新时间	string(date-time)
  // volume	体积	number
  // volumeUnit	体积字典code	string
  // width	宽	number
  id: '',
  merchandiseEnglishName: '',
  affiliationBrandCode: '',
  category: '',
  affiliationBrandName: '',
  registrationCode: '',
  unit: '',
  moq: '',
  billNo: '',
  cartonQuantity: '',
  sellPrice: '',
  categoryText: '',
  categoryTemporaryArr: [],
  checkState: '',
  checkState_dictText: '',
  color: '',
  createBy: '',
  createTime: '',
  createType: '',
  firstCategory: '',
  length: '',
  width: '',
  height: '',
  masterImage: '',
  merchandiseChinaName: '',
  merchandiseDescribe: '',
  merchandiseType: '',
  minMaxPrice: '',
  onOrOffTime: '',
  suttleUnit: 'A059_B',
  lwhUnit: 'A060_A',
  volumeUnit: 'A061_B',
  otherImage: '',
  otherVideo: '',
  productCode: '',
  productName: '',
  // quotes: [
  //   {
  //     minimum: '',
  //     maximum: '',
  //     price: '',
  //     // minimum: '',
  //     // maximum: '',
  //     // price: '',
  //   },
  // ],
  reject: '',
  secondCategory: '',
  state: '',
  supplierName: '',
  suttle: '',
  tag: '',
  texture: '',
  thirdCategory: '',
  twoTitle: '',
  updateBy: '',
  updateTime: '',
  volume: '',
  supplierCode: userStore.userInfo.id,
  firstCategory_dictText: '',
  secondCategory_dictText: '',
}

const getCategoryList = async () => {
  const res = await getProductCategoryApi({ pid: 0 })
  if (res.data.success) {
    options.value = res.data.result || []
  }
}
getCategoryList()

const validateBrand = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('请选择')
  }
  if (isPage('add')) {
    const res = await apiProductLimit({
      brandCode: value,
      supplierId: userStore.userInfo.id,
    })
    if (res.data?.success) {
      return Promise.resolve()
    } else {
      return Promise.reject('该品牌维护的产品数已达上限， 请联系客服升级')
    }
  } else {
    return Promise.resolve()
  }
}
const postFormRules: Record<string, Rule[]> = {
  merchandiseEnglishName: [{ required: true, message: '请输入', trigger: 'change' }],
  // brandName: [{ required: true, message: '品牌名称未输入', trigger: 'change' }],
  affiliationBrandCode: [{ required: true, validator: validateBrand, trigger: 'change' }],
  categoryTemporaryArr: [{ required: true, message: '请选择', trigger: 'change' }],
  sellPrice: [{ required: true, message: '请选择', trigger: 'change' }],
  registrationCode: [{ required: true, message: '请输入', trigger: 'change' }],
  unit: [{ required: true, message: '请选择', trigger: 'change' }],
  moq: [{ required: true, message: '请选择', trigger: 'change' }],
  otherImage: [{ required: true, message: '请上传', trigger: 'change' }],
}
// onMounted(() => {
// })
const brandList = ref<Array<BrandItem>>()

const getInfo = () => {
  apiProductDetail({ id: route.query.id }).then((res) => {
    console.log('---- 获取详情 ----', res)
    const data = res.data.result
    mergeObj(postForm.value, data)
    if (data.firstCategory) {
      postForm.value.categoryTemporaryArr.push(data.firstCategory)
    }
    if (data.secondCategory) {
      postForm.value.categoryTemporaryArr.push(data.secondCategory)
    }
    if (data.thirdCategory) {
      postForm.value.categoryTemporaryArr.push(data.thirdCategory)
    }
    // postForm.value.category = data.firstCategory
    // postForm.value.brandTag = data.brandTag.split(',')
  })
}

const init = () => {
  route.query.id && getInfo()
  apiBrandList({ pageNo: 1, pageSize: 9999 }).then((res) => {
    // console.log(res.data.result.records)
    brandList.value = res.data.result.records
  })
}
init()

// 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.masterImage = params.otherImage.split(',')[0]
    params.category = params.categoryTemporaryArr[params.categoryTemporaryArr.length - 1]
    // params.brandTag = params.brandTag.join(',')
    // params.brandType = params.brandType.join(',')
    if (isPage('add')) {
      apiProductAdd(params).then((res) => {
        if (res.data.code === 200) {
          notification.success({
            message: '提示',
            description: '添加成功!',
          })
          router.push('/product/index')
        }
      })
    } else if (isPage('edit')) {
      const doEdit = () => {
        apiProductEdit(params).then((res) => {
          console.log(res)
          // message.success('编辑成功')
          if (res.data.code === 200) {
            notification.success({
              message: '提示',
              description: '编辑成功!',
            })
            router.push('/product/index')
          }
        })
      }
      // 审核中 不允许编辑
      // 审核通过 提交编辑弹提示 - 要重新审核
      // 被驳回 直接提交编辑
      if (params.checkState === 'A055_B') {
        Modal.confirm({
          title: '提示',
          centered: true,
          // icon: createVNode(ExclamationCircleOutlined),
          content: '提交后此品牌需要重审核，是否继续？',
          onOk() {
            doEdit()
          },
        })
      } else {
        doEdit()
      }
    }
  })
}

// const addQuote = () => {
//   const quote: QuoteItem = {
//     minimum: '',
//     maximum: '',
//     price: '',
//   }
//   if (postForm.value.quotes) {
//     postForm.value.quotes.push(quote)
//   }
// }

// const delQuote = (index: number) => {
//   console.log(index)
//   postForm.value.quotes.splice(index, 1)
// }

const checkLimit = (val: number) => {
  console.log(val)
  apiProductLimit({
    brandCode: val,
    supplierId: userStore.userInfo.id,
  }).then((res) => {
    if (res.data.success) {
    }
  })
}
</script>
<style scoped lang="less">
@import '@/assets/styles/variables.less';

.status {
  .icon {
    width: 10px;
    height: 10px;
    margin-right: 5px;
    border-radius: 50%;
    display: block;
  }
  .text {
  }
}
.mock-table {
  .mock-table-header {
    background-color: @color-primary-light;
  }
}
</style>
