<template>
  <div class="ff-matrix--table">
    <div class="ff-matrix--head">
      <span>商品编码︰{{productCode}}</span>
      <span class="ff-matrix--clear" @click="handleClearInputCount"><Icon type="ios-trash-outline" />清空</span>
    </div>

    <div class="ff-matrix--table-content">
      <table>
        <thead>
          <tr class="ff-matrix--edit-color">
            <th class="ff-matrix-th-head">
              <div class="ff-matrix-th-head-box">
                <span>颜色</span>
                <span>尺寸</span>
              </div>
            </th>
            <th v-for="size of tHead">
              {{ size.name }}
            </th>
            <th class="ff-matrix-font--red">
              行合计
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(value, key, index) of tBody">
            <td class="ff-matrix--edit-color">
              {{key}}
            </td>
            <td v-for="(list, sub) of tHead" class="ff-matrix--table-align">
              <ul>
                <li v-if="value[list.name].disabled" class="ff-matrix--table-disabled">
                  <span></span>
                </li>
                <li v-else class="ff-matrix--table-compile">
                  <input 
                    class="ff-matrix--input"
                    :id="`matrixCountInput-${index}-${sub}`"
                    :data-id="`${index}-${sub}`"
                    v-model="value[list.name].count"
                    @focus="handleInputFocus($event)"
                    @keyup.enter="handleKeyUpEnter"
                  >
                </li>
              </ul>
            </td>
            <td class="ff-matrix--table-align ff-matrix-font--red">
              <ul>
                <li>{{ calculateRow(value) }}</li>
              </ul>
            </td>
          </tr>
          <tr class="ff-matrix--table-total">
            <td class="ff-matrix--edit-color">
              合计
            </td>
            <td
              v-for="size of tHead"
              class="ff-matrix--table-align"
            >
            {{ calculateLine(size) }}
            </td>
            <td>{{ calculateTotal() }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="ff-matrix--footer">
      <span class="ff-matrix--des"></span>
      <span>该矩形框表示︰条码档案不存在该条码！</span>
    </div>
    <div class="ff-matrix--box-btn">
      <Button
        :loading="loading"
        type="posdefault"
        style="margin-right:10px"
        @click="handleMatrixConfirm"
      >
        确定
      </Button>
      <Button
        type="fcdefault"
        @click="handleMatrixCancel"
      >
        取消
      </Button>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .span-style () {
    display: inline-block;
    width: 62px;
    height: 18px;
    box-sizing: border-box;
    padding: 0 4px;
    border-radius: 2px;
    border: 1px solid #e6e6e6;
    background-color: #f4f4f4;
  }

  .ff-matrix--min-table {
    max-width: 760px;
  }

  .ff-matrix--table {
    user-select: none;
    font-size: 12px;
    color: #575757;
    user-select: none;
    margin: 10px;

    .ff-matrix--active-one {
      background-color: #f9c89b;
    }

    .ff-matrix--active-two {
      background-color: #9bd0fc;
    }

    .ff-matrix--active-three {
      background-color: #aab5f7;
    }

    .ff-matrix--active-four {
      background-color: #c1e6b0;
    }

    input[type="radio"] {
      transform: translateY(2px);
    }

    .ff-matrix--head {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .ff-matrix--head-no-data {
      margin-bottom: 10px;
    }

    .ff-matrix--clear {
      display: inline-block;
      cursor: pointer;
      color: #0089ea;

      i {
        font-size: 16px;
      }
    }

    .ff-matrix--matching {
      .ff-matrix--radio-one {
        margin: 0 10px 0 5px;
      }
    }

    .ff-matrix--choose {
      display: flex;
      justify-content: space-between;
      margin: 16px 0 6px;

      & > span {
        display: flex;
        align-items: center;
      }

      .ff-matrix--active-label {
        padding: 0 10px;
        border-radius: 2px;
        box-sizing: border-box;
        min-width: 63px;
        height: 20px;
        line-height: normal;
        display: flex;
        align-items: center;
        margin: 0 2px 0 4px;

        input {
          margin-top: 2px;
        }
      }
    }

    .ff-matrix--reveal-choose {
      padding: 6px 0 12px 14px;

      .ff-matrix--radio-one {
        margin-right: 16px;
      }
    }

    .ff-matrix--table-content {
      overflow: scroll;
      margin-top: 10px;
      .ff-matrix-font--red {
        color: #ed3838;
      }

      table {
        width: 100%;

        th {
          height: 34px;
          font-weight: bold;
        }

        th,
        td {
          border: 1px solid #e6e6e6;
          min-width: 80px;
          text-align: center;
          box-sizing: border-box;
          vertical-align: middle;
        }

        .ff-matrix-th-head {
          background: url("/static/img/matrix.jpg") no-repeat;
          background-size: 100% 100%;
          width: 100px;
          .ff-matrix-th-head-box {
            display: flex;
            align-items: center;
            height: 100%;

            span {
              flex: 1;
              text-align: center;
            }

            span:first-child {
              padding-top: 10px;
            }

            span:last-child {
              padding-bottom: 10px;
            }
          }
        }

        tr td:first-child {
          font-weight: bold;
        }

        .ff-matrix--table-align {
          text-align: center;

          li {
            min-height: 24px;

            max-height: 24px;
            border-bottom: 1px solid #e6e6e6;
            /*padding: 3px 14px;*/
            padding: 2px;
            box-sizing: border-box;
            text-align: center;
            line-height: 20px;

            &:last-child {
              border-bottom: none;
            }
          }

          .ff-matrix--table-reveal {
          }

          .ff-matrix--table-disabled {
            /*background-color: #F4F4F4;*/
            font-size: 0;
            color: #575757;

            span {
              display: inline-block;
              height: 20px;
              box-sizing: border-box;
              width: 100%;
              border: 1px solid #e6e6e6;
              background-color: #f4f4f4;
              font-size: 12px;
              line-height: 1.4;
              color: #575757;
            }
          }

          .ff-matrix--table-compile {
            position: relative;
            display: flex;
            justify-content: center;
            line-height: 1;

            input {
              /*width: calc(~"100% + 2px");*/
              /*position: absolute;*/
              /*width: 90px;*/
              width: 100%;
              height: 20px;
              box-sizing: border-box;
              padding: 0 4px;
              /*left: -1px;*/
              color: #575757;
              /*border: none;
                border-left: 1px solid #E6E6E6;
                border-right: 1px solid #E6E6E6;*/
              border: 1px solid #e6e6e6;
              transition: border-color 0.2s ease;
              text-align: center;

              &:focus {
                border: 1px solid #0f8ee9;
                /*height: 20px;*/
                /*z-index: 1;
                  top: -1px;*/
              }
            }

            .ff-matrix--input-tip {
              &:focus {
                border-color: #e80000;
              }
            }

            .ff-input--prompt {
              position: absolute;
              top: 100%;
              left: 50%;
              width: 140px;
              margin-top: 7px;
              transform: translateX(-50%);
              border-radius: 4px;
              padding: 7px 8px;
              z-index: 1;
              background-color: #fff;
              border: 1px solid #d8d8d8;

              &::before {
                position: absolute;
                content: "";
                width: 8px;
                height: 8px;
                top: -5px;
                border: 1px solid #d8d8d8;
                left: 50%;
                margin-right: 2px;
                border-bottom-color: transparent;
                border-right-color: transparent;
                background-color: #fff;
                transform: translateX(-50%) rotate(45deg);
              }

              i {
                font-size: 16px;
                color: #e80000;
              }
            }

            .ff-matrix--input-disabled {
              background-color: #f4f4f4;
            }
          }
        }
      }

      .ff-matrix--table-total {
        height: 25px;
        color: #ed3838;

        td {
          padding: 3px 14px;
        }
      }

      .ff-matrix--edit-color {
        background-color: #f5f6fa;
      }
    }

    /*以上公共样式*/
    .ff-matrix--edit-reveal {
      table {
        th,
        td {
          border-color: #d8d8d8;
        }

        .ff-matrix--table-align {
          li {
            border-color: #d8d8d8;
          }

          .ff-matrix--table-disabled {
            span {
              border-color: #d8d8d8;
            }
          }

          .ff-matrix--table-compile {
            input {
              border-color: #d8d8d8;
            }
          }
        }
      }
    }

    /*纯编辑和纯展示时候的样式*/
    .ff-matrix--footer {
      margin: 10px 0 20px;
      /*padding-left: 15px;*/
      box-sizing: border-box;

      i {
        color: #e80000;
        font-size: 15px;
      }

      .ff-matrix-hint {
        color: #e80000;
      }

      .ff-matrix--des {
        .span-style();
        width: 32px;
        height: 14px;
        vertical-align: middle;
        margin: 0 3px 1px;
      }
    }

    .ff-matrix--box-btn {
      padding-bottom: 10px;
    }

    .ff-matrix--box-btn,
    .ff-matrix--reveal,
    .ff-matrix--matching {
      text-align: right;

      .ff-matrix-btn {
        padding: 6px 21px;
        border-radius: 2px;
        box-sizing: border-box;
        user-select: none;
        /*transition: all .2s ease;*/
      }

      .ff-matrix-btn-confirm {
        background-color: #fd6442;
        margin-right: 3px;
        color: #fff;

        &:hover {
          background-color: rgba(253, 100, 66, 0.7);
        }
      }

      .ff-matrix-btn-cancel {
        color: #fd6442;
        padding: 3px 20px;
        border: 1px solid #fd6442;
        background-color: #fff;

        &:hover {
          opacity: 0.5;
        }

        &:first-child:focus {
          opacity: 0.5;
        }
      }

      .ff-btn-disabled {
        cursor: not-allowed;
        background-color: #e6e6e6;
        border: 1px solid #d8d8d8;

        &:hover {
          opacity: 1;
        }
      }
    }

    .ff-matrix--reveal {
      text-align: left;

      table {
        vertical-align: bottom;
        width: auto;
        display: inline-block;

        th,
        td {
          min-width: 63px;
        }

        .ff-matrix--table-align {
          /*li {
              padding: 3px 4px;
            }*/
        }
      }

      .ff-matrix--table-total {
        td {
          padding: 3px 4px;
        }
      }

      .ff-matrix-btn-cancel {
        padding: 4px 8px;
        margin-left: 15px;
      }
    }

    /*纯展示时候的样式*/
  }
</style>
<style>
  .ff-input--prompt {
    color: #575757;
  }
</style>

<script>
  const R3 = window.R3;
  const { network, urlSearchParams, store } = R3;

  export default {
    props: {
      productId: {
        type: String,
        default: ''
      },
      productCode: {
        type: String,
        default: ''
      },
      options: {
        type: Object
      }
    },
    data() {
      return {
        SKUID: [],
        tHead: [],
        tBody: {},
        tColor: [],
        inputElList: [],
        inputFocusIndex: 0,
        loading: false
      }
    },
    methods: {
      async apiFetchMatrixData() {
        try {
          const { data } = await network.post('/p/c/drp/getMatrixProduct', {productId: this.productId})
          const tHead = data.data.SIZE.map(v => Object.assign(v, {id: v.ID, name: `${v.ECODE}/${v.ENAME}`}))
          this.tHead = tHead.sort((a, b) => {
            if (a.MATRIXCOL !== 0 && !a.MATRIXCOL) {
              return 1
            }
            if (b.MATRIXCOL !== 0 && !b.MATRIXCOL) {
              return -1
            }
            return a.MATRIXCOL - b.MATRIXCOL
          })
          this.tColor = data.data.COLOR.map(v => Object.assign(v, {id: v.ID, name: `${v.ECODE}/${v.ENAME}`}))
          this.SKUID = data.data.SKU

          this.tColor.map((obj, index) => {
            this.$set(this.tBody, [obj.name], {})
            this.tHead.map((list, sub) => {
              const skuObj = this.SKUID.find(
                v => v.PS_C_CLR_ID === obj.id && v.PS_C_SIZE_ID === list.id
              )
              if (skuObj === undefined) {
                this.$set(this.tBody[obj.name], [list.name], {
                  ID: -1,
                  count: '', // 数量
                  TAG: `${index}-${sub}`, // 唯一标识符
                  disabled: true
                })
              } else {
                this.$set(this.tBody[obj.name], [list.name], {
                  ID: -1,
                  count: '', // 数量
                  TAG: `${index}-${sub}`, // 唯一标识符
                  ...skuObj,
                  disabled: false
                })
              }
            })
          })

          this.$nextTick(() => {
            this.inputElList = Array.from(this.$el.querySelectorAll('.ff-matrix--input'))
            if (this.inputElList.length > 0) {
              this.$el.addEventListener('keydown', this.handleKeyDown)
              this.$el.querySelectorAll('.ff-matrix--input')[0].focus()
            }
          })
        } catch {}
      },
      handleKeyDown(e) {
        // tab按键
        if (e.keyCode === 9) {
          if (this.inputElList.length === 0) return
          this.inputFocusIndex === this.inputElList.length - 1
            ? this.inputElList[(this.inputFocusIndex = 0)].focus()
            : this.inputElList[(this.inputFocusIndex += 1)].focus();
          e.preventDefault(); // 阻止默认事件
          e.stopPropagation(); // 防止事件冒泡
        }
        // 上按键
        if (e.keyCode === 38) {
          const arr = this.inputElList[this.inputFocusIndex].dataset.id.split('-');
          const index = this.inputElList.findIndex((n) => {
            const data = n.dataset.id.split('-');
            return data[1] === arr[1] && arr[0] - 1 == data[0];
          });
          if (index === -1) return;
          this.inputFocusIndex = index;
          this.inputElList[this.inputFocusIndex].focus();
        }
        // 下按键
        if (e.keyCode === 40) {
          const arr = this.inputElList[this.inputFocusIndex].dataset.id.split('-');
          const index = this.inputElList.findIndex((n) => {
            const data = n.dataset.id.split('-');
            return data[1] === arr[1] && Number.parseInt(arr[0]) + 1 == data[0];
          });
          if (index === -1) return;
          this.inputFocusIndex = index;
          this.inputElList[this.inputFocusIndex].focus();
        }
        // 左按键
        if (e.keyCode === 37) {
          this.inputFocusIndex === 0 ? '' : this.inputElList[(this.inputFocusIndex -= 1)].focus();
        }
        // 右按键
        if (e.keyCode === 39) {
          this.inputFocusIndex === this.inputElList.length - 1 ? '' : this.inputElList[(this.inputFocusIndex += 1)].focus();
        }
      },
      handleKeyUpEnter() {
        this.inputFocusIndex === this.inputElList.length - 1 ? this.handleMatrixConfirm() : this.inputElList[(this.inputFocusIndex += 1)].focus()
      },
      handleInputFocus(event) {
        const id = event.target.dataset.id
        const index = this.inputElList.findIndex(el => el.dataset.id === id)
        this.inputFocusIndex = index
        setTimeout(() => {
          this.inputElList[this.inputFocusIndex].select()
        })
      },
      handleClearInputCount() {
        Object.keys(this.tBody).map(obj => {
          Object.keys(this.tBody[obj]).map(data => {
            this.$set(this.tBody[obj][data], 'count', '') 
          })
        })
        this.inputElList[0].select()
      },
      handleMatrixConfirm() {
        const {url, mainTableName, tableName, mainTableValue, formDataKey, fc} = this.options
        let formParams = []
        Object.keys(this.tBody).map(obj => {
          Object.keys(this.tBody[obj]).map(list => {
            const {disabled, count, PS_C_SKU_ECODE, PS_C_SKU_ID } = this.tBody[obj][list]
            if (!disabled && count && !Object.is(Number(count), NaN) && Number(count) !== 0) {
              let formItem = {}
              formItem[formDataKey[0]] = !!fc ? PS_C_SKU_ID : PS_C_SKU_ECODE
              formItem[formDataKey[1]] = count
              formItem['ID'] = -1
              formParams.push(formItem)
            }
          })
        })
        let saveParams = {}
        saveParams[mainTableName] = mainTableValue
        saveParams[tableName] = formParams
        this.apiMatrixSave(url, saveParams)
      },
      async apiMatrixSave(url, params) {
        this.loading = true
        try {
          const { data } = await network.post(url, params)
          if (data.code === 0) {
            this.$emit('refreshData')
          }
          this.loading = false
        } catch {
          this.loading = false
        }
      },
      handleMatrixCancel() {
        this.$emit('closeMatrix')
      },
      calculateRow(val) {
        let total = 0
        Object.keys(val).map(obj => {
          total += Object.is(Number(val[obj].count), NaN) ? 0 : Number(val[obj].count)
        })
        return total
      },
      calculateLine(val) {
        let total = 0
        Object.keys(this.tBody).map((obj) => {
          total += Object.is(Number(this.tBody[obj][val.name].count), NaN) ? 0 : Number(this.tBody[obj][val.name].count) 
        })
        return total
      },
      calculateTotal() {
        let total = 0
        Object.keys(this.tBody).map((obj) => {
          Object.keys(this.tBody[obj]).map((data) => {
            total += Object.is(Number(this.tBody[obj][data].count), NaN) ? 0 : Number(this.tBody[obj][data].count)
          })
        })
        return total
      }
    },
    watch: {},
    mounted() {
      this.apiFetchMatrixData()
    },
    created() {},
    beforeDestroy() {
      if (this.inputElList.length > 0 ) {
        this.$el.removeEventListener('keydown', this.handleKeyDown)
      }
    }
  }
</script>
