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

    <div class="filter-container">
      <el-cascader
        v-model="sysPlatform"
        class="filter-item"
        :options="permissionsSysOriginPlatformAlls"
        @change="changeSysOriginPlatform"
      />
      <el-select
        v-model="listQuery.payPlatform"
        placeholder="支付平台"
        style="width: 120px"
        class="filter-item"
        @change="renderDataChage"
      >
        <el-option
          v-for="item in payPlatform[listQuery.platform]"
          :key="item.value"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
      <el-select
        v-model="listQuery.groupName"
        placeholder="分组名称"
        style="width: 120px"
        class="filter-item"
        @change="renderDataChage"
      >
        <el-option
          v-for="item in productConfigGroupNames"
          :key="item.value"
          :label="item.name"
          :value="item.value"
        />
      </el-select>

      <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-input
        v-model.trim="listQuery.productPackage"
        placeholder="产品包名"
        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"
        @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
    >

      <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="handleUpdate(scope.row)">编辑</el-button>
            <el-dropdown>
              <span class="el-dropdown-link">
                更多
              </span>
              <el-dropdown-menu slot="dropdown">
                <!-- <el-dropdown-item @click.native="handleRecommend(scope.row)">
                  <span v-if="scope.row.groupName === 'CANDY'">{{ scope.row.recommend === true ? '取消推荐' : '推荐' }} </span>
                  <span v-else-if="scope.row.groupName === 'VIP'">推荐</span>
                </el-dropdown-item> -->
                <el-dropdown-item v-if="scope.row.showcase === false" @click.native="handlDel(scope.row, false)">删除</el-dropdown-item>
                <el-dropdown-item v-if="scope.row.showcase === false" @click.native="handlDel(scope.row, true)">同步删除</el-dropdown-item>
                <el-dropdown-item @click.native="handleEdit(scope.row)">修改包名</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <cnf-product-edit
      v-if="cnfProductVisible"
      :platform="listQuery.platform"
      :sys-origin="listQuery.sysOrigin"
      :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=''"
    />

    <edit-package
      v-if="editPackageVisible"
      :row="clickRow"
      @close="editPackageVisible=false"
    />
  </div>
</template>

<script>
// delByProductId
import { getProductConfigList, delProductConfig, updateSort } from '@/api/product'
import { productConfigGroupNames, productConfigShowcase, productTypes, platformOrigins, productTags, productPositions } from '@/constant/type'
import ProductRecommend from './recommend'
import { convertDescription } from '@/utils'
import { simpleElDropTable } from '@/utils/drop-table'
import CnfProductEdit from './edit'
import { copyText } from '@/utils'
import { mapGetters } from 'vuex'
import EditPackage from './edit-package'
export default {
  name: 'ProductPlatform',
  components: { ProductRecommend, CnfProductEdit, EditPackage },
  data() {
    return {
      editPackageVisible: false,
      payPlatform: {
        'iOS': [
          { value: 'Apple', name: 'Apple' }
        ],
        'Android': [
          { value: 'Google', name: 'Google' },
          { value: 'Huawei', name: 'Huawei' }
        ]
      },
      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: 'regionName',
          width: '80px'
        },
        {
          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'
        }
      ],
      recommendType: 1,
      recommendId: '',
      recommendProductId: '',
      recommendProductType: '',
      productRecommendVisible: false,
      clickRow: {},
      list: [],
      people: 0,
      listQuery: {
        productId: '',
        groupName: 'CANDY',
        showcase: true,
        productType: '',
        sysOrigin: '',
        platform: '',
        payPlatform: 'Apple',
        productPackage: '',
        region: ''
      },
      productConfigGroupNameMap: {},
      productConfigTypeMap: {},
      productConfigGroupNames,
      productConfigShowcase,
      productTags,
      productTypes,
      productPositions,
      platformOrigins,
      listLoading: true,
      sysOriginPlatforms: []
    }
  },
  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(true)
    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]
      getProductConfigList(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.cnfProductVisible = true
    },
    handleUpdate(row) {
      this.editId = row.id
      this.cnfProductVisible = true
    },
    handleEdit(item) {
      const that = this
      that.editPackageVisible = true
      that.clickRow = item
    },
    handlDel(row, sysncDel) {
      const that = this
      that.searchLoading = that.listLoading = false
      const tipsText = sysncDel ? '同步删除所有,将会删除所有与当前产品关联项, 您确定要删除吗?' : '将会删除所有与当前产品关联项, 您确定要删除吗？'
      this.$confirm(tipsText, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        delProductConfig({ id: row.id, sysOrigin: that.listQuery.sysOrigin, groupName: row.groupName, productId: sysncDel ? row.productId : '' }).then(res => {
          that.renderData()
          that.$opsMessage.success()
        }).catch(er => {
        })
      }).catch(() => {})
    },
    renderDataSuccess() {
      this.$message({
        message: 'Successful',
        type: 'success'
      })
      this.renderData()
    },
    handleRowClick(row) {
      this.clickRow = row
    },
    handleRecommend(row) {
      const that = this
      that.productRecommendVisible = true
      that.recommendId = row.id
      that.recommendProductId = row.productId
      that.recommendProductType = row.productType
      if (row.groupName === 'CANDY') {
        that.recommendType = row.recommend === true ? 2 : 1
      } else if (row.groupName === 'VIP') {
        that.recommendType = 1
      }
    },
    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)
      })
    },
    changeSysOriginPlatform(val) {
      this.listQuery.payPlatform = this.payPlatform[val[val.length - 1]][0].value
      this.renderDataChage()
    },
    renderDataChage() {
      this.renderData(true)
    },
    copyContent(text) {
      const that = this
      copyText(text).then(() => {
        that.$opsMessage.success()
      }).catch(er => {
        that.$opsMessage.fail()
      })
    }
  }
}
</script>
