<template>
  <div
    class="wrap"
    :style="{ marginBottom: marginBottom + 'px' }">
    <p
      class="tb-title"
      v-if="tableType != 'Addon'"
      v-html="comTitle"></p>
    <div :class="getTableContainerClass">
      <el-table
        :show-header="tableType != 'Addon'"
        ref="elTable"
        :data="comTableData"
        style="width: 100%"
        :header-cell-style="{
          backgroundColor: '#fff',
          fontWeight: 'normal',
          fontSize: '14px',
          fontFamily: 'Proxima Nova',
          color: '#000',
          '--comDisplayCss': comDisplayCss,
        }"
        @selection-change="handleSelectionChange"
        @select="dialogCheck"
        row-key="id"
        :span-method="arraySpanMethod"
        :row-class-name="tableRowClassName">
        <el-table-column
          v-if="tableType != 'Comparison'"
          type="selection"
          width="50"
          align="center"
          :reserve-selection="true"
          :selectable="handleSelectable">
        </el-table-column>
        <template v-for="item in tableColumns">
          <el-table-column
            :align="item.align ? item.align : 'left'"
            v-if="item.type"
            :key="item.prop"
            :prop="item.prop"
            :label="item.label"
            :formatter="item.formatter"
            :width="item.width"
            :sortable="item.sortable">
            <template #default="{ row }">
              <template v-if="item.type == 'radioInput'">
                <div class="flex between">
                  <span>{{ row.decName }}</span>
                  <el-input
                    min="0" :max="row.max_num"
                    v-model="row.num"
                    type="number"
                    class="edit-input"
                    size="small"  @input="getNumber($event, row, row.max_num)"/>
                </div>
              </template>
              <div v-else>
                <template v-if="row.filter_boolean">
                  <div class="triangle"></div>
                  <div class="text">Eco</div>
                </template>
                {{ row[item.prop] }}
                <el-popover
                  v-if="tableType == 'Undecorated'"
                  placement="top-start"
                  trigger="hover">
                  <i class="el-icon-warning" slot="reference"></i>
                  <p class="popover-text">{{ comTitle }}</p>
                </el-popover>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            :align="item.align ? item.align : 'center'"
            v-if="!item.type"
            :key="item.prop"
            :prop="item.prop"
            :label="item.label"
            :formatter="item.formatter"
            :sortable="item.sortable"
            show-overflow-tooltip
            :width="(798 - tableColumns[0].width - tableColumns[0].extraWidth) /
              (tableColumns.length - 1)">
            <template #default="{ row, $index }">
              <div v-if="item.prop === 'website_setup'">
                <!-- 打印表用supplier -->
                <div v-if="$index === 0 && tableType == 'Decoration'">
                  <span v-if="row['supplier_setup_id'] < 5 || row['supplier_setup_id'] == 7">£ {{ row['supplier_setup']? parseFloat(row['supplier_setup']).toFixed(2) : "0.00" }}</span>
                  <span>{{
                    $_setupPriceFilter(row['supplier_setup_id'])
                  }}</span>
                </div>
                <div v-else>
                  <span v-if="row['website_setup_id'] < 5 || row['website_setup_id'] == 7">£ {{ row['website_setup']? parseFloat(row['website_setup']).toFixed(2) : "0.00" }}</span>
                  <span>{{
                    $_setupPriceFilter(row['website_setup_id'])
                  }}</span>
                </div>
              </div>
              <div
                v-else-if="
                  judgeProp(row, item.prop, $index) == '111' ||
                  judgeProp(row, item.prop, $index) == '111.00'
                ">
                -
              </div>
              <div
                v-else-if="
                  judgeProp(row, item.prop, $index) == '999' ||
                  judgeProp(row, item.prop, $index) === '999.00'
                ">
                POA
              </div>
              <div v-else-if="judgeProp(row, item.prop, $index) === ''">0</div>
              <div v-else>
                <span
                  v-if="
                    isNumber(judgeProp(row, item.prop, $index)) &&
                    !item.isFirstColumn
                  "
                  >£</span
                >
                <span>{{ judgeProp(row, item.prop, $index) }}</span>
              </div>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </div>
  </div>
</template>

<script>
import { times as npTimes,plus as npPlus, minus as npMinus } from 'number-precision';
export default {
  filters: {
    // Decoration Table：打印价格+附加价格
    multiplyPrice(a1, row, prop) {
      const rep = /^[0-9]+.?[0-9]*$/
      if (!rep.test(a1)) {
        return a1
      } else {
        return npTimes(a1, row.num)
      }
    },
    // Undecorated Table：基础价格+Decoration所选价格（包含附加价格）
    plusPrice(a1, a2) {
      return a2 ? npPlus(a1, a2) : a1
    },
    // Decoration Table：计算差价
    differencePrice(a1, row, prop, selectRow) {
      const rep = /^[0-9]+.?[0-9]*$/
      if (rep.test(a1)) {
        const temp = prop.split('_')

        const supplier = +row[`supplier_${temp[1]}`]
        const suppliers = npTimes(row.num - 1, supplier)
        const noIncludePrice = npPlus(a1, suppliers)

        const selSupplier = +selectRow[`supplier_${temp[1]}`]
        const selSuppliers = npTimes(selectRow.num - 1, selSupplier)
        const isIncludePrice = npPlus(+selectRow[prop], selSuppliers)

        return noIncludePrice > isIncludePrice
          ? `+${npMinus(noIncludePrice, isIncludePrice)}`
          : npMinus(noIncludePrice, isIncludePrice)
      } else {
        return a1
      }
    },
  },
  props: {
    hasDecAdd: {
      type: Number,
      default: 0,
    },
    tableData: {
      type: Array,
      default: () => {
        return []
      },
    },
    tableColumns: {
      type: Array,
      default: () => {
        return []
      },
    },
    operateWith: {
      type: String,
      default: '100%',
    },
    isCheckBox: {
      type: Boolean,
      default: false,
    },
    tableType: {
      type: String,
      default: 'Undecorated',
    },
    decorationObj: {
      type: Object,
      default: () => {
        return {}
      },
    },
    selectId: {
      type: Number,
      default: null
    },
    selectRow: {
      type: Object,
      default: () => {
        return {}
      },
    },
    multipleSelection: {
      type: Array,
      default: () => {
        return []
      },
    },
    selectDecoration: {
      type: Object,
      default: () => {
        return {}
      },
    },
    curPrint: {
      type: String,
      default: '',
    },
    curModel: {
      type: String,
      default: '',
    },
    marginBottom: {
      type: Number,
      default: 20,
    },
    decorationMultiple: {
      type: Number,
      default: 1,
    },
    headerShow: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      setupConfigList: [
        { id: 1, name: '/col' },
        { id: 2, name: '/desgin' },
        { id: 3, name: '/pos' },
        { id: 4, name: '/pos desgin' },
        { id: 5, name: 'POA' },
        { id: 6, name: 'Waived' },
      ],
      setupTitleList: ['1st', '2nd', '3rd'],
    }
  },
  computed: {
    getTableContainerClass() {
      // 根据tableType的值返回不同的class
      return {
        'table-container': true,
        'border-Decoration': this.tableType === 'Decoration' && this.hasDecAdd
      };
    },
    comTitle() {
      if (this.tableType === 'Undecorated') {
        return `Includes ${this.curModel}`
      } else if (this.tableType === 'Decoration') {
        return `Add-Ons`
      } else {
        return this.curPrint
      }
    },
    comDisplayCss() {
      return this.tableType === 'Comparison' ? '1px solid #efefef' : 'none'
    },
    comMultipleSelID() {
      return this.multipleSelection.map(i => i.id)
    },
    comTableData() {
      if (this.tableType === 'Decoration') {
        return this.tableData
      } else {
        return this.tableData
      }
    },
  },
  mounted() {
    // 初始勾上默认选择打印项
    if (JSON.stringify(this.selectRow) !== '{}') {
      this.$refs.elTable.toggleRowSelection(this.selectRow)
    }
  },
  methods: {
    judgeProp(row, prop, $index) {
      if (
        $index === 0 && this.tableType === 'Decoration'
      ) {
        const temp = prop.split('_')
        return row[`supplier_${temp[1]}`]
      } else {
        return row[prop]
      }
    },
    $_setupPriceFilter(setupPriceID) {
      const result = this.setupConfigList.filter(
        item => item.id === setupPriceID
      )
      return result.length > 0 ? result[0].name : ''
    },
    isNumber(val) {
      const rep = /^[0-9]+.?[0-9]*$/
      return rep.test(val)
    },
    /* 暂不实现此功能
    //点击table栏时选中按钮
    handleCurrentChange(currentRow, oldCurrentRow) {
      this.$refs.elTable.clearSelection()
      this.$emit('update:selectId', currentRow.id)
      this.addCar(currentRow)
    },
    */
    // table全选
    handleSelectionChange(val) {
      this.$emit('update:multipleSelection', val)
    },
    dialogCheck(selection, row) {
      if (this.isCheckBox) return // 是多选框返回
      this.$refs.elTable.clearSelection()
      // 初始化
      if (selection.length === 0) {
        this.$emit('update:selectId', null)
        this.$emit('update:selectRow', {})
        return
      }
      if (row) {
        this.$emit('update:selectId', row.id)
        this.$emit('update:selectRow', row)
        this.$refs.elTable.toggleRowSelection(row, true)
      }
    },
    addCar(currentRow) {
      // 加入购物车需要parentId
      const selrow = Object.assign({}, currentRow)
      selrow.parentId = this.decorationObj.parentId
      this.$emit('update:selectRow', selrow)
      this.$refs.elTable.toggleRowSelection(currentRow)
    },
    getRowKey(row) {
      return row.id
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      // 隐藏'Decoration'选项框
      if (this.tableType === 'Decoration' && columnIndex === 0) {
        return [0, 1]
      }
      if (this.tableType === 'Decoration' && columnIndex === 1) {
        return [1, 2]
      }
    },
    tableRowClassName({ row }) {
      if (this.tableType === 'Decoration') {
        return this.decorationMultiple ? 'borderNone' : 'hiddenRow'
      }
      return 'fontBold'
    },
    handleSelectable(row, index) {
      // website_setup_id 5为POA，不可选
      return row.website_setup_id !== 5;
    },
    getNumber(e, row, max) {
        if (parseInt(e) > max) {
          row.num = max
        }
    }
  },
}
</script>

<style lang="scss" scoped>
$deep-grey: #63676b;
$deep-blue: #1d4992;
.wrap {
  font-family: Arial;
}
.table-container {
  border-width: 1px 1px 4px;
  border-style: solid;
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
  border-color: transparent $deep-blue $deep-blue;
}
.border-Decoration {
  border-width: 1px 1px 1px !important;
  border-style: solid;
  border-radius: 0;
  border-color: transparent $deep-blue $deep-blue;
}
.tb-title {
  background-color: $deep-blue;
  color: #fff;
  font-size: 14px;
  text-align: center;
  padding: 9px 0;
  font-weight: bold;
}

.popover-text{
  font-size: 18px;
  padding: 10px;
  color: #000;
  font-weight: 600;
}
// 首行样式
:deep(th.is-leaf) {
  padding: 0 !important;
  .cell {
    padding: 4px 0 !important;
  }
}
// :deep(.is-left:nth-child(2)) {
//   border-right: 1px solid #efefef;
// }
// :deep(.is-center:nth-child(2)) {
//   border-right: 1px solid #efefef;
// }
// 无数据不显示No Data
:deep(.el-table__empty-block){
  display: none;
}
// 非首行样式
:deep(.el-table__header-wrapper) {
  .el-checkbox{
    display: none;
  }
}
:deep(.el-table__body) {
  color: #000;
  font-size: 14px;
  td {
    padding: 4px 0 !important;
  }
  .el-table__cell{
    padding: 8px 0 !important;
    // 选择框颜色
    .el-checkbox__inner,.el-input__inner{
      border: 1px solid $deep-blue;
    }
  }
  .el-table__cell:not(:first-child) {
    .cell {
      word-break: normal !important;
      padding: 0;
    }
  }
  // 打印表格首列
  .el-table__cell:first-child {
    font-weight: bold;
  }

  // el-table 内置函数返回样式
  .borderNone {
    td:nth-child(1) {
      // border-right: 1px solid #efefef;
      .edit-input {
        .el-input__inner {
          padding-left: 5px;
          padding-right: 0;
        }
      }
    }
    td:nth-child(2) {
      border-right: none;
    }
  }
  .fontBold {
    .el-table__cell:nth-child(2) {
      font-weight: bold;
    }
  }
  .hiddenRow {
    display: none;
  }
}
.edit-input {
  max-width: 42px;
}
.triangle{
    position: absolute;
    left:-50px;
    top: 0;
    width: 0; 
    height: 0;
    border-color: transparent #33AD60; 
    border-width: 0 0 25px 50px;
    border-style: solid;
  }
  .text{
    position: absolute;
    left:-47px;
    top: -2px;
    color: #fff;
    font-size: 10px;
  }
</style>
