<template>
  <Dialog :title="dialogTitle" :append-to-body="true" v-model="dialogVisible" width="70%">
    <el-form ref="formRef" :model="formValidate" :rules="formRules" label-width="100px" v-loading="formLoading">
      <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
        <el-tab-pane :label="t('product.basicInfo')" name="one">
          <el-form-item :label="t('product.displayShop')" prop="shopId">
            <el-select v-model="formValidate.shopId" :placeholder="t('common.selectShop')" @change="selectShop">
              <el-option v-for="item in shopList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item :label="t('product.productName')" prop="store_name">
            <el-input
              v-model="formValidate.store_name"
              class="input-width"
              :placeholder="t('common.enterProductName')"
            />
          </el-form-item>
          <el-form-item :label="t('product.productCategory')" prop="cate_id">
            <el-select v-model="formValidate.cate_id" :placeholder="t('common.selectCategory')">
              <el-option v-for="item in categoryTree" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item :label="t('product.keyword')" prop="keyword">
            <el-input v-model="formValidate.keyword" class="input-width" :placeholder="t('common.enterKeyword')" />
          </el-form-item>
          <el-form-item :label="t('product.unitName')" prop="unit_name">
            <el-input v-model="formValidate.unit_name" class="input-width" :placeholder="t('common.enterUnitName')" />
          </el-form-item>
          <el-form-item :label="t('product.productPrice')" prop="price">
            <el-input v-model="formValidate.price" class="input-width" :placeholder="t('common.enterPrice')" />
          </el-form-item>
          <el-form-item :label="t('product.marketPrice')" prop="otPrice">
            <el-input v-model="formValidate.otPrice" class="input-width" :placeholder="t('common.enterMarketPrice')" />
          </el-form-item>
          <el-form-item :label="t('product.stock')" prop="stock">
            <el-input v-model="formValidate.stock" class="input-width" :placeholder="t('common.enterStock')" />
          </el-form-item>
          <el-form-item :label="t('product.coverImage')" prop="image">
            <Materials v-model="formValidate.image" num="1" type="image" />
          </el-form-item>
          <el-form-item :label="t('product.sliderImage')" prop="slider_image">
            <Materials v-model="formValidate.slider_image" num="5" type="image" />
          </el-form-item>
          <el-form-item :label="t('product.productStatus')" prop="is_show">
            <el-radio-group v-model="formValidate.is_show">
              <el-radio :label="1">{{ t('common.yes') }}</el-radio>
              <el-radio :label="0">{{ t('common.no') }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label="t('product.productDescription')" prop="store_info">
            <el-input
              type="textarea"
              rows="5"
              v-model="formValidate.store_info"
              :placeholder="t('common.enterProductDescription')"
            />
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane :label="t('product.productSpec')" name="two">
          <el-form-item :label="t('product.productSpec')" prop="spec_type">
            <el-radio-group v-model="formValidate.spec_type" @change="changeSpec">
              <el-radio :label="0">{{ t('product.singleSpec') }}</el-radio>
              <el-radio :label="1">{{ t('product.multipleSpec') }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 多规格添加-->
          <el-col :span="24" v-if="formValidate.spec_type === 1" class="noForm">
            <el-col :span="24">
              <el-form-item :label="t('product.selectSpec')" prop="">
                <div class="acea-row row-middle">
                  <el-select v-model="formValidate.selectRule">
                    <el-option v-for="(item, index) in ruleList" :value="item.ruleName" :key="index">{{
                      item.ruleName
                    }}</el-option>
                  </el-select>
                  <el-button type="primary" class="mr20" @click="confirm">{{ t('common.confirm') }}</el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item v-if="attrs.length !== 0">
                <div v-for="(item, index) in attrs" :key="index" style="width: 100%">
                  <div class="acea-row row-middle"
                    ><span class="mr5">{{ item.value }}</span>
                    <Icon icon="ep:circle-close" @click="handleRemoveRole(index)" />
                  </div>
                  <div class="rulesBox">
                    <el-tag
                      type="dot"
                      closable
                      color="primary"
                      v-for="(j, indexn) in item.detail"
                      :key="indexn"
                      :name="j"
                      class="mr20"
                      @close="handleRemove2(item.detail, indexn)"
                      >{{ j }}</el-tag
                    >
                    <el-input
                      :placeholder="t('common.enterSpecName')"
                      v-model="item.detail.attrsVal"
                      style="width: 150px"
                    >
                      <template #append>
                        <el-button type="primary" @click="createAttr(item.detail.attrsVal, index)">{{
                          t('common.addAttribute')
                        }}</el-button>
                      </template>
                    </el-input>
                  </div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="createBnt">
              <el-form-item>
                <el-button type="primary" icon="md-add" @click="addBtn" class="mr15">{{
                  t('common.addNewSpec')
                }}</el-button>
                <el-button type="success" @click="generate">{{ t('common.generateNow') }}</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="showIput">
              <el-col :xl="6" :lg="9" :md="10" :sm="24" :xs="24">
                <el-form-item :label="t('common.selectSpec')">
                  <el-input :placeholder="t('common.enterSpecName')" v-model="formDynamic.attrsName" />
                </el-form-item>
              </el-col>
              <el-col :xl="6" :lg="9" :md="10" :sm="24" :xs="24">
                <el-form-item :label="t('common.enterSpecValue')">
                  <el-input v-model="formDynamic.attrsVal" :placeholder="t('common.enterSpecValue')" />
                </el-form-item>
              </el-col>
              <el-col :xl="6" :lg="5" :md="10" :sm="24" :xs="24">
                <el-button type="primary" @click="createAttrName">{{ t('common.confirm') }}</el-button>
                <el-button type="danger" @click="offAttrName">{{ t('common.cancel') }}</el-button>
              </el-col>
            </el-col>
            <!-- 多规格设置-->
            <el-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24" v-if="manyFormValidate.length">
              <!-- 多规格表格-->
              <el-col :span="24">
                <el-form-item :label="t('product.productAttributes')" class="labeltop">
                  <el-table :data="manyFormValidate" size="small" style="width: 90%">
                    <el-table-column
                      type="myindex"
                      v-for="(item, index) in formValidate.header"
                      :key="index"
                      :label="item.title"
                      :property="item.slot"
                      align="center"
                    >
                      <template #default="scope">
                        <div v-if="item.slot == 'pic'" align="center">
                          <Materials v-model="scope.row[item.slot]" num="1" type="image" :width="60" :height="60" />
                          <!-- <single-pic v-model="scope.row[scope.column.property]" type="image" :num="1" :width="60" :height="60" /> -->
                        </div>
                        <div v-else-if="item.slot.indexOf('value') != -1" align="center">
                          {{ scope.row[item.slot] }}
                        </div>
                        <div v-else-if="item.slot == 'action'" align="center">
                          <a @click="delAttrTable(scope.$index)" align="center">{{ t('common.delete') }}</a>
                        </div>
                        <div v-else align="center">
                          <el-input v-model="scope.row[item.slot]" align="center" />
                        </div>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form-item>
              </el-col>
            </el-col>
          </el-col>
          <!-- 单规格表格-->
          <el-col :xl="23" :lg="24" :md="24" :sm="24" :xs="24" v-if="formValidate.spec_type === 0">
            <el-form-item>
              <el-table :data="oneFormValidate" size="small" style="width: 90%">
                <el-table-column :prop="t('product.coverImage')" :label="t('product.coverImage')" align="center">
                  <template #default="scope">
                    <Materials v-model="scope.row.pic" num="1" type="image" :width="60" :height="60" />
                  </template>
                </el-table-column>
                <el-table-column :prop="t('product.productPrice')" :label="t('product.productPrice')" align="center">
                  <template #default="scope">
                    <el-input type="text" v-model="scope.row.price" />
                  </template>
                </el-table-column>
                <el-table-column :prop="t('product.cost')" :label="t('product.cost')" align="center">
                  <template #default="scope">
                    <el-input type="text" v-model="scope.row.cost" />
                  </template>
                </el-table-column>
                <el-table-column :prop="t('product.marketPrice')" :label="t('product.marketPrice')" align="center">
                  <template #default="scope">
                    <el-input type="text" v-model="scope.row.ot_price" />
                  </template>
                </el-table-column>
                <el-table-column :prop="t('product.stock')" :label="t('product.stock')" align="center">
                  <template #default="scope">
                    <el-input type="text" v-model="scope.row.stock" maxlength="7" />
                  </template>
                </el-table-column>
                <el-table-column :prop="t('product.barCode')" :label="t('product.barCode')" align="center">
                  <template #default="scope">
                    <el-input type="text" v-model="scope.row.bar_code" />
                  </template>
                </el-table-column>
                <el-table-column :prop="t('product.weight')" :label="t('product.weight')" align="center">
                  <template #default="scope">
                    <el-input type="text" v-model="scope.row.weight" />
                  </template>
                </el-table-column>
                <el-table-column :prop="t('product.volume')" :label="t('product.volume')" align="center">
                  <template #default="scope">
                    <el-input type="text" v-model="scope.row.volume" />
                  </template>
                </el-table-column>
                <!-- <el-table-column prop="volume" label="所需兑换积分" align="center">
                  <template #default="scope">
                    <el-input type="text" v-model="scope.row.integral"/>
                  </template>
                </el-table-column> -->
              </el-table>
            </el-form-item>
          </el-col>
        </el-tab-pane>
        <el-tab-pane :label="t('product.productDetails')" name="three">
          <el-form-item :label="t('product.productDescription')">
            <vue-ueditor-wrap
              v-model="formValidate.description"
              :config="myConfig"
              @before-init="addCustomDialog"
              style="width: 90%"
            />
          </el-form-item>
        </el-tab-pane>
        <!-- <el-tab-pane label="物流设置" name="four">
        <el-form-item label="运费设置">
          <el-radio-group v-model="postageSet">
            <el-radio :label="false">规定邮费</el-radio>
            <el-radio :label="true">运费模板</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="邮费" prop="postage" v-show="!postageSet">
          <el-input class="input-width" v-model="formValidate.postage" placeholder="请输入邮费" />
        </el-form-item>
        <el-form-item label="运费模板" prop="temp_id" v-show="postageSet">
          <el-select v-model="formValidate.temp_id"  class="mr20">
            <el-option :value="0" label="选择运费模板" />
            <el-option v-for="(item,index) in templateList" :value="item.id" :key="index" :label="item.name"/>
          </el-select>
        </el-form-item>
      </el-tab-pane> -->
        <el-tab-pane :label="t('product.marketingSettings')" name="four">
          <el-form-item :label="t('product.getPoints')" prop="give_integral">
            <el-input v-model="formValidate.give_integral" class="input-width" :placeholder="t('common.enterPoints')" />
          </el-form-item>
          <!-- <el-form-item label="是否新品" prop="is_new">
          <el-radio-group v-model="formValidate.is_new">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item> -->
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer>
      <el-button v-if="activeName !== 'one'" @click="upTab">{{ t('common.previousStep') }}</el-button>
      <el-button type="primary" v-if="activeName !== 'four'" @click="downTab">{{ t('common.nextStep') }}</el-button>
      <el-button v-if="activeName == 'four'" @click="submitForm" type="primary" :disabled="formLoading">{{
        t('common.save')
      }}</el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import * as StoreProductApi from '@/api/mall/product/product'
import * as ProductCategoryApi from '@/api/mall/product/category'
// import { handleTree3 } from '@/utils/tree'
import type { TabsPaneContext } from 'element-plus'
import * as ShopApi from '@/api/mall/store/shop'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  image: undefined,
  sliderImage: undefined,
  storeName: undefined,
  storeInfo: undefined,
  keyword: undefined,
  barCode: undefined,
  cateId: undefined,
  price: undefined,
  vipPrice: undefined,
  otPrice: undefined,
  postage: undefined,
  unitName: undefined,
  sort: undefined,
  sales: undefined,
  stock: undefined,
  isShow: 1,
  isHot: undefined,
  isBenefit: undefined,
  isBest: undefined,
  isNew: 0,
  description: undefined,
  isPostage: undefined,
  merUse: undefined,
  giveIntegral: undefined,
  cost: undefined,
  isSeckill: undefined,
  isBargain: undefined,
  isGood: undefined,
  ficti: undefined,
  browse: undefined,
  codePath: undefined,
  isSub: undefined,
  tempId: undefined,
  specType: 0,
  isIntegral: undefined,
  integral: undefined
})
const formValidate = ref({
  shopId: null,
  imageArr: [],
  sliderImageArr: [],
  store_name: '',
  cate_id: 0,
  keyword: '',
  unit_name: '',
  store_info: '',
  image: '',
  slider_image: [],
  description: '',
  ficti: 0,
  give_integral: 0,
  sort: 0,
  is_show: 1,
  price: 0,
  otPrice: 0,
  stock: 0,
  is_new: 0,
  postage: 0,
  is_postage: 0,
  is_sub: 0,
  is_integral: 0,
  id: 0,
  spec_type: 0,
  temp_id: '',
  attrs: [],
  items: [
    {
      pic: '',
      price: 0,
      cost: 0,
      ot_price: 0,
      stock: 0,
      bar_code: '',
      integral: 0
    }
  ],
  header: [],
  selectRule: ''
})

const manyFormValidate = ref([])
const oneFormValidate = ref([
  {
    imageArr: [],
    pic: '',
    price: 2,
    cost: 0,
    ot_price: 0,
    stock: 0,
    seckill_stock: 0,
    seckill_price: 0,
    pink_stock: 0,
    pink_price: 0,
    bar_code: '',
    weight: 0,
    volume: 0,
    brokerage: 0,
    brokerage_two: 0,
    integral: 0
  }
])

const formRules = reactive({
  shopId: [{ required: true, message: t('common.selectShop'), trigger: 'blur' }],
  image: [{ required: true, message: t('common.uploadImage'), trigger: 'blur' }],
  slider_image: [{ required: true, message: t('common.uploadImage'), trigger: 'blur' }],
  store_name: [{ required: true, message: t('common.enterProductName'), trigger: 'blur' }],
  cate_id: [{ required: true, message: t('common.selectCategory'), trigger: 'blur' }],
  price: [{ required: true, message: t('common.enterPrice'), trigger: 'blur' }]
})
const ruleList = ref([])
const attrs = ref([])
// 规格数据
const formDynamic = reactive({
  attrsName: '',
  attrsVal: ''
})
const createBnt = ref(false)
const showIput = ref(false)
const postageSet = ref(false) //false -固定  true 运费模板
const templateList = ref([])
// 批量设置表格data
const oneFormBatch = ref([
  {
    pic: '',
    price: 0,
    cost: 0,
    ot_price: 0,
    stock: 0,
    bar_code: '',
    seckill_stock: 0,
    seckill_price: 0,
    pink_stock: 0,
    pink_price: 0,
    weight: 0,
    volume: 0,
    integral: 0
  }
])

const formRef = ref() // 表单 Ref
const categoryTree = ref<any[]>([]) // 分类树

const myConfig = reactive({
  autoHeightEnabled: false, // 编辑器不自动被内容撑高
  initialFrameHeight: 500, // 初始容器高度
  initialFrameWidth: '100%', // 初始容器宽度
  UEDITOR_HOME_URL: '/UEditor/',
  serverUrl: '',
  zIndex: 9999,
  toolbars: [
    [
      'undo',
      'redo',
      '|',
      'bold',
      'italic',
      'underline',
      'fontborder',
      'strikethrough',
      'superscript',
      'subscript',
      'removeformat',
      'formatmatch',
      'autotypeset',
      'blockquote',
      'pasteplain',
      '|',
      'forecolor',
      'backcolor',
      'insertorderedlist',
      'insertunorderedlist',
      'selectall',
      'cleardoc',
      '|',
      'rowspacingtop',
      'rowspacingbottom',
      'lineheight',
      '|',
      'customstyle',
      'paragraph',
      'fontfamily',
      'fontsize',
      '|',
      'directionalityltr',
      'directionalityrtl',
      'indent',
      '|',
      'justifyleft',
      'justifycenter',
      'justifyright',
      'justifyjustify',
      '|',
      'touppercase',
      'tolowercase',
      '|',
      'imagenone',
      'imageleft',
      'imageright',
      'imagecenter'
    ]
  ]
})
const activeName = ref('one')
const shopList = ref([])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  activeName.value = 'one'
  getList()

  resetForm()

  // 修改时，设置数据
  if (id) {
    formLoading.value = false
  } else {
    id = 0
  }
  getInfo(id)
  // 获得分类树
  // await getTree()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const selectShop = (val) => {
  getTree(val)
}

// const selectCate = () => {
//   if(!formValidate.value.shopId){
//     return message.warning('请先选择店铺')
//   }
// }

const getList = async () => {
  try {
    const data = await ShopApi.getShopList()
    shopList.value = data
  } finally {
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  // const valid = await formRef.value.validate()
  formRef.value.validate((valid, fields) => {
    if (valid) {
      console.log(fields)
    } else {
      return message.warning(t('common.addBasicInfo'))
      // console.log('error submit!', fields)
    }
  })

  // 提交请求
  formLoading.value = true
  try {
    if (formValidate.value.spec_type === 0) {
      formValidate.value.attrs = oneFormValidate.value
      formValidate.value.header = []
      formValidate.value.items = []
    } else {
      formValidate.value.items = attrs.value
      formValidate.value.attrs = manyFormValidate.value
    }
    if (formValidate.value.spec_type === 1 && manyFormValidate.value.length === 0) {
      message.warning(t('common.addSpec'))
    }
    await StoreProductApi.createStoreProduct(formValidate.value)
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab.paneName, event)
}
const upTab = () => {
  if (activeName.value == 'two') {
    activeName.value = 'one'
    return
  }
  if (activeName.value == 'three') {
    activeName.value = 'two'
    return
  }
  if (activeName.value == 'four') {
    activeName.value = 'three'
    return
  }
  // if (activeName.value == 'five') {
  //   activeName.value = 'four'
  //   return
  // }
}
const downTab = () => {
  if (activeName.value == 'one') {
    activeName.value = 'two'
    return
  }
  if (activeName.value == 'two') {
    activeName.value = 'three'
    return
  }
  if (activeName.value == 'three') {
    activeName.value = 'four'
    return
  }
  // if (activeName.value == 'four') {
  //   activeName.value = 'five'
  //   return
  // }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    image: undefined,
    sliderImage: undefined,
    storeName: undefined,
    storeInfo: undefined,
    keyword: undefined,
    barCode: undefined,
    cateId: undefined,
    price: undefined,
    vipPrice: undefined,
    otPrice: undefined,
    postage: undefined,
    unitName: undefined,
    sort: undefined,
    sales: undefined,
    stock: undefined,
    isShow: undefined,
    isHot: undefined,
    isBenefit: undefined,
    isBest: undefined,
    isNew: undefined,
    description: undefined,
    isPostage: undefined,
    merUse: undefined,
    giveIntegral: undefined,
    cost: undefined,
    isSeckill: undefined,
    isBargain: undefined,
    isGood: undefined,
    ficti: undefined,
    browse: undefined,
    codePath: undefined,
    isSub: undefined,
    tempId: undefined,
    specType: undefined,
    isIntegral: undefined,
    integral: undefined
  }
  formValidate.value = {
    imageArr: [],
    sliderImageArr: [],
    store_name: '',
    cate_id: '',
    keyword: '',
    unit_name: '',
    store_info: '',
    image: '',
    slider_image: [],
    description: '',
    ficti: 0,
    give_integral: 0,
    sort: 0,
    is_show: 1,
    price: 0,
    otPrice: 0,
    stock: 0,
    is_new: 0,
    postage: 0,
    is_postage: 0,
    is_sub: 0,
    is_integral: 0,
    id: 0,
    spec_type: 0,
    temp_id: '',
    attrs: [],
    items: [
      {
        pic: '',
        price: 0,
        cost: 0,
        ot_price: 0,
        stock: 0,
        bar_code: '',
        integral: 0
      }
    ],
    header: [],
    selectRule: ''
  }
  attrs.value = []

  formRef.value?.resetFields()
}

// 详情
const getInfo = (id) => {
  // let that = this;
  StoreProductApi.getStoreProductInfo(id)
    .then(async (res) => {
      let data = res.productInfo
      console.log('data:', data)
      postageSet.value = false
      if (data) {
        // let cate_id = parseInt(data.cate_id) || 0;
        if (data.temp_id > 0) postageSet.value = true
        attrs.value = data.items || []
        formValidate.value = data
        formValidate.value.cate_id = Number(data.cate_id)
        if (formValidate.value.shopId) {
          console.log('shopId:', formValidate.value.shopId)
          await getTree(formValidate.value.shopId)
        }
        oneFormValidate.value = [data.attr]
        formValidate.value.header = []
        generate()
        manyFormValidate.value = data.attrs
        console.log('data2:', formValidate.value.spec_type)
        if (data.spec_type === 0) {
          manyFormValidate.value = []
        } else {
          createBnt.value = true
          oneFormValidate.value = [
            {
              imageArr: [],
              pic: '',
              price: 0,
              cost: 0,
              ot_price: 0,
              stock: 0,
              seckill_stock: 0,
              seckill_price: 0,
              pink_stock: 0,
              pink_price: 0,
              bar_code: '',
              weight: 0,
              volume: 0,
              brokerage: 0,
              brokerage_two: 0,
              integral: 0
            }
          ]

          console.log('spec_type2:', formValidate.value.spec_type)
        }
      }

      ruleList.value = res.ruleList
      templateList.value = res.tempList
    })
    .catch((res) => {
      console.log('err:' + res)
    })
}

const route = useRoute()
// 立即生成
const generate = () => {
  StoreProductApi.isFormatAttr(formValidate.value.id, { attrs: attrs.value })
    .then((res) => {
      manyFormValidate.value = res.value
      let headerdel = {
        title: t('table.action'),
        slot: 'action',
        fixed: 'right',
        width: 220
      }
      res.header.push(headerdel)
      formValidate.value.header = res.header
      //this.formValidate.attrs = res.attr;
      let header = res.header
      header.pop()
      if (!route.params.id && formValidate.value.spec_type === 1) {
        manyFormValidate.value.map((item) => {
          item.pic = formValidate.value.image
        })
        oneFormBatch.value[0].pic = formValidate.value.image
      }
    })
    .catch((res) => {
      console.log('err:' + res)
    })
}

/** 获得分类树 */
const getTree = async (val) => {
  const data = await ProductCategoryApi.getCategoryList({ shopId: val })
  // const tree = handleTree3(data, 'id', 'parentId')
  // console.log('tree:',tree)
  //const menu = { id: 0, name: '顶级分类', children: tree }
  categoryTree.value = data
}

const addCustomDialog = () => {
  window.UE.registerUI(
    'yshop',
    function (editor, uiName) {
      let dialog = new window.UE.ui.Dialog({
        iframeUrl: '/yshop/materia/index',
        editor: editor,
        name: uiName,
        title: t('common.uploadImage'),
        cssRules: 'width:1200px;height:650px;padding:20px;'
      })
      this.dialog = dialog

      var btn = new window.UE.ui.Button({
        name: 'dialog-button',
        title: t('common.uploadImage'),
        cssRules: `background-image: url(../../../assets/imgs/icons.png);background-position: -726px -77px;`,
        onclick: function () {
          dialog.render()
          dialog.open()
        }
      })

      return btn
    },
    37
  )
}

// 改变规格
const changeSpec = () => {}

const confirm = () => {
  createBnt.value = true
  if (formValidate.value.selectRule.trim().length <= 0) {
    message.error(t('common.selectAttribute'))
  }
  ruleList.value.forEach(function (item, index) {
    console.log(index)
    if (item.ruleName === formValidate.value.selectRule) {
      attrs.value = item.ruleValue
    }
  })
}

// 删除规格
const handleRemoveRole = (index) => {
  attrs.value.splice(index, 1)
  manyFormValidate.value.splice(index, 1)
}

// 删除属性
const handleRemove2 = (item, index) => {
  item.splice(index, 1)
}

// 添加规则名称
const createAttrName = () => {
  if (formDynamic.attrsName && formDynamic.attrsVal) {
    let data = {
      value: formDynamic.attrsName,
      detail: [formDynamic.attrsVal]
    }
    attrs.value.push(data)
    var hash = {}
    attrs.value = attrs.value.reduce(function (item, next) {
      hash[next.value] ? '' : (hash[next.value] = true && item.push(next))
      return item
    }, [])
    clearAttr()
    showIput.value = false
    createBnt.value = true
  } else {
    message.warning(t('common.addCompleteSpec'))
  }
}
// 添加属性
const createAttr = (num, idx) => {
  if (num) {
    attrs.value[idx].detail.push(num)
    var hash = {}
    attrs.value[idx].detail = attrs.value[idx].detail.reduce(function (item, next) {
      hash[next] ? '' : (hash[next] = true && item.push(next))
      return item
    }, [])
  } else {
    message.warning(t('common.addAttribute'))
  }
}
// 取消
const offAttrName = () => {
  showIput.value = false
  createBnt.value = true
}
// 删除表格中的属性
const delAttrTable = (index) => {
  manyFormValidate.value.splice(index, 1)
}
// 添加按钮
const addBtn = () => {
  clearAttr()
  createBnt.value = false
  showIput.value = true
}

const clearAttr = () => {
  formDynamic.attrsName = ''
  formDynamic.attrsVal = ''
}
</script>

<style scoped >
.input-width {
  width: 40%;
}

.mb15 {
  margin-bottom: 15px !important;
}
.mb5 {
  margin-bottom: 5px !important;
}
.mr20 {
  margin-right: 20px !important;
}

.mr5 {
  margin-right: 5px !important;
}
.mr15 {
  margin-right: 15px !important;
}
.ml95 {
  margin-left: 95px !important;
}
.mt10 {
  margin-top: 10px;
}

.acea-row {
  display: -webkit-box;
  display: -moz-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-lines: multiple;
  -moz-box-lines: multiple;
  -o-box-lines: multiple;
  -webkit-flex-wrap: wrap;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  /* 辅助类 */
}
.acea-row.row-middle {
  -webkit-box-align: center;
  -moz-box-align: center;
  -o-box-align: center;
  -ms-flex-align: center;
  -webkit-align-items: center;
  align-items: center;
}
</style>
