<template>
  <div class="department-management-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="4">
        <el-button
          v-show="selectRows.length > 0"
          icon="el-icon-plus"
          type="primary"
          @click="addBatchDist"
        >
          {{ __('批量分销') }}
        </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_name">
            <el-input
              v-model.trim="queryForm.product_name"
              clearable
              :placeholder="__('请输入商品名称')"
              style="width: 140px"
            />
          </el-form-item>
          <el-form-item prop="product_id">
            <el-input
              v-model.trim="queryForm.product_id"
              clearable
              :placeholder="__('请输入产品编号')"
              style="width: 140px"
            />
          </el-form-item>
          <el-form-item prop="store_name">
            <el-input
              v-model.trim="queryForm.store_name"
              clearable
              :placeholder="__('请输入所属店铺')"
              style="width: 140px"
            />
          </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: 140px"
            >
              <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>
            <tree-select
              ref="treeSelect"
              :checked-keys="defaultCheckedKeys"
              :check-strictly="true"
              clearable
              :data="data"
              :default-props="defaultProps"
              :height="300"
              :node-key="nodeKey"
              size="small"
              style="width: 140px"
              :width="220"
              @change="change"
            />
          </el-form-item>
          <el-form-item>
            <el-button 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" show-overflow-tooltip type="selection" />
      <el-table-column align="center" :label="__('操作')" width="185">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.product_is_dist === 0"
            type="success"
            @click="addDistProduct(scope.row.product_id)"
          >
            {{ __('我要分销') }}
          </el-button>
          <el-button v-if="scope.row.product_is_dist === 1" type="info">
            {{ __('已经分销') }}
          </el-button>

          <el-button type="default" @click="showPreview(scope.row)">
            {{ __('查看') }}
          </el-button>

        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :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="180"
      />
      <el-table-column
        align="center"
        :label="__('商品卖点')"
        prop="product_tips"
        show-overflow-tooltip
        width="150"
      />
      <el-table-column
        align="center"
        :label="__('供应价格')"
        prop="product_unit_price"
      />
      <el-table-column
        align="center"
        :label="__('市场价')"
        prop="product_market_price"
      />
      <el-table-column
        align="center"
        :label="__('建议零售价')"
        prop="product_advice_price"
      />
      <el-table-column align="center" :label="__('店铺编号')" prop="store_id" />
      <el-table-column
        align="center"
        :label="__('店铺名称')"
        prop="store_name"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :formatter="renderTime"
        :label="__('上架时间')"
        prop="product_sale_time"
        width="160"
      />
    </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" />
    <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 {
    addDistProduct,
    addBatchDistProduct,
    doDelete,
    editFiled,
    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'

  export default {
    name: 'ProductManagement',
    components: { TreeSelect, Table },
    data() {
      return {
        tableConfig: {
          height: window.innerHeight - 220 - 90,
        },
        dialogVisible: false,
        pc_url: '',
        params: {
          authorization: '',
        },
        defaultCheckedKeys: [],
        verifyOptions: [
          {
            value: 3000,
            label: this.__('未通过'),
          },
          {
            value: 3001,
            label: this.__('通过'),
          },
          {
            value: 3002,
            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,
          product_state_id: 1001,
          product_verify_id: 3001,
          store_is_open: 1,
          product_fx_enable: 1,
          store_type: 2,
        },
      }
    },
    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)
      },
      addDistProduct(product_id) {
        this.$baseConfirm(this.__('请确认是否分销此商品？'), null, async () => {
          const { msg, status } = await addDistProduct({
            product_id: product_id,
          })
          this.$baseMessage(msg, 'success', false, 'vab-hey-message-success')
          await this.fetchData()
        })
      },
      async addBatchDist() {
        let product_ids = this.selectRows.map((item) => item.product_id)
        const { msg, status } = await addBatchDistProduct({
          product_ids: product_ids.toString(),
        })

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

        await this.fetchData()
      },
      // 获取规格数据
      async getTree() {
        const { data } = await getTree()
        this.data = data
      },
      // 异步获取品牌数据
      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)
        this.$baseMessage(msg, 'success', false, 'vab-hey-message-success')
      },
      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)
        this.$baseMessage(msg, 'success', false, 'vab-hey-message-success')
      },
      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.__('否')
        }
      },
      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: 1001,
          product_verify_id: 3001,
          store_is_open: 1,
          product_fx_enable: 1,
          store_type: 2,
        }
        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
      },
      change(id) {
        this.queryForm.category_id = id
      },
      showPreview(row) {
        this.pc_url =
          process.env.VUE_APP_BASE_URL +
          '/product/detail?item_id=' +
          row.item_id
        this.dialogVisible = true
      },
    },
  }
</script>
