<template>
  <el-dialog
    append-to-body
    custom-class="center-dialog"
    :title="title"
    top="0vh"
    :visible.sync="dialogFormVisible"
    width="800px"
    @close="close"
  >
    <vab-query-form>
      <vab-query-form-left-panel :span="24">
        <el-form :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.product_name"
              clearable
              :placeholder="__('请输入商品名称')"
            />
          </el-form-item>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.product_id"
              clearable
              :placeholder="__('请输入产品SPU编码')"
            />
          </el-form-item>
          <el-form-item>
            <tree-select
              ref="treeSelect"
              :checked-keys="defaultCheckedKeys"
              :check-strictly="true"
              clearable
              :data="data"
              :default-props="defaultProps"
              :height="300"
              :node-key="nodeKey"
              size="small"
              :width="220"
              @change="change"
            />
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="queryForm.brand_id"
              clearable
              filterable
              :loading="loading"
              :placeholder="__('请输入商品品牌')"
              remote
              :remote-method="remoteFindUserList"
              reserve-keyword
            >
              <el-option
                v-for="item in brandNames"
                :key="item.brand_id"
                :label="item.brand_name"
                :value="item.brand_id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="queryForm.tradeTypes"
              clearable
              :placeholder="__('请选择')"
            >
              <el-option
                v-for="item in tradeType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="fetchData">
              {{ __('查询') }}
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-left-panel>
    </vab-query-form>
    <el-table
      v-loading="listLoading"
      border
      :data="list"
      height="400"
      @selection-change="setSelectRows"
    >
      <el-table-column align="center" show-overflow-tooltip type="selection" />
      <el-table-column
        align="center"
        :label="__('商品编号')"
        prop="item_id"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('商品标题')"
        prop="product_item_name"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('商品单价')"
        prop="item_unit_price"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('产品SPU')"
        prop="product_id"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :formatter="formatEnable"
        :label="__('产品状态')"
        prop="product_state_id"
        show-overflow-tooltip
      />
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNum"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">{{ __('取消') }}</el-button>
      <el-button type="primary" @click="save">{{ __('确定') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { translateTitle as __ } from '@/utils/i18n'

  import { getList } from '@/api/product/item'
  import { getBrands as getListBrand } from '@/api/base/product/brand'
  import { addItem } from '@/api/store/activity/base'
  import TreeSelect from '@/components/treeSelect'
  import { getTree } from '@/api/base/product/category'

  export default {
    name: 'ProductItemTable',
    components: { TreeSelect },
    data() {
      return {
        defaultCheckedKeys: [],
        list: [],
        defaultProps: {
          children: 'children',
          label: 'label',
        },
        loading: false,
        listLoading: true,
        form: {},
        data: [], // 产品规格数据
        nodeKey: 'id',
        title: '',
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: [],
        brandNames: [],

        tradeType: [
          {
            label: this.__('选中筛选(分类和品牌可用)'),
            value: 1,
          },
          {
            label: this.__('剔除筛选(分类和品牌可用)'),
            value: 2,
          },
        ],
        queryForm: {
          tradeTypes: 1,
          pageNum: 1,
          pageSize: 10,
          product_state_id: 1001,
        },
        dialogFormVisible: false,
      }
    },
    created() {
      this.getTree()
    },
    methods: {
      __,
      // 获取规格数据
      async getTree() {
        const { data } = await getTree()
        this.data = data
      },
      showTable(activity_id) {
        this.activity_id = activity_id

        this.fetchData()
        this.dialogFormVisible = true
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      close() {
        this.list = []
        this.dialogFormVisible = false
      },
      formatEnable(row) {
        return row.product_state_id === 1001
          ? this.__('正常')
          : row.product_state_id === 1002
          ? this.__('下架厂库中')
          : row.product_state_id === 1003
          ? this.__('待审核')
          : this.__('违规禁售')
      },
      async fetchData() {
        this.listLoading = true
        const { data } = await getList(this.queryForm)
        this.list = data.items
        this.total = data.records
        this.listLoading = false
      },

      async remoteFindUserList(brand_name) {
        if (brand_name !== '') {
          this.loading = true
          setTimeout(() => {
            this.loading = false
            getListBrand({ brand_name: brand_name })
              .then((res) => {
                this.brandNames = res.data
              })
              .catch((err) => {
                this.brandNames = []
              })
          }, 200)
        } else {
          this.brandNames = []
        }
      },

      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.fetchData()
      },
      async save() {
        if (this.selectRows.length === 0) {
          this.$baseMessage('请选择商品', 'success')
          return
        }
        for (let i = 0; i < this.selectRows.length; i++) {
          let productStateId = this.selectRows[i].product_state_id
          if (productStateId !== 1001) {
            let msg =
              productStateId === 1002
                ? this.__('下架厂库中')
                : productStateId === 1003
                ? this.__('待审核')
                : this.__('违规禁售')
            this.$baseMessage(msg, 'error')
            return
          }
        }
        let param = this.getParam()
        const { msg, status } = await addItem(param)
        if (status === 200) {
          this.$baseMessage(msg, 'success')
          this.$emit('fetch-data')
          this.close()
        } else {
          this.$baseMessage(msg, 'error')
          return
        }
      },
      getParam() {
        let selectItem = this.selectRows.map((item) => item.item_id)
        let param = {
          item_id: JSON.stringify(selectItem),
          activity_id: this.activity_id,
        }
        return param
      },

      change(id) {
        this.queryForm.category_id = id
      },
    },
  }
</script>
