<template>
  <!-- tables -->
  <div class="tables_grid">
    <el-table ref="tableRef" style="width: 100%" tooltip-effect="dark myTooltips" :show-header="showHeader"
      class="table-style" :data="tableData" :border="border" :row-key="(val) => rowKey(val)" @cell-click="cellClick"
      @selection-change="handleSelectionChange">
      <template v-for="(item,index) in tableList">
        <el-table-column :fixed="suspension ? 'right' : false" :label="item.label" :width="item.colWidth" align="center"
          v-if="item.field == 'action'">
          <template slot-scope="scope">
            <div style="display: flex;align-items: center;justify-content: center;">
              <div v-for="disk in item.labelButton" :key="disk.key" class="btn_table">
                <el-button :class="disk.modality" :type="disk.style" :icon="disk.icon" size="mini"
                  :disabled="jurisdiction(scope.row,disk.type)" @click="buttonData(scope.row,disk.type)">
                  {{ disk.label }}
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column class="card_unpack_btn" :fixed="suspension ? 'right' : false" :label="item.label"
          :width="unpackWidth" align="center" v-else-if="item.field == 'unpackBtn'">
          <template slot="header" slot-scope="scope">
            <div class="unpack_card">
              <div v-if="!iconFlag">{{item.label}}</div>
              <i class="card_unpack" :class="iconFlag ? 'el-icon-s-fold' : 'el-icon-s-unfold'" @click="getUnpack"></i>
            </div>
          </template>
          <template slot-scope="scope">
            <div class="center_in" v-if="!iconFlag">
              <div v-for="disk in item.labelButton" :key="disk.key" class="btn_table">
                <el-button :class="disk.modality" :type="disk.style" :icon="disk.icon" size="mini"
                  :disabled="jurisdiction(scope.row,disk.type)" @click="buttonData(scope.row,disk.type)">
                  {{ disk.label }}
                </el-button>
              </div>
            </div>
            <div v-else :key="index">
              <el-popover placement="top" trigger="click" v-model="scope.row.visible">
                <div class="center_in">
                  <div v-for="disk in item.labelButton" :key="disk.key" class="btn_table">
                    <el-button :class="disk.modality" :type="disk.style" :icon="disk.icon" size="mini"
                      :disabled="jurisdiction(scope.row,disk.type)" @click="buttonData(scope.row,disk.type)">
                      {{ disk.label }}
                    </el-button>
                  </div>
                </div>
                <el-tag style="cursor: pointer;" size="mini" slot="reference">操作</el-tag>
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="item.label" align="center" v-else-if="item.field == 'suitableForCold'">
          <template slot-scope="scope" v-if="item.field == 'suitableForCold'">
            <div v-if="scope.row[item.field]">{{ scope.row[item.field] }} ℃</div>
          </template>
        </el-table-column>
        <el-table-column :label="item.label" align="center" v-else-if="item.field == 'iceTime'">
          <template slot-scope="scope" v-if="item.field == 'iceTime'">
            <div>{{ geticeTime(scope.row) }}</div>
          </template>
        </el-table-column>
        <el-table-column :label="item.label" align="center" v-else-if="item.field == 'historyCode'">
          <template slot-scope="scope" v-if="item.field == 'historyCode'">
            <div v-if="scope.row[item.field]">{{ scope.row[item.field].join(',') }}</div>
          </template>
        </el-table-column>
        <el-table-column :label="item.label" align="center" v-else-if="item.field == 'historyCodeNum'">
          <template slot-scope="scope" v-if="item.field == 'historyCodeNum'">
            <div v-if="scope.row['historyCode']">{{ scope.row['historyCode'].length }}</div>
          </template>
        </el-table-column>
        <el-table-column :label="item.label" align="center" v-else-if="item.field == 'multistage'">
          <template v-for="(child,cgindex) in item.children">
            <el-table-column :prop="child.field" :label="child.label" :width="child.colWidth" :align="child.align">
              <template slot-scope="scope">
                <div v-if="child.field == 'suitableForColdTime'">≥{{scope.row[child.field]}}min</div>
                <div
                  v-else-if="child.field == 'iceRaftRecord.suitableForCold' && scope.row.iceRaftRecord.suitableForCold">
                  {{nestedField(scope.row,child.field)}}℃
                </div>
                <div v-else-if="child.field == 'suitableForCold'">
                  {{scope.row.suitableForCold ? scope.row.suitableForCold + '℃' : ''}}
                </div>
                <div v-else>{{nestedField(scope.row,child.field)}}</div>
              </template>
            </el-table-column>
          </template>
        </el-table-column>
        <el-table-column :label="item.label" align="center"
          v-else-if="item.field == 'receiptImg' || item.field == 'receiptsign'">
          <template slot-scope="scope">
            <el-image style="width: 60px; height: 60px" :src="scope.row[item.field]"
              :preview-src-list="getImage(scope.row[item.field])"></el-image>
          </template>
        </el-table-column>
        <el-table-column :prop="item.field" :label="item.label" :width="item.colWidth" :align="item.align"
          v-else-if="['provUser.isorders','provUser.userType','customer.type','tbFillData.productMediaId','iceRaftRecord.status'].includes(item.field)">
          <template slot-scope="scope">
            <div :style="{color: filterColoril(scope.row,item.options,item.field)}">
              {{initDictvalue(scope.row,item.options,item.field)}}
            </div>
          </template>
        </el-table-column>
        <el-table-column :prop="item.field" :label="item.label" :width="item.colWidth" :align="item.align"
          v-else-if="['userId','paymentType','paymentStatus','assignmentStatus', 'type', 'status', 'monitorStatus', 'storeId', 'personCode', 'optType', 'corrosion', 'crackle', 'deform', 'damage', 'safeAnnex', 'gasPressure', 'bodyDeform', 'fillingLeak', 'bodyTemperature', 'filledLeak', 'warnSign', 'fillLabel', 'seal','addressType'].includes(item.field)">
          <template slot-scope="scope">
            <div :style="{color: filterColor(scope.row,item.options,item.field)}">
              {{initDictvalueil(scope.row,item.options,item.field)}}
            </div>
          </template>
        </el-table-column>
        <el-table-column :prop="item.field" :label="item.label" :width="item.colWidth" :align="item.align"
          v-else-if="item.field == 'myStatus'">
          <template slot-scope="scope">
            <div :style="{color: myfilterColor(scope.row,item.options,item.field)}">
              {{myInitDictvalueil(scope.row,item.options,item.field)}}
            </div>
          </template>
        </el-table-column>
        <el-table-column :prop="item.field" :label="item.label" :width="item.colWidth" :align="item.align"
          v-else-if="item.field == 'region'">
          <template slot-scope="scope">
            <div>{{scope.row.provinceName}}{{scope.row.cityName}}{{scope.row.regionName}}</div>
          </template>
        </el-table-column>
        <el-table-column :prop="item.field" :label="item.label" :width="item.colWidth" :align="item.align"
          v-else-if="item.field == 'deviceData.T_t'">
          <template slot-scope="scope">
            <div>{{scope.row.deviceData.T_t || ''}}</div>
          </template>
        </el-table-column>
        <el-table-column :prop="item.field" :label="item.label" :width="item.colWidth" :align="item.align"
          v-else-if="item.field == 'location'">
          <template slot-scope="scope">
            <div v-if="scope.row.iceRaftRecord">
              <div v-if="scope.row.iceRaftRecord.outStorageTime == ''">{{scope.row.iceRaftRecord.iceLocker.name}}</div>
              <div v-else>{{scope.row.iceRaftRecord.coolerBox.name}}
              </div>
            </div>
            <div v-else>
              <div v-if="scope.row.outStorageTime == ''">{{scope.row.iceLocker.name}}</div>
              <div v-else>{{scope.row.coolerBox.name}}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column :prop="item.field" :label="item.label" :width="item.colWidth" :align="item.align"
          v-else-if="item.field == 'freezeClaim'">
          <template slot-scope="scope">
            <div v-if="scope.row[item.field]">{{getFreeze(scope.row[item.field])}}</div>
            <div v-else-if="scope.row.iceRaftRecord">
              <span v-if="scope.row.iceRaftRecord.status">≥{{scope.row.iceRaftRecord.freezeClaim}}h</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column :prop="item.field" :label="item.label" :width="item.colWidth" :align="item.align"
          v-else-if="item.field == 'freezeDuration'">
          <template slot-scope="scope">
            <div v-if="scope.row.iceRaftRecord">{{ formatMinutes(scope.row.iceRaftRecord.freezeDuration) }}</div>
            <div v-else>{{ formatMinutes(scope.row.freezeDuration) }}</div>
          </template>
        </el-table-column>
        <el-table-column :prop="item.field" :label="item.label" :width="item.colWidth" :align="item.align"
          v-else-if="item.field == 'assessStar'">
          <template slot-scope="scope">
            <el-rate disabled v-model="scope.row.assessStar"></el-rate>
            <el-tooltip class="item" effect="dark" :content="scope.row.assessContent" placement="top">
              <div class="cell el-tooltip">{{scope.row.assessContent}}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column :prop="item.field" :label="item.label" :width="item.colWidth" :align="item.align"
          v-else-if="item.field == 'deliveryDuration'">
          <template slot-scope="scope">
            <div>{{formatMinutes(scope.row[item.field]) || ''}}</div>
          </template>
        </el-table-column>
        <el-table-column type="index" :fixed="item.boxhead ? true : false" :width="item.colWidth" :label="item.label"
          :align="item.align" v-else-if="item.field == 'index'">
        </el-table-column>
        <el-table-column type="selection" v-model="selectionList" :reserve-selection="true" width="55"
          v-else-if="item.field == 'selection'"></el-table-column>
        <el-table-column :show-overflow-tooltip="true" :prop="item.field" :label="item.label" :width="item.colWidth"
          :align="item.align" v-else>
        </el-table-column>
      </template>
    </el-table>
  </div>
</template>

<script>
  import {
    putUpdateStatus
  } from '@/api/waybill'
  import {
    orderStatus,
    rectificationState
  } from '@/assets/js/blockSort'
  export default {
    props: {
      // 表格边框
      border: {
        type: Boolean,
        default: () => false,
      },
      // 是否显示表头
      showHeader: {
        type: Boolean,
        default: () => true,
      },
      // 表格数据
      tableList: {
        type: Array,
        default: () => [],
      },
      // 表格label数据
      tableData: {
        type: Array,
        default: () => [],
      },
      // 网关数据
      detailGateway: {
        type: Array,
        default: () => [],
      },
      // 语言数据
      detailLanguage: {
        type: Array,
        default: () => [],
      },
      // 是否悬浮
      suspension: {
        type: Boolean,
        default: () => false,
      },
      // 历史记录按钮显示控制
      historyFlag: {
        type: Boolean,
        default: () => false,
      },
      // 头部高度
      tableHeight: {
        type: String,
        default: () => '',
      },
      // 操作按钮宽度
      controlswidth: {
        type: String,
        default: () => '370px',
      }
    },
    data() {
      return {
        orderStatusList: orderStatus(),
        waybillIds: [],
        selectionList: [],
        iconFlag: false,
        unpackWidth: '',
        visible: false,
      }
    },
    watch: {
      controlswidth: {
        handler: function(newUser, oldUser) {
          this.unpackWidth = newUser
        },
        immediate: true,
        deep: true,
      }
    },
    methods: {
      geticeTime(event){
        let specificDateTime = event.iceRaftRecord.ice_use_time
        const specificDate = new Date(specificDateTime);
        // 获取当前时间
        const now = new Date();
        // 计算时间差，得到毫秒数
        const timeDifference = now - specificDate;
        // 将时间差转换为小时、分钟和秒
        const hours = Math.floor(timeDifference / 3600000);
        const minutes = Math.floor((timeDifference % 3600000) / 60000);
        const seconds = Math.floor((timeDifference % 60000) / 1000);
        let time = ''
        if(minutes){
          time = hours + 'h' + minutes + 'm'
        }
        return time
        // console.log(`使用时间差: ${hours}小时 ${minutes}分钟 ${seconds}秒`);
      },
      getImage(image) {
        let arr = []
        arr.push(image)
        return arr
      },
      // 嵌套字段
      nestedField(event, type) {
        let propertyName = type.split(".")
        let name = ''
        if (propertyName.length > 1) {
          if (event[propertyName[0]] != undefined) {
            if (event[propertyName[0]][propertyName[1]]) {
              name = event[propertyName[0]][propertyName[1]]
            }
          }
        } else {
          if (event[propertyName[0]] != undefined) {
            name = event[propertyName[0]]
          }
        }
        return name
      },
      // 冷冻要求
      getFreeze(event) {
        let title = event
        let arrList = []
        title.forEach(item => {
          let arr = '≥' + item + 'h'
          arrList.push(arr)
        })
        return arrList.toString()
      },
      // 文字匹配
      initDictvalue(value, list, type) {
        let propertyName = type.split(".")
        let name = ''
        if (list) {
          list.forEach(item => {
            if (value[propertyName[0]][propertyName[1]] == item.value) {
              name = item.label
            }
          })
        }
        return name
      },
      filterColoril(value, list, type) {
        let propertyName = type.split(".")
        let color = ''
        if (list) {
          list.forEach(item => {
            if (value[propertyName[0]][propertyName[1]] == item.value) {
              color = item.bgcolor
            }
          })
        }
        return color
      },
      // 普通类型文字匹配
      initDictvalueil(value, list, type) {
        let name = ''
        if (list) {
          list.forEach(item => {
            if (value[type] === item.value) {
              name = item.label
            }
          })
        }
        return name
      },
      // tag颜色获取
      filterColor(value, list, type) {
        let color = ''
        if (list) {
          list.forEach(item => {
            if (value[type] === item.value) {
              color = item.bgcolor
            }
          })
        }
        return color
      },
      // 总分钟格式化
      formatMinutes(totalMinutes) {
        if (totalMinutes) {
          const hours = Math.floor(totalMinutes / 60); // 计算小时
          const minutes = totalMinutes % 60; // 计算分钟（余数）
          return `${hours}h${minutes}m`;
        } else {
          return ''
        }
      },
      // 我的运单
      myInitDictvalueil(value, list, type) {
        if ([1, 2, 3].includes(value.status)) {
          return list[0].label
        } else if ([4, 5, 6, 7].includes(value.status)) {
          return list[1].label
        } else if (value.status == 8) {
          return list[2].label
        }
      },
      myfilterColor(value, list, type) {
        if ([1, 2, 3].includes(value.status)) {
          return list[0].bgcolor
        } else if ([4, 5, 6, 7].includes(value.status)) {
          return list[1].bgcolor
        } else if (value.status == 8) {
          return list[2].bgcolor
        }
      },
      // 城市筛选
      cityScreening(value, list, type) {
        function getChildById(parentArray, id) {
          for (let i = 0; i < parentArray.length; i++) {
            if (parentArray[i].value === id) { // 如果当前元素的ID与目标ID相等，则返回该元素
              return parentArray[i];
            } else if (parentArray[i].children && Array.isArray(parentArray[i].children)) { // 判断当前元素是否有子节点且类型为数组
              const result = getChildById(parentArray[i].children, id); // 对子节点进行递归调用
              if (result !== null) { // 若子节点存在结果，则返回该结果
                return result;
              }
            }
          }
          return null; // 没有找到符合条件的元素时返回null
        }
        var name = getChildById(list, value[type])
        if (name != null) {
          return name.label
        }
      },
      // 权限按钮
      jurisdiction(row, type) {
        if (this.historyFlag) {
          if (row.status != '4' && type == 'edit') {
            return false
          } else if (row.status == '1' && type == 'del' || row.status == '2' && type == 'del') {
            return false
          } else {
            return true
          }
        } else {
          return false
        }
      },
      // 选择tables某一项
      cellClick(row) {
        this.$emit('cellClick', row)
      },
      // 选择多行数据
      handleSelectionChange(row) {
        this.selectionList = row
        let arrID = []
        const arr = row
        arr.forEach(item => {
          // const option = {
          //   id: item.id,
          //   status: item.status,
          // }
          // arrID.push(option)
          // arrID.push(item.id)
          arrID.push(item)
        })
        this.waybillIds = JSON.parse(JSON.stringify(arrID))
      },
      // 操作按钮
      buttonData(row, type) {
        // console.log(row, type, '操作按钮')
        this.$emit("buttonData", row, type);
      },
      // 删除订单
      deleteOrder(row) {
        this.$confirm('此操作将永久删除该订单, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let arrOrderId = []
          arrOrderId.push(row.id)
          putUpdateStatus({
            id: arrOrderId,
            status: 8,
          }).then(res => {
            if (res.code == 200) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
            }
          })
        }).catch(() => {})
      },
      // 清空选中项
      clearSelected() {
        this.$nextTick(() => {
          this.$refs.tableRef.clearSelection();
        })
      },
      rowKey(val) {
        if (val.id) {
          return val.id
        } else {
          if (val.T_id) {
            return val.T_id + Math.random()
          } else {
            return val.T_sn
          }
        }
      },
      // 展开收起
      getUnpack() {
        if (this.iconFlag) {
          this.unpackWidth = this.controlswidth
          this.iconFlag = false
        } else {
          this.unpackWidth = '70px'
          this.iconFlag = true
        }
      }
    }
  }
</script>

<style scoped lang="scss">
  ::v-deep .el-table__fixed-right {
    transition: width 0.15s;
    -webkit-transition: width 0.15s;
    -moz-transition: width 0.15s;
    -webkit-transition: width 0.15s;
    -o-transition: width 0.15s;
  }

  .btn_table:nth-of-type(n+2) {
    margin-left: 10px;
  }

  .el-button--mini {
    padding: 5px;
  }

  .deleteBtn {
    color: #ff6665;
  }

  .icon_play {
    font-size: 25px;
    color: #83FF00;
  }

  .icon_pause {
    font-size: 25px;
    color: #FF9494;
  }

  .title_play {
    font-size: 15px;
    color: #83FF00;
    margin-left: 10px;
  }

  .title_pause {
    font-size: 15px;
    color: #FF9494;
    margin-left: 10px;
  }

  .card_operation {
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }

  .gateway_title {
    color: #59fe6d;
  }

  .gateway_title1 {
    color: #34d9f4;
  }

  .operator_title {
    color: #fff;
  }

  .unpack_card {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .card_unpack {
    cursor: pointer;
    font-size: 25px;
    margin-left: 10px;
  }
</style>
<style>
  .myTooltips {
    max-width: 50%;
  }
</style>
