<template>
  <div class="department-management-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="4">
        <el-button
          icon="el-icon-top"
          type="primary"
          @click="review(1001)"
        >
          {{ __('上架') }}
        </el-button>
        <el-button
          icon="el-icon-bottom"
          type="primary"
          @click="review(1002)"
        >
          {{ __('下架') }}
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="20">
        <el-form
          ref="form"
          :inline="true"
          :model="queryForm"
          @submit.native.prevent
        >
          <el-form-item prop="product_verify_id">
            <el-select
              v-if="false"
              v-model.trim="queryForm.product_verify_id"
              clearable
              :placeholder="__('审核状态')"
              style="width: 100px"
            >
              <el-option
                v-for="item in verifyOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-radio-group v-model="queryForm.product_verify_id" @change="queryData">
              <el-radio-button v-for="item in verifyOptions" :key="item.value" :label="item.value" >{{item.label}}</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="product_name">
            <el-input
              v-model.trim="queryForm.product_name"
              clearable
              :placeholder="__('商品名称')"
              style="width: 120px"
            />
          </el-form-item>
          <el-form-item prop="product_id">
            <el-input
              v-model.trim="queryForm.product_id"
              clearable
              :placeholder="__('产品编号')"
              style="width: 100px"
            />
          </el-form-item>
          <el-form-item v-if="false" prop="product_number">
            <el-input
              v-model.trim="queryForm.product_number"
              clearable
              :placeholder="__('商品货号')"
              style="width: 100px"
            />
          </el-form-item>
          <el-form-item prop="store_name">
            <el-input
              v-model.trim="queryForm.store_name"
              clearable
              :placeholder="__('所属店铺')"
              style="width: 100px"
            />
          </el-form-item>
          <el-form-item prop="brand_id">
            <el-select
              v-model="queryForm.brand_id"
              clearable
              filterable
              :loading="loading"
              :placeholder="__('品牌名称')"
              remote
              :remote-method="remoteMethod"
              style="width: 100px"
            >
              <el-option
                v-for="item in options"
                :key="item.brand_id"
                :label="item.brand_name"
                :value="item.brand_id"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="product_state_id">
            <el-select
              v-model.trim="queryForm.product_state_id"
              clearable
              :placeholder="__('产品状态')"
              style="width: 100px"
            >
              <el-option
                v-for="item in stateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <tree-select
              ref="treeSelect"
              :checked-keys="defaultCheckedKeys"
              clearable
              :data="data"
              :default-props="defaultProps"
              :height="300"
              :node-key="nodeKey"
              size="small"
              style="width: 120px"
              :width="220"
              @change="change"
            />
          </el-form-item>
          <el-form-item>
            <el-button v-if="false" icon="el-icon-delete" type="primary" @click="clearData">
              {{ __('清空') }}
            </el-button>
            <el-button icon="el-icon-search" type="primary" @click="queryData">
              {{ __('查询') }}
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>
    <el-table
      v-loading="listLoading"
      border
      :data="list"
      :height="tableConfig.height"
      row-key="product_id"
      style="width: 100%"
      @cell-click="tabClick"
      @expand-change="loadItems"
      @selection-change="setSelectRows"
    >
      <el-table-column
        align="center"
        fixed
        show-overflow-tooltip
        type="selection"
      />
      <el-table-column
        align="center"
        fixed="left"
        :label="__('操作')"
        width="200px"
      >
        <template #default="{ row }">
          <el-button type="text" @click="showTable(row)">
            {{ __('SKU') }}
          </el-button>
          <el-button
            v-if="row.product_state_id === 1000"
            type="text"
            @click="handleDelete(row)"
          >
            {{ __('删除') }}
          </el-button>
          <el-button
            v-if="row.product_state_id !== 1000"
            type="text"
            @click="outOfStock(row)"
          >
            {{ __('下架') }}
          </el-button>
          <el-button type="text" @click="spxx(row)">
            {{ __('详细') }}
          </el-button>
          <el-button
            :disabled="row.product_verify_id !== 3002"
            type="text"
            @click="reviewEdit(row)"
          >
            {{ __('审核') }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column fixed="left" type="expand">
        <template slot-scope="props">
          <el-table
            ref="multipleTable"
            v-loading="loading"
            :data="props.row.productItems"
          >
            <el-table-column :label="__('商品编号')" prop="item_id" />
            <el-table-column
              :formatter="formatDefault"
              :label="__('是否默认')"
              prop="item_is_default"
            />
            <el-table-column :label="__('规格名称')" prop="item_name" />
            <el-table-column :label="__('商品价格')" prop="item_unit_price" />
            <el-table-column :label="__('商品库存')" prop="item_quantity" />
            <el-table-column
              :formatter="formatEnable"
              :label="__('是否启用')"
              prop="item_enable"
            />
          </el-table>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        fixed="left"
        :label="__('产品编号')"
        prop="product_id"
      />
      <el-table-column
        align="center"
        :label="__('商品主图')"
        prop="product_image"
      >
        <template slot-scope="scope">
          <el-popover placement="top-start" title="" trigger="hover">
            <img
              alt=""
              :src="scope.row.product_image"
              style="width: 150px; height: 150px"
            />
            <img
              slot="reference"
              :src="scope.row.product_image"
              style="width: 30px; height: 30px"
            />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="__('产品名称')"
        prop="product_name"
        show-overflow-tooltip
        width="200"
      />
      <el-table-column
        v-if="false"
        align="center"
        :label="__('商品卖点')"
        prop="product_tips"
        show-overflow-tooltip
        width="150"
      />
      <el-table-column align="center" :label="__('店铺编号')" prop="store_id" />
      <el-table-column
        align="center"
        :label="__('店铺名称')"
        prop="store_name"
        show-overflow-tooltip
        width="150"
      />
      <el-table-column
        v-if="false"
        align="center"
        :label="__('市场价')"
        prop="product_market_price"
      />
      <el-table-column
        v-if="false"
        align="center"
        :label="__('商品单价')"
        prop="product_unit_price"
      />
      <el-table-column
        align="center"
        :label="__('商品审核')"
        prop="product_verify_id"
        width="100"
      >
        <template #default="{ row }">
          <el-tag :type='({"3000":"warning","3001":"success","3002":"info"})[row.product_verify_id]'>
            {{ ({"3000":"未通过","3001":"通过","3002":"待审核"})[row.product_verify_id] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="__('商品状态')"
        prop="product_state_id"
        width="100"
      >
        <template slot-scope="scope">
          <span
            v-if="
              scope.row.product_id === tabClickIndex &&
              scope.column.id === columnId
            "
          >
            <el-select
              v-model="scope.row.product_state_id"
              @change="stateChange(scope.row)"
            >
              <el-option
                v-for="item in stateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </span>
          <span v-else>
            <el-tag :type='({"1001":"success","1002":"info","1000":"warning"})[scope.row.product_state_id]'>
            {{ ({"1001":"销售中","1002":"仓库中","1000":"违规禁售"})[scope.row.product_state_id] }}
            </el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :formatter="renderTime"
        :label="__('上架时间')"
        prop="product_sale_time"
        width="180"
      />
      <el-table-column
        v-if="false"
        align="center"
        :label="__('供应状态')"
        prop="product_fx_enable"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.product_fx_enable"

            :active-value="1"

            :inactive-value="0"
            @change="sChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        v-if="false"
        align="center"
        :label="__('允许分销')"
        prop="product_dist_enable"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.product_dist_enable"

            :active-value="1"

            :inactive-value="0"
            @change="sChangeDist(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="__('佣金比率')"
        prop="product_commission_rate"
        width="100px"
      >
        <template slot-scope="scope">
          <span
            v-if="
              scope.row.product_id === tabClickIndex &&
              scope.column.id === columnId
            "
          >
            <el-input
              ref="editInput"
              v-model="scope.row.product_commission_rate"
              @blur.stop="inputBlurProductCommissionRate(scope.row)"
            />
          </span>
          <span v-else>{{ scope.row.product_commission_rate }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="__('商品排序')"
        prop="product_order"
      >
        <template slot-scope="scope">
          <span
            v-if="
              scope.row.product_id === tabClickIndex &&
              scope.column.id === columnId
            "
          >
            <el-input
              ref="editInput"
              v-model="scope.row.product_order"
              @blur.stop="inputBlurOtrder(scope.row)"
            />
          </span>
          <span v-else>{{ scope.row.product_order }}</span>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      :current-page="queryForm.pageNum"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <Table ref="Table" />
    <StockTable ref="StockTable" @fetch-data="fetchData" />
    <ReviewEdit ref="ReviewEdit" @fetch-data="fetchData" />

    <el-dialog
      :append-to-body="true"
      custom-class="center-dialog"
      height="50%"
      title="商品预览"
      top="0vh"
      :visible.sync="dialogVisible"
      width="90%"
    >
      <iframe
        frameborder="0"
        height="700px"
        :src="pc_url"
        width="100%"
      ></iframe>
    </el-dialog>
  </div>
</template>

<script>
import {
  doDelete,
  doEdit,
  editFiled, editState,
  enable,
  getList,
} from '@/api/product/base'
  import { getList as getItemList } from '@/api/product/item'
  import { getTree } from '@/api/base/product/category'
  import { renderTime } from '@/utils/date'
  import { getBrands } from '@/api/base/product/brand'
  import TreeSelect from '@/components/treeSelect'
  import { translateTitle as __ } from '@/utils/i18n'
  import Table from './components/ProductItemTable'
  import StockTable from './components/OutOfStockTable'
  import ReviewEdit from './components/ReviewEdit'

  export default {
    name: 'ProductManagement',
    components: { TreeSelect, Table, StockTable, ReviewEdit },
    data() {
      return {
        tableConfig: {
          height: window.innerHeight - 220 - 90,
        },
        dialogVisible: false,
        pc_url: '',
        defaultCheckedKeys: [],
        verifyOptions: [
          {
            value: null,
            label: this.__('全部'),
          },
          {
            value: 3002,
            label: this.__('待审核'),
          },
          {
            value: 3000,
            label: this.__('拒绝'),
          },
          {
            value: 3001,
            label: this.__('通过'),
          },
        ],
        stateOptions: [
          {
            // 1001-正常;1002-下架仓库中;1000-违规禁售
            value: 1001,
            label: this.__('销售中'),
          },
          {
            value: 1002,
            label: this.__('仓库中'),
          },
          {
            value: 1000,
            label: this.__('违规禁售'),
          },
        ],
        data: [], // 产品规格数据
        defaultProps: {
          children: 'children',
          label: 'label',
        },
        nodeKey: 'id',
        loading: true,
        options: [], // 品牌数据
        tabClickIndex: null, // 点击的行
        columnId: null, // 点击的列
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        queryForm: {
          pageNum: 1,
          pageSize: 20,
        },
      }
    },
    created() {
      let query = this.$route.query
      if (query.product_verify_id) {
        this.queryForm.product_verify_id = Number(query.product_verify_id)
      }
      this.queryData()
      this.getTree()
    },
    methods: {
      __,
      showTable(row) {
        this.$refs['Table'].showTable(row)
      },
      outOfStock(row) {
        this.$refs['StockTable'].showTable(row)
      },
      reviewEdit(row) {
        this.$refs['ReviewEdit'].showTable(row)
      },
      async stateChange(row) {
        // 保存数据
        let param = {
          product_id: row.product_id,
          product_state_id: row.product_state_id,
          enable_name: 'product_state_id',
          enable_id: 'product_id',
        }
        const { msg, status } = await enable(param)
        this.$baseMessage(msg, 'success', false, 'vab-hey-message-success')
        this.tabClickIndex = null
        this.columnId = null
        this.fetchData()
      },
      // 获取规格数据
      async getTree() {
        const { data } = await getTree()
        this.data = data
      },
      async spxx(row) {
        this.pc_url =
          process.env.VUE_APP_BASE_URL +
          '/product/detail?item_id=' +
          row.item_id
        this.dialogVisible = true
      },
      // 异步获取品牌数据
      async remoteMethod(queryParam) {
        if (queryParam.trim() !== '') {
          this.loading = true
          const { data } = await getBrands({ brand_name: queryParam.trim() })
          this.options = data
          this.loading = false
        } else {
          this.options = []
        }
      },
      // async sChange(row) {
      //   // 保存数据
      //   await this.doEdit(row)
      // },
      async sChange(row) {
        const param = {
          product_id: row.product_id,
          product_fx_enable: row.product_fx_enable,
          enable_name: 'product_fx_enable',
          enable_id: 'product_id',
        }

        const { msg, status } = await enable(param)

        if (200 == status) {
          this.$baseMessage(msg, 'success')
        } else {
          this.$baseMessage(msg, 'error')
        }
      },
      async sChangeDist(row) {
        const param = {
          product_id: row.product_id,
          product_dist_enable: row.product_dist_enable,
          enable_name: 'product_dist_enable',
          enable_id: 'product_id',
        }

        const { msg, status } = await enable(param)

        if (200 == status) {
          this.$baseMessage(msg, 'success')
        } else {
          this.$baseMessage(msg, 'error')
        }
      },

      async review(product_state_id) {
        if (this.selectRows.length > 0) {
          let product_id = this.selectRows.map((item) => item.product_id)
          const { msg, status } = await editState({
            product_state_id: product_state_id,
            product_id: product_id.toString(),
          })

          if (200 == status) {
            this.$baseMessage(msg, 'success')
          } else {
            this.$baseMessage(msg, 'error')
          }

          await this.fetchData()
        } else {
          this.$baseMessage(this.__('未选中任何行'), 'error')
          return false
        }
      },

      handleDelete(row) {
        this.$baseConfirm(this.__('你确定要删除当前项吗'), null, async () => {
          const { msg, status } = await doDelete({ product_id: row.product_id })
          if (200 == status) {
            this.$baseMessage(msg, 'success')
          } else {
            this.$baseMessage(msg, 'error')
          }
          await this.fetchData()
        })
      },
      // 添加明细原因 row 当前行 column 当前列
      tabClick(row, column, cell, event) {
        this.tabClickIndex = row.product_id
        this.columnId = column.id
        // inout 获取焦点
        this.$nextTick(() => {
          if (!this.$refs['editInput']) return
          this.$refs['editInput'].focus()
        })
      },
      async inputBlurProductCommissionRate(row) {
        this.tabClickIndex = null
        this.columnId = null
        // 保存数据
        let param = {
          product_commission_rate: row.product_commission_rate,
          id: row.product_id,
          oper: 'oper',
        }
        const { msg, status } = await editFiled(param)
        this.$baseMessage(msg, 'success', false, 'vab-hey-message-success')
      },
      async inputBlurOtrder(row) {
        this.tabClickIndex = null
        this.columnId = null
        // 保存数据
        let param = {
          product_order: row.product_order,
          id: row.product_id,
          oper: 'oper',
        }
        const { msg, status } = await editFiled(param)
        this.$baseMessage(msg, 'success', false, 'vab-hey-message-success')
      },
      async loadItems(row, expanded) {
        if (expanded.length !== 0) {
          this.loading = true
          const { data } = await getItemList({
            product_id: row.product_id,
          })
          row.productItems = data.items
          this.loading = false
        }
      },
      // 格式化时间
      renderTime(row) {
        return renderTime(row.product_sale_time)
      },
      formatDefault(row) {
        if (row.item_is_default) {
          return this.__('是')
        } else {
          return this.__('否')
        }
      },
      formatVerify(row) {
        switch (row.product_verify_id) {
          case 3001:
            return this.__('通过')
          case 3002:
            return this.__('待审核')
          case 3000:
            return this.__('未通过')
          default:
            return ''
        }
      },
      formatState(row) {
        switch (row.product_state_id) {
          case 1001:
            return this.__('销售中')
          case 1002:
            return this.__('仓库中')
          case 1000:
            return this.__('违规禁售')
          default:
            return ''
        }
      },
      formatEnable(row) {
        return row.item_enable === 1001
          ? this.__('销售中')
          : row.item_enable === 1002
          ? this.__('仓库中')
          : this.__('违规禁售')
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.fetchData()
      },
      queryData() {
        this.queryForm.pageNum = 1
        this.fetchData()
      },
      clearData() {
        this.queryForm = {
          product_name: null,
          product_id: null,
          product_number: null,
          store_name: null,
          brand_id: null,
          product_state_id: null,
          product_verify_id: null,
        }
        this.$refs.treeSelect.clearSelectedNode()
      },
      // 初始化表格数据
      async fetchData() {
        this.listLoading = true
        const { data } = await getList(this.queryForm)
        this.list = data.items
        this.total = data.records
        this.listLoading = false
      },
      async doEdit(row) {
        const saveForm = {
          product_state_id: row.product_state_id,
          product_id: row.product_id,
          product_fx_enable: row.product_fx_enable,
          product_dist_enable: row.product_dist_enable,
          product_commission_rate: row.product_commission_rate,
          product_order: row.product_order,
          defaultCheckedKeys: [],
        }
        const { msg, status } = await doEdit(saveForm)
        this.$baseMessage(msg, 'success', false, 'vab-hey-message-success')
      },
      change(id) {
        this.queryForm.category_id = id
      },
    },
  }
</script>
