<template>
  <view class="mtr-content">
    <view class="content-view">
      <!-- 材料列表 -->
      <view class="mtr-tab">
        <u-table
          align="center"
          border-color="#FFFFFF"
          color="#333333"
          font-size="rpx"
          :th-style="thStyle"
          padding="0"
        >
          <u-tr class="u-tr">
            <u-th
              class="u-th content-tab-th"
              v-for="(value, key) in titles"
              :key="key"
              width="auto"
            >
              <text :class="['tab-th-txt', { left: key == firstKey }]">{{
                value
              }}</text>
            </u-th>
          </u-tr>
          <view class="line-view"></view>
          <u-tr class="u-tr" v-for="(item, index) in list" :key="index">
            <u-td
              class="u-td"
              v-for="(value, key) in titles"
              :key="key"
              width="200"
            >
              <view v-if="key == 'useLength'" class="uselen-input">
                <u-input
                  @blur="handleBlur(item)"
                  :border="true"
                  border-color="#2979FF"
                  @focus="handleFocus(item)"
                  type="number"
                  placeholder="请输入"
                  v-model="item[key]"
                  placeholder-style="color: #999999;font-size:26rpx"
                  input-align="center"
                  :clearable="false"
                  :verify-number="true"
                >
                  <u-icon name="edit"></u-icon
                ></u-input>
              </view>
              <text v-else :class="['tab-th-txt', { left: key == firstKey }]">{{
                item[key]
              }}</text>
            </u-td>
          </u-tr>
        </u-table>
      </view>
      <!-- 其他 -->
      <view class="mtr-other">
        <view class="line-view"></view>
        <view class="u-flex u-row-between other-space">
          <view class="other-label">其他</view>
          <view class="list">
            <view
              v-for="(item, index) in other"
              :key="index"
              class="u-flex u-row-between"
            >
              <u-input
                v-model="item.otherExplain"
                :border="true"
                class="u-m-r-15"
                :clearable="false"
                placeholder="请输入内容"
                :border-color="index === 0 ? '#2979FF' : '#FF930D'"
              />
              <u-input
                v-model="item.extraAmt"
                type="number"
                :border="true"
                class="u-m-l-15"
                :clearable="false"
                placeholder="请输入金额"
                :border-color="index === 0 ? '#2979FF' : '#FF930D'"
              />
              <image
                v-if="index === 0"
                class="image-view"
                :src="addImage"
                @click="handleAdd"
              />
              <image
                v-else
                class="image-view"
                :src="subtractImage"
                @click="handleSubtract(index)"
              />
            </view>
          </view>
        </view>
        <view class="other-space u-p-t-20">
          <text>超出金额</text>
          <text>{{ money }}元</text>
        </view>
      </view>
    </view>
    <!-- 底部确定按钮 -->
    <view class="bottom-view">
      <u-button
        class="sure-button"
        type="primary"
        shape="circle"
        @click="handleSure"
        :custom-style="buttonStyle"
      >
        确定
      </u-button>
    </view>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
export default {
  data() {
    return {
      orderId: '',
      fieldName: 'materialList',
      list: [], // 材料列表
      other: [], // 其他列表
    }
  },
  computed: {
    buttonStyle() {
      return {
        width: '600rpx',
        height: '104rpx',
        'font-size': '32rpx',
        'font-weight': 'bold',
      }
    },
    titles() {
      return {
        matName: this.isMaterial ? '材料名称' : '工艺名称',
        matUnit: '单位',
        freeLength: '免费量',
        unitAmt: '单价/元',
        useLength: '用量',
      }
    },
    widths() {
      return {
        matName: 200,
        matUnit: 'auto',
        freeLength: 'auto',
        unitAmt: 'auto',
        useLength: 'auto',
      }
    },
    thStyle() {
      return {
        'font-weight': 'bold',
      }
    },
    firstKey() {
      return Object.keys(this.titles)[0]
    },
    subtractImage() {
      return process.uniEnv.qn_base_url + 'qxiao.png'
    },
    addImage() {
      return process.uniEnv.qn_base_url + 'tianjia.png'
    },
    money() {
      // 总额
      var amount = 0
      for (var item of this.list) {
        let useLength = Number(item.useLength) || 0
        let freeLength = Number(item.freeLength) || 0
        let unitAmt = Number(item.unitAmt) || 0
        amount += Math.max(useLength - freeLength, 0) * unitAmt
      }
      for (var item of this.other) {
        if (item.extraAmt && Number(item.extraAmt)) {
          amount += Number(item.extraAmt)
        }
      }
      return amount
    },
    isMaterial() {
      return this.fieldName === 'materialList'
    },
    isCraft() {
      return this.fieldName === 'craftList'
    },
    priceType() {
      return this.isMaterial ? '01' : '02'
    },
  },
  onLoad(option) {
    getApp().trackPage('订单材料列表页')
    this.orderId = option.orderId
    this.fieldName = option.fieldName
    const eventChannel = this.getOpenerEventChannel()
    let self = this
    eventChannel.on('showMaterialData', function(data) {
      if (!data || data.length === 0) {
        self.getMaterialData()
      } else {
        self.formatServiceMoreList(data)
      }
    })
    if (this.$u.test.isEmpty(this.other)) {
      this.handleAdd()
    }
  },
  created() {},
  mounted() {},
  methods: {
    getMaterialData() {
      let self = this
      self.$u.api.getOrderMaterial(self.orderId).then((res) => {
        if (res.code !== 200) {
          console.log(res.data.message)
          return
        }
        self.formatServiceMoreList(res.data)
      })
    },
    formatServiceMoreList(materialCraftsData) {
      let self = this
      materialCraftsData.map((item) => {
        if (item.priceType === self.priceType) {
          item.matType === '04' ? self.other.push(item) : self.list.push(item)
        }
      })
    },
    handleBlur(item) {
      // 失去焦点如果没输入用原先的值
      if (
        this.$u.test.isEmpty(item.useLength) ||
        !this.$u.test.number(item.useLength)
      ) {
        item.useLength = 0
      }
    },
    handleFocus(item) {
      // 点击清空
      if (this.$u.test.isEmpty(item.useLength)) {
        item.useLength = null
      }
    },
    /* 其他添加新的 */
    handleAdd() {
      this.other.push({
        //orderNo:this.formInfo.orderNo,
        isDel: 'N',
        isWebAdd: true,
        matName: '其他',
        extraAmt: null,
        priceType: this.priceType,
        matType: '04',
        otherExplain: '',
      })
    },
    /* 其他删除某个 */
    handleSubtract(index) {
      this.other.splice(index, 1)
    },
    validateForm() {
      if (this.isMaterial) {
        let row = this.list.find((item) => {
          return !this.$u.test.isEmpty(item.useLength) && item.useLength != '0'
        })
        if (!this.$u.test.isEmpty(this.list) && this.$u.test.isEmpty(row)) {
          this.$refs.uToast.show({
            title: '请填写电缆、漏保、空开等用量',
            type: 'error',
            icon: false,
            position: 'bottom',
          })
          return false
        }
      }
      return true
    },
    handleSure() {
      if (!this.validateForm()) {
        return false
      }
      let pages = getCurrentPages()
      let prevPage = pages[pages.length - 2] //上一个页面
      let data = {}
      let tmps = []
      this.other.map((item) => {
        if (!this.$u.test.isEmpty(item.otherExplain)) {
          item.extraAmt = item.extraAmt || 0
          tmps.push(item)
        }
      })
      data[this.fieldName] = this.list.concat(tmps) // 将list合并给上以页面
      prevPage.$vm.setData(data) //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
      uni.navigateBack()
    },
  },
}
</script>

<style lang="scss" scoped>
.mtr-content {
  display: flex;
  flex-direction: column;
  background-color: #f4f5f7;
  height: 100vh;

  .content-view {
    padding: 30rpx 30rpx 60rpx 30rpx;
    margin: 20rpx 30rpx;
    border-radius: 12rpx;
    background-color: #ffffff;
    height: 100%;
    overflow: auto;

    .line-view {
      background-color: #f4f5f7;
      height: 2rpx;
      margin: 20rpx 0;
    }

    .mtr-tab {
      .tab-th-txt {
        background-color: #ffffff;
        padding: 10rpx 0;
        line-break: anywhere;

        &.left {
          text-align: left;
        }
      }
    }

    .mtr-other {
      .other-space {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .other-content {
        margin-bottom: 30rpx;
      }

      .input-view {
        padding: 10rpx 30rpx;
        width: 100%;
        border-radius: 12rpx;
        border: 1px #f4f5f7 solid;
        margin-bottom: 30rpx;

        .input-title {
          width: 80rpx;
          flex-shrink: 0;
          color: #333333;
          font-size: 26rpx;
        }

        .input-content {
          width: 100%;
        }
      }

      .image-view {
        width: 52rpx;
        height: 52rpx;
        flex-shrink: 0;
        margin: 30rpx 0 30rpx 30rpx;
      }
    }
  }

  .bottom-view {
    margin-bottom: 44rpx;
    margin-top: 10rpx;
    height: 104rpx;
  }
}
.other-label {
  width: 150rpx;
  align-self: flex-start;
  line-height: 80rpx;
}
</style>
