<template>
  <div>
    <vxe-table
      ref="xTable"
      :row-config="{ isHover: true }"
      :data="newtableData"
      :span-method="colspanMethod"
      :height="height"
      :checkbox-config="{
        checkField: 'checked',
        checkMethod: checCheckboxkMethod3,
        visibleMethod: showCheckboxkMethod2,
      }"
      :header-cell-style="{
        height: '70px',
        color: '#606266',
        'text-align': 'center',
      }"
      :scroll-y="{ enabled: false, gt: 10 }"
      :loading="loading"
      border
    >
      <vxe-column type="checkbox" width="50" :border="false"></vxe-column>
      <vxe-column
        v-for="(item, index) in tablelabel"
        :key="index"
        :visible="item.show"
        :title="item.label"
        :field="item.param"
        :fixed="item.fixed"
        :column-key="item.param"
        :min-width="item.minwidth"
        :filters="item.filters"
        :sortable="item.sortable"
        align="center"
      >
        <template slot-scope="{ row }">
          <span v-if="row.render == true" class="firstspan">
            <span v-if="row.business_id">质检码：{{ row.business_id }}</span>
            <span v-if="row.biz_order_id || row.order_sn"
              >订单编号：{{ row.biz_order_id || row.order_sn }}</span
            >
            <span v-if="row.publish_time"
              >发布时间：{{ row.publish_time }}</span
            >
          </span>
          <span v-else-if="row.render == false">
            <div v-if="item.label === '机器信息'" class="machineinfo">
              <p>
                {{ row.brand_name }} {{ row.model_name }} {{ row.rom_name }}
                {{ row.color_name }}
              </p>
              <div class="info">
                <div class="info-left">
                  <el-popover
                    v-if="row['img']"
                    placement="right"
                    width="375"
                    trigger="click"
                  >
                    <img
                      v-if="row['img']"
                      style="height: 350px"
                      :src="row['img']"
                    />
                    <img
                      v-if="row['img']"
                      slot="reference"
                      style="float: left; height: 70px"
                      :src="row['img']"
                    />
                  </el-popover>
                  <img
                    v-else
                    style="float: left; height: 70px"
                    src="./../assets/noimg.jpg"
                  />
                </div>
                <ul class="info-right">
                  <li>
                    <span
                      v-if="item.link"
                      style="display: flex; align-items: center"
                    >
                      机器编号：
                      <el-link
                        :underline="false"
                        type="primary"
                        @dblclick.native="jump(row, '机器编号')"
                        >{{ row.serial_number }}</el-link
                      >
                    </span>
                    <span v-else> 机器编号：{{ row.serial_number }} </span>
                  </li>
                  <li>IMEI：{{ row.imei1 }}</li>
                  <li>IMEI2：{{ row.imei2 }}</li>
                  <li>SN:{{ row.sn }}</li>
                </ul>
              </div>
            </div>
            <span
              v-else-if="
                item.label === '机器状态' ||
                item.label === '订单状态' ||
                item.label === '商品状态'
              "
            >
              <el-tag>{{ row[item.param] || "/" }}</el-tag>
            </span>
            <span v-else-if="item.label === '订单价格\n(利润)'">
              <span style="display: block">{{ row.payment / 100 }}</span>
              <span
                :class="
                  row.payment / 100 - row.total_cost > 0 ? 'color' : 'green'
                "
                >{{
                  (row.payment / 100 - Number(row.total_cost)).toFixed(2)
                }}</span
              >
            </span>
            <span v-else-if="item.label == '质检报告'" class="look">
              <el-link
                :underline="false"
                type="primary"
                @click="lookquily(row, '0')"
                >质检报告</el-link
              >
              <el-link
                v-if="item.detailshow"
                :underline="false"
                type="primary"
                @click="lookquily(row, '1')"
                >商品详情</el-link
              >
            </span>
            <span v-else-if="item.label == '预计结算价'">
              <span :style="6 ? 'color:#ff6b81' : 'color:#2ed573'">{{
                Number((row.price * 0.98) / 100).toFixed(2) +
                "~" +
                Number((row.price * 0.99) / 100).toFixed(2)
              }}</span>
            </span>
            <span v-else-if="item.label == '预估利润'">
              <span
                :style="
                  Number(row.price / 100) - Number(row.total_cost) > 0
                    ? 'color:#ff6b81'
                    : 'color:#2ed573'
                "
                >{{
                  (Number(row.price / 100) - Number(row.total_cost)).toFixed(2)
                }}</span
              >
            </span>
            

            <span
              v-else-if="
                item.label == '退款金额' ||
                item.label == '申请退款金额' ||
                item.label == '定价'
              "
            >
              <span>{{ Number(row[item.param] / 100).toFixed(2) }}</span>
            </span>
            <span
              v-else-if="
                item.label == '交易成功时间' ||
                item.label == '关闭时间' ||
                item.label == '退款时间' ||
                item.label == '订单创建时间' ||
                item.label == '操作时间' ||
                item.label == '付款时间'
              "
              >{{ row[item.param] | dateformat("YYYY-MM-DD HH:mm:ss") }}</span
            >
            <!-- 操作 -->
            <span v-else-if="item.label === '操作'" class="operate">
              <el-popconfirm
                title="请确认？"
                v-if="item.status.includes('Agree')"
                @confirm="operate('Agree', row)"
              >
                <el-link slot="reference" type="primary" :underline="false"
                  >同意</el-link
                >
              </el-popconfirm>
              <el-popconfirm
                title="请确认驳回？"
                v-if="item.status.includes('Reject')"
                @confirm="operate('Reject', row)"
              >
                <el-link slot="reference" type="danger" :underline="false"
                  >驳回</el-link
                >
              </el-popconfirm>
              <el-link
                type="warning"
                :underline="false"
                v-if="item.status.includes('Logs')"
                @click="operate('Logs', row)"
                >日志</el-link
              >
              <el-link
                type="danger"
                :underline="false"
                v-if="item.status.includes('OffShelf')"
                @click="operate('OffShelf', row)"
                >下架</el-link
              >
            </span>
            <span v-else>
              {{ row[item.param] ? row[item.param] : "-" }}
            </span>
          </span>
        </template>
      </vxe-column>
    </vxe-table>
    <xylog
      :xylogdialog-visible="xylogdialogVisible"
      :xylogid="xylogid"
      :xylogtype="xylogtype"
      @xylogdialog="xylogdialog"
    />
  </div>
</template>

<script>
import Sortable from "sortablejs";
import xylog from "./../Dialog/xyqualitydialog";
export default {
  name:"erpTable",
  components: {
    xylog,
  },
  data() {
    return {
      xylogid: "",
      xylogtype: "",
      xylogdialogVisible: false,
    };
  },
  props: {
    tableDate: {
      default: () => {
        return [];
      },
    },
    tablelabel: {
      default: () => {
        return [];
      },
    },
    excelName: {
      default: () => {
        return "";
      },
    },
    loading: {
      default: () => {
        return false;
      },
    },
    tabbar: {
      default: () => {
        return false;
      },
    },
  },
  computed: {
    newtableData() {
      if (this.tableDate.length == 0) return;
      let result = [];
      const arr = this._.cloneDeep(this.tableDate);
      result = arr.map((item) => [{ ...item }, { ...item }]).flat();
      result.map((e, i) => {
        if (i % 2 === 0) {
          this.$set(e, "render", true);
          this.$set(e, "checked", false);
        } else {
          this.$set(e, "render", false);
        }
      });
      return result;
    },
    height() {
      let height = "";
      if (this.tabbar) {
        height = document.documentElement.clientHeight - 235;
      } else {
        height = document.documentElement.clientHeight - 280;
      }
      return height;
    },
    tablelabelLen() {
      let num = 0;
      this.tablelabel.forEach((item) => {
        if (item.show) {
          num++;
        }
      });
      return num;
    },
  },
  mounted() {},
  methods: {
    colspanMethod({ _rowIndex, _columnIndex }) {
      if (_rowIndex % 2 === 0) {
        if (_columnIndex === 0) {
          return { rowspan: 1, colspan: 1 };
        } else if (_columnIndex === 1) {
          return { rowspan: 1, colspan: this.tablelabelLen };
        } else {
          return { rowspan: 0, colspan: 0 };
        }
      }
    },
    checCheckboxkMethod3({ row }) {
      return row.render == true;
    },
    showCheckboxkMethod2({ row }) {
      return row.render == true;
    },
    // 同意
    tongyi(row) {
      this.$emit("tongyi", row);
    },
    // 驳回
    bohui(row) {
      this.$emit("bohui", row);
    },
    // 跳转
    jump(row, name) {
      switch (name) {
        case "机器编号":
          this.$router.push({
            name: "MachineDetails",
            query: { row: row.res_id },
          });
          break;
        default:
          break;
      }
    },
    // 操作
    operate(val, data) {
      switch (val) {
        case "Agree":
          this.$emit("Agree", data);
          break;
        case "Reject":
          this.$emit("Reject", data);
          break;
        case "OffShelf":
          this.$emit("OffShelf", data);
          break;
        case "Logs":
          this.$emit("looksLogs", data);
          break;
        default:
          break;
      }
    },
    //查看质检码
    lookquily(row, type) {
      this.xylogdialogVisible = true;
      if (type == "0") {
        this.xylogtype = "0";
        this.xylogid = row.id;
      } else {
        this.xylogtype = "1";
        this.xylogid = row.item_id;
      }
    },

    // 质检报告dilog关闭
    xylogdialog(e) {
      this.xylogdialogVisible = e;
    },
    // sortable初始化
    InitializeSortable() {
      const sortableId = document.querySelector(
        ".vxe-table--header-wrapper tr"
      );
      this.sortable = Sortable.create(sortableId, {
        // 元素被选中
        onChoose: function (/**Event*/ evt) {
          evt.oldIndex; // element index widthin parent
        },
        // 开始拖拽的时候
        onStart: function (/**Event*/ evt) {
          evt.oldIndex; // element index widthin parent
        },
        // 结束拖拽
        onEnd: function (/**Event*/ evt) {
          var itemEl = evt.item; // dragged HTMLElement
          evt.to; // target list
          evt.from; // previous list
          evt.oldIndex; // element's old index widthin old parent
          evt.newIndex; // element's new index widthin new parent
          evt.clone; // the clone element
          evt.pullMode; // when item is in another sortable: `"clone"` if cloning, `true` if moving
        },
        // 元素从一个列表拖拽到另一个列表
        onAdd: function (/**Event*/ evt) {
          // same properties as onEnd
        },
        // 列表内元素顺序更新的时候触发
        onUpdate: function (/**Event*/ evt) {
          // same properties as onEnd
        },
        // 列表的任何更改都会触发
        onSort: function (/**Event*/ evt) {
          // same properties as onEnd
        },
        // 元素从列表中移除进入另一个列表
        onRemove: function (/**Event*/ evt) {
          // same properties as onEnd
        },
        // 试图拖拽一个filtered的元素
        onFilter: function (/**Event*/ evt) {
          var itemEl = evt.item; // HTMLElement receiving the `mousedown|tapstart` event.
        },
        // 拖拽移动的时候
        onMove: function (/**Event*/ evt, /**Event*/ originalEvent) {
          // Example: https://jsbin.com/nawahef/edit?js,output
          evt.dragged; // dragged HTMLElement
          evt.draggedRect; // DOMRect {left, top, right, bottom}
          evt.related; // HTMLElement on which have guided
          evt.relatedRect; // DOMRect
          evt.willInsertAfter; // Boolean that is true if Sortable will insert drag element after target by default
          originalEvent.clientY; // mouse position
          // return false; — for cancel
          // return -1; — insert before target
          // return 1; — insert after target
        },
        // clone一个元素的时候触发
        onClone: function (/**Event*/ evt) {
          var origEl = evt.item;
          var cloneEl = evt.clone;
        },
        // 拖拽元素改变位置的时候
        onChange: function (/**Event*/ evt) {
          evt.newIndex; // most likely why this event is used is to get the dragging element's current index
          // same properties as onEnd
        },
      });
    },
    //列拖拽
    columnDrop() {
      const wrapperTr = document.querySelector(".vxe-table--header-wrapper tr");
      this.sortable = Sortable.create(wrapperTr, {
        animation: 180,
        delay: 0,
        onEnd: (evt) => {
          console.log(evt, "evt-----------");
          const oldItem = this.tablelabel[evt.oldIndex];
          this.tablelabel.splice(evt.oldIndex, 1);
          this.tablelabel.splice(evt.newIndex, 0, oldItem);
          this.InitializeSortable();
        },
      });
    },
    scrollHeight() {
      setTimeout(() => {
        this.$refs.xTable.scrollTo(0, 0);
      }, 500);
    },
  },
};
</script>

<style lang="scss" scoped>
.firstspan {
  display: flex;
  span {
    margin-right: 20px;
  }
}
.machineinfo {
  text-align: left !important;
  font-weight: 500;
  p {
    margin-bottom: 0px;
  }
  .info {
    display: flex;
    align-items: center;
    margin-top: 5px;
    .info-right {
      display: flex;
      flex-direction: column;
      justify-content: center;
      margin: 0 0 0 15px;
    }
  }
}
.look {
  display: flex;
  flex-direction: column;
}
.operate {
  display: flex;
  flex-direction: column;
  align-items: center;
  span {
    line-height: 20px;
  }
}
::v-deep {
  .vxe-table--body .vxe-cell--checkbox:nth-child(odd) :after {
    content: "";
    position: absolute;
    top: 0px;
    right: -5px;
    display: inline-block;
    width: 20px;
    height: calc(100% - 1px);
    background-color: #ffffff;
  }
  .vxe-body--row.row--hover {
    .vxe-cell--checkbox:nth-child(odd) :after {
      background-color: #f5f7fa;
    }
  }

  /*调整表格 单元格背景颜色*/
  .vxe-table .vxe-table--body-wrapper,
  .vxe-table .vxe-table--footer-wrapper {
    border: none;
    background-color: rgba(255, 255, 255);
  }
  .vxe-cell--checkbox:nth-child(odd) {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .vxe-body--row:nth-child(even) {
    background-color: rgb(248 248 249);
  }
}
</style>
<!-- <template #default="{ row }">
 <div v-if="row.price && row.maoney">
  <span
 :class="row.price * 0.98 - row.maoney.total_fee / 1 - dateOne.total_cost / 1 > 0 ? 'red' : 'green'">{{
(
  row.price * 0.98 - row.maoney.total_fee / 1 - dateOne.total_cost / 1).toFixed(2) }}</span>
   <span class="red">~</span>
   <span
  :class="row.price * 0.99 - row.maoney.total_fee / 1 * 0.01 - dateOne.total_cost / 1 > 0 ? 'red' : 'green'">{{
   (
   row.price * 0.99 - row.maoney.total_fee / 1 - dateOne.total_cost / 1).toFixed(2) }}</span>
   </div>
   <div v-else>/</div>
  </template> -->