<template>
  <el-dialog
    :visible.sync="visible"
    v-bind="modalOptions"
    append-to-body
  >
    <el-form
      ref="formData"
      :model="formData"
      :rules="formRules"
      size="mini"
      label-suffix=":"
      label-width="150px"
    >

      <el-form-item label="商品ID" prop="productId">
        <el-input
          v-model="formData.productId" maxlength="20" placeholder="商品ID" disabled
        />
      </el-form-item>
      <el-form-item label="商家Id" prop="productIdproductId">
        <el-input
          v-model="formData.productIdproductId" maxlength="20" placeholder="请输入商家id"
        />
      </el-form-item>
      
      <el-form-item label="平台分类" prop="classifyId" v-if="isCopy">
        <el-cascader v-model="classifyId" placeholder="请选择官方分类" clearable :props="props" />
        <!-- <el-select v-model="formData.classifyId" placeholder="请选择平台分类">
        <el-option
        v-for="item in classOptions" :key="item.classifyId" :label="item.classifyName"
        :value="item.classifyId"
        >
        </el-option>
        </el-select> -->
        </el-form-item>
      <el-form-item label="商家分组" prop="shopGroupId" v-if="!isCopy">
        <el-cascader
          v-model="formData.shopGroupArr" placeholder="请选择商家分组" :options="shopGroupList"
          :props="{ checkStrictly: true, expandTrigger: 'hover', label: 'groupName', value: 'shopGroupId', children: 'childs' }"
          clearable
        />
        <!-- <el-select v-model="formData.shopGroupId" placeholder="请选择">
          <el-option v-for="item in shopGroup" :key="item.shopGroupId" :label="item.groupName"
          :value="item.shopGroupId">
          </el-option>
          </el-select> -->
      </el-form-item>
      <el-form-item label="是否加入选品" prop="shelveState" v-if="!isCopy">
        <el-radio-group v-model="formData.shelveState">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">不是</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <!-- 是复制还是加入选品 -->
        <template v-if="!isCopy">
          <el-button size="mini" @click="handleClose">取 消</el-button>
          <el-button type="primary" size="mini" @click="handleSubmit">确 定</el-button>
        </template>
        <template v-else>
          <el-button size="mini" @click="handleClose(1)">取 消</el-button>
          <el-button type="primary" size="mini" @click="handleCopy">复 制</el-button>
        </template>
        
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { commdityClassGetAll, commdityClassGetGroup, getProductById, addProductFixed,commdityClassgetById, getClassifyList,copyGoods } from '@/api/commodity'

let arrList = [];
export default {
  name: 'AddSelection',
  props:{
    // 控制是否是复制商品
    isCopy:{
      type: Boolean,
      default: false
    }
  },
  components: {
  },
  data() {
    return {
      modalOptions: {
        closeOnClickModal: false,
        width: '620px',
        title: ''
      },
      visible: false,
      formData: {
        productId: '',
        productIdproductId: 186,
        shopParentId: '',
        shopGroupId: '',
        shopGroupArr: [], // 非后端参数
        shelveState: '',
      },
      formRules: {
        productId: [
          { required: true, message: '缺少商品ID' }
        ],
        productIdproductId: [
          { required: true, message: '商家id不能为空' }
        ],
        shopGroupId: [
          { required: true, message: '请选择商家分组' }
        ],
        shelveState: [
          { required: true, message: '请选择是否加入选品' }
        ],
        classifyId:[
          { required: true, message: '请选择商品分类' }
        ]
      },
      // classOptions: [],
      shopGroupList: [],
      //  异步加载
      props: {
                lazy: true,
                checkStrictly: true,
                label: 'classifyName',
                value: 'classifyId',
                lazyLoad(node, resolve) {
                    const { level, value } = node;
                    if (level === 0) {
                        getClassifyList({ page: 1, pageSize: 15 }).then(res => {
                            resolve(res.data.list)
                        })
                    } else if (level === 1) {
                        commdityClassgetById({ oneClassifyId: value }).then(res => {
                            // 将里面所有的childs.categoryName 换为classifyName
                            let arr = res.data.childs.map(item => {
                                item.classifyName = item.categoryName
                                item.classifyId = item.id
                                return item
                            })
                            arrList = arr
                            resolve(arr)
                        })
                    } else {
                        //  过滤出对应id
                        let arrItem = arrList.filter(item => {
                            return item.classifyId == value
                        })
                        if (arrItem.length <= 0) return
                        let arr = arrItem[0].childs.map(item => {
                            item.classifyName = item.categoryName
                            item.classifyId = item.id
                            return item
                        })
                        resolve(arr)
                    }
                }
            },
            classifyId:""
    }
  },
  created() {
    this.getAllClass()
    this.getGroupSelect()
  },
  methods: {
    handleClose(val) {
      this.visible = false
      if(val == 1){
        this.$emit("changeIsCopy")
      }
    },
    //  获取商品类别
    async getAllClass() {
      const res = await commdityClassGetAll({ page: 1, pageSize: 9999 })
      this.classOptions = res.data.list
    },
    // 商家分组查询
    async getGroupSelect() {
      const res = await commdityClassGetGroup({ search: '', page: 1, pageSize: 9999 })
      this.shopGroupList = res.data.list
    },
    initList() {
    },
    handleOpen(params = {}) {
      this.modalOptions.title = this.isCopy?'复制商品':'加入选品'
      this.formData.productId = params.productId
      this.formData.shopGroupArr = []
      // this.formData = Object.assign(this.$options.data().formData, params)
      this.visible = true
      this.initList()
      if (params.productId) {
        this.getInfo(params.productId)
      }
      // this.$refs.formData && this.$refs.formData.resetFields()
    },
    async getInfo(id) {
      const loading = this.$loading({ text: '加载中' })
      try {
        const res = await getProductById({ productId: id })
        // this.formData = Object.assign(this.$options.data().formData, res.data, {
        this.formData = Object.assign(this.$options.data().formData, this.formData, {
          shopParentId: res.data.shopId || ''
          // shopGroupId: res.data.shopGroupId || '',
        })
        this.$nextTick(() => {
          this.$refs.formData && this.$refs.formData.validate()
        })
      } finally {
        loading.close()
      }
    },
    handleSubmit() {
      this.$refs.formData.validate(async (valid) => {
        if (valid) {
          const loading = this.$loading({ text: '加载中' })
          try {
            const { shopGroupArr, ...otps } = this.formData
            const params = {
              ...otps,
              shopGroupId: Array.isArray(shopGroupArr) && shopGroupArr.length ? shopGroupArr[shopGroupArr.length - 1] : ''
            }
            await addProductFixed(params)
            loading.close()
            this.$message({ message: `选品添加成功!`, type: 'success' })
            this.$emit('success')
            this.visible = false
          } catch (e) {
            loading.close()
          } finally {
            loading.close()
          }
        } else {
          this.$message({ message: '请输入相关信息', type: 'warning' })
          return false
        }
      })
    },
    //  复制商品
    async handleCopy(){
      let { productIdproductId, productId, shopGroupArr } = this.formData
      let obj = Object.assign({},{
        shopId:productIdproductId,
        productId:productId,
        shopGroupArr:0,
        classifyId:this.classifyId[this.classifyId.length - 1]
      })
      let res = await copyGoods(obj)
      if(res.code == 200 || res.code == ''){
        this.$message({
          message: '复制成功',
          type: 'success'
        })
        this.visible = false
        this.classifyId = ""
        this.$emit("changeIsCopy")
      }
    }
  }
}
</script>

