<template>
  <div class="app-container-product-platform">

    <div class="filter-container">
      <el-cascader
        v-model="sysPlatform"
        class="filter-item"
        :options="permissionsSysOriginPlatformAlls"
        @change="renderDataChage"
      />

      <el-select
        v-model="listQuery.showcase"
        placeholder="状态"
        style="width: 120px"
        class="filter-item"
        @change="renderDataChage"
      >
        <el-option
          v-for="item in productConfigShowcase"
          :key="item.value"
          :label="item.name"
          :value="item.value"
        />
      </el-select>

      <el-select
        v-model="listQuery.productType"
        placeholder="产品类型"
        clearable
        style="width: 120px"
        class="filter-item"
        @change="renderDataChage"
      >
        <el-option
          v-for="item in productTypes"
          :key="item.value"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
      <el-input
        v-model.trim="listQuery.productId"
        placeholder="产品ID"
        style="width: 200px;"
        class="filter-item"
      />
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        :disabled="true"
        @click="handleCreate"
      >
        添加
      </el-button>
      <el-dropdown v-if="isDrag" v-loading="isDragLoading" class="filter-item">
        <el-button type="danger">
          保存排序<i class="el-icon-arrow-down el-icon--right" />
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="handleSort(false)">仅当前平台</el-dropdown-item>
          <el-dropdown-item @click.native="handleSort(true)">同步所有平台</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
      @cell-mouse-enter="handleMouseEnter"
    >

      <el-table-column
        v-for="(item, index) in col"
        :id="item.id"
        :key="`col_${index}`"
        :prop="item.prop"
        :label="item.label"
        align="center"
        :width="item.width"
      >
        <template slot-scope="scope">
          <div v-if="index === 0 && scope.row.recommend === true" class="seal-block seal-danger">推荐</div>
          <div v-if="item.prop === 'productId'">
            <el-link @click="copyContent(scope.row.productId)">{{ scope.row.productId }}</el-link>
          </div>
          <div v-else-if="item.prop === 'productType'">
            <el-link @click="copyContent(scope.row.productType)">{{ getTypeNames(scope.row.productType) }}</el-link>
          </div>
          <div v-else-if="item.prop === 'productPackage'">
            <el-link @click="copyContent(scope.row.productPackage)">{{ scope.row.productPackage }}</el-link>
          </div>
          <div v-else-if="item.prop === 'groupName'">
            {{ getGroupNames(scope.row.groupName) }}
          </div>
          <div v-else-if="item.prop === 'showcase'">
            <span v-if="scope.row.showcase === false">下架</span>
            <span v-if="scope.row.showcase === true">上架</span>
          </div>
          <div v-else>{{ scope.row[item.prop] }}</div>

          <div v-if="item.prop === 'operation'">
            <el-button type="text" @click.native="systemConfig(scope.row)">配置</el-button>
            <el-button type="text" @click="giftPackDetails(scope.row)">礼包详情</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <cnf-product-edit
      v-if="cnfProductVisible"
      :platform="listQuery.platform"
      :sys-origin="'x'"
      :edit-id="editId"
      @close="cnfProductVisible = false; editId='';"
      @success="renderData()"
    />

    <product-recommend
      v-if="productRecommendVisible"
      :id="recommendId"
      :product-id="recommendProductId"
      :platform="listQuery.platform"
      :sys-origin="listQuery.sysOrigin"
      :product-type="recommendProductType"
      :type="recommendType"
      :prompt="recommendPromptDesc"
      @success="productRecommendSuccess"
      @close="productRecommendVisible=false;recommendId='';recommendProductId='';recommendType=1;recommendProductType=''"
    />

    <gift-pack-config
      v-if="giftPackConfigVisable"
      :pack-id="giftPackId"
      :sys-origin="listQuery.sysOrigin"
      @close="giftPackConfigVisable=false"
      @success="renderDataSuccess"
    />

    <add-gift-pack-config
      v-if="addGiftPackConfigVisable"
      :sys-origin="listQuery.sysOrigin"
      @close="addGiftPackConfigVisable=false"
      @success="renderDataSuccess"
    />

    <gift-pack-deatils-drawer
      v-if="giftPackDeatilsDrawer"
      :row="thisRow"
      @close="giftPackDeatilsDrawer = false"
    />
  </div>
</template>

<script>
import { getProductConfigPackList, delProductConfig, updateSort } from '@/api/product'
import { productConfigGroupNames, productConfigShowcase, productTypes, platformOrigins, productTags, productPositions } from '@/constant/type'
import ProductRecommend from '@/views/cnf/product/product-platform/recommend'
import { convertDescription } from '@/utils'
import { simpleElDropTable } from '@/utils/drop-table'
import CnfProductEdit from '@/views/cnf/product/product-platform/edit'
import { copyText } from '@/utils'
import giftPackConfig from './config'
import addGiftPackConfig from './add'
import GiftPackDeatilsDrawer from '@/components/data/GiftPackDeatilsDrawer'
import { mapGetters } from 'vuex'

export default {
  name: 'ProductPlatform',
  components: { ProductRecommend, CnfProductEdit, giftPackConfig, addGiftPackConfig, GiftPackDeatilsDrawer },
  data() {
    return {
      giftPackId: '',
      giftPackConfigVisable: false,
      addGiftPackConfigVisable: false,
      giftPackDeatilsDrawer: false,
      thisRow: {},
      sysPlatform: [],
      editId: '',
      cnfProductVisible: false,
      isDragLoading: false,
      isDrag: false,
      col: [
        {
          label: '产品id',
          prop: 'productId'
        },
        {
          label: '描述',
          prop: 'description'
        },
        {
          label: '包名',
          prop: 'productPackage'
        },
        {
          label: '产品单价',
          prop: 'unitPrice',
          width: '80px'
        },
        {
          label: '获得糖果数量',
          prop: 'obtainCandy'
        },
        {
          label: '分组',
          prop: 'groupName'
        },
        {
          label: '产品类型',
          prop: 'productType'
        },
        {
          label: '平台',
          prop: 'platform',
          width: '80px'
        },
        {
          label: '优惠比率',
          prop: 'discountRate'
        },
        {
          label: '标签',
          prop: 'tags'
        },
        {
          label: '状态',
          prop: 'showcase'
        },
        {
          label: '序号',
          prop: 'sort',
          width: '50px'
        },
        {
          label: '创建时间',
          prop: 'createTime',
          width: '180px'
        },
        {
          label: '操作',
          prop: 'operation',
          width: '200px'
        }
      ],
      recommendType: 1,
      recommendId: '',
      recommendProductId: '',
      recommendProductType: '',
      productRecommendVisible: false,
      clickRow: {},
      list: [],
      people: 0,
      listQuery: {
        productId: '',
        groupName: 'GIFT_PACK',
        showcase: true,
        productType: '',
        sysOrigin: '',
        platform: ''
      },
      productConfigGroupNameMap: {},
      productConfigTypeMap: {},
      productConfigGroupNames,
      productConfigShowcase,
      productTags,
      productTypes,
      productPositions,
      platformOrigins,
      listLoading: true
    }
  },
  computed: {
    ...mapGetters(['permissionsSysOriginPlatformAlls', 'permissionsFirstSysOrigin']),
    recommendPromptDesc() {
      return this.recommendType === 1 ? '同时只能推荐一个产品，该产品被推荐将会取消上一个推荐产品是否继续？' : '是否确定取消推荐产品？'
    }
  },
  mounted() {
    this.rowDrop()
  },
  created() {
    const that = this

    if (!that.permissionsFirstSysOrigin) {
      return
    }
    that.listQuery.sysOrigin = that.permissionsFirstSysOrigin.value
    that.listQuery.platform = that.permissionsFirstSysOrigin.children[0].value
    that.sysPlatform = [that.listQuery.sysOrigin, that.listQuery.platform]
    that.renderData()
    that.productConfigGroupNames.forEach(item => {
      that.productConfigGroupNameMap[item.value] = item.name
    })
    that.productTypes.forEach(item => {
      that.productConfigTypeMap[item.value] = item.name
    })
  },
  methods: {
    renderData(isClean) {
      const that = this
      that.listLoading = true
      if (isClean === true) {
        that.listQuery.cursor = 1
      }
      that.listQuery.sysOrigin = that.sysPlatform[0]
      that.listQuery.platform = that.sysPlatform[1]
      getProductConfigPackList(that.listQuery).then(res => {
        that.listLoading = false
        const { body } = res
        that.list = body || []
        // that.total = body.total || 0
        // that.list = body.records
      })
    },
    getGroupNames(key) {
      return this.productConfigGroupNameMap[key]
    },
    getTypeNames(key) {
      return this.productConfigTypeMap[key]
    },
    handleSearch() {
      this.renderData(true)
    },
    handleCreate() {
      this.addGiftPackConfigVisable = true
    },
    systemConfig(row) {
      const that = this
      that.giftPackId = row.id
      that.giftPackConfigVisable = true
    },
    handlDel(id) {
      const that = this
      that.searchLoading = that.listLoading = false

      this.$confirm('您确定要删除该产品配置吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        delProductConfig(id, that.listQuery.sysOrigin).then(res => {
          that.renderData()
          that.$opsMessage.success()
        }).catch(er => {
        })
      }).catch(() => {})
    },
    renderDataSuccess() {
      this.$message({
        message: 'Successful',
        type: 'success'
      })
      this.renderData()
    },
    handleRowClick(row) {
      this.clickRow = row
    },
    productRecommendSuccess() {
      this.renderData()
      this.productRecommendVisible = false
    },
    convertPositionIndexName(value) {
      return convertDescription(value, this.productPositions)
    },
    rowDrop() {
      const that = this
      simpleElDropTable((event, type) => {
        if (event.newIndex === event.oldIndex) {
          return
        }
        that.list.splice(event.newIndex, 0, that.list.splice(event.oldIndex, 1)[0])
        const newArray = that.list.slice(0)
        that.list = []
        that.$nextTick(function() {
          that.list = newArray
        })
        that.isDrag = true
      })
    },
    handleGroupNameChange(value) {
      if (value === 'VIP') {
        this.form.showcase = true
      }
    },
    handleSort(allPlatform) {
      const that = this
      const list = that.list
      if (list.length <= 0) {
        return
      }

      const productConfigSorts = []
      const size = list.length
      for (let index = 0; index < size; index++) {
        const data = list[index]
        productConfigSorts.push({
          id: data.id,
          productId: data.productId,
          sort: size - index
        })
      }

      that.isDragLoading = true
      updateSort({
        productConfigSorts,
        allPlatform,
        sysOrigin: this.listQuery.sysOrigin
      }).then(res => {
        that.isDragLoading = false
        that.isDrag = false
      }).catch(er => {
        that.isDragLoading = false
        console.error('error', er)
      })
    },
    renderDataChage() {
      this.renderData(true)
    },
    handleMouseEnter(row) {
      this.thisRow = row
    },
    giftPackDetails(row) {
      this.giftPackDeatilsDrawer = true
    },
    copyContent(text) {
      const that = this
      copyText(text).then(() => {
        that.$opsMessage.success()
      }).catch(er => {
        that.$opsMessage.fail()
      })
    }
  }
}
</script>
