<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 @checkbox-change="selectEvent"
      @checkbox-all="selectAllEvent">
      <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" :show-overflow="item.remarkshow" align="center">
        <!-- <template
          v-if="
            item.label == '预计结算价'
          "
          v-slot:header="{ column, rowIndex }"
        >
          <span>{{ item.label }}</span>
          <el-tooltip
            class="item"
            effect="dark"
            content="点击批量修改"
            placement="top-start"
          >
            <i
              class="el-icon-document-copy"
              style=" margin-left: 5px; cursor: pointer"
            />
          </el-tooltip>
        </template> -->
        <template slot-scope="{ row }">
          <span v-if="row.render" class="firstspan">
            <span v-if="row.business_id">
              <span v-if="item.link" style="display: flex; align-items: center">
                质检码：
                <el-link :underline="false" type="primary" @dblclick.native="jump(row, '质检码')">{{ row.business_id
                  }}</el-link>
              </span>
              <!-- <span v-else-if="item.isdetail" style="display: flex; align-items: center">
                质检码：
                <el-link :underline="false" type="primary" @dblclick.native="jump(row, '审核页')">{{ row.business_id
                  }}</el-link>
              </span> -->
              <span v-else> 质检码：{{ row.business_id }} </span>
            </span>
            <span v-if="row.biz_order_id">订单编号：{{ row.biz_order_id }}</span>
            <span v-if="row.refund_id">售后订单编号：{{ row.refund_id }}</span>
            <span v-if="
              row.publish_time && /^\d{10}$|^\d{13}$/.test(row.publish_time)
            ">发布时间：{{
              row.publish_time | dateformat("YYYY-MM-DD HH:mm:ss")
            }}</span>
            <span v-if="row.last_truename">最近翻库人：{{ row.last_truename }}</span>
            <span v-if="row.last_publish_time">最近翻库日期：{{
              row.last_publish_time | dateformat("YYYY-MM-DD HH:mm:ss")
            }}</span>
            <span v-if="row.buyer_nick">买家昵称：{{ row.buyer_nick }}</span>
          </span>
          <span v-else-if="!row.render">
            <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/img/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 === '机器成色'">
              {{
                Number(row.stuff_status) > 0
                  ? row.stuff_status + "新"
                  : row.stuff_status
              }}
            </span>
            <span v-else-if="
              item.label === '机器状态' ||
              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 ? 'red' : '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.99) / 100).toFixed(2)
              }}</span>
            </span>
            <span v-else-if="item.label == '预估利润'">
              <span :style="6 ? 'color:#2ed573' : 'color:#ff6b81'">{{
                Number(
                  (row.price * 0.99) / 100 - row.total_cost - row.ag_server_fee
                ).toFixed(2)
              }}</span>
            </span>

            <span v-else-if="
              item.label == '退款金额' ||
              item.label == '申请退款金额' ||
              item.label == '定价' ||
              item.label == '保底价'
            ">
              <span>{{ Number(row[item.param] / 100).toFixed(2) }}</span>
            </span>
            <span
              v-else-if="
                row[item.param] &&
                ((/^\d{10}$|^\d{13}$/.test(row[item.param]) &&
                  item.label == '交易成功时间') ||
                  item.label == '关闭时间' ||
                  item.label == '退款时间' ||
                  item.label == '订单创建时间' ||
                  item.label == '付款时间' ||
                  item.label == '发货时间' ||
                  item.label == '首次发布时间' ||
                  item.label == '申请退款时间')
              "
              >{{ row[item.param] | dateformat("YYYY-MM-DD HH:mm:ss") }}</span
            >
            <div v-else-if="item.label === '快递单号'">
              <div>{{ row.refund_post_company }}</div>
              <div>{{ row[item.param] }}</div>
            </div>
            <!-- 操作 -->
            <span v-else-if="item.label === '操作'" class="operate">
              <el-link v-if="
                item.status.includes('AgreeReturn') &&
                row.refund_status === 1 &&
                row.need_return_goods === 'true'
              " :underline="false" type="primary" @click="operate('AgreeReturn', row)">同意退货</el-link>
              <el-link v-if="
                item.status.includes('AgreeRefund') &&
                row.refund_status === 1 &&
                row.need_return_goods === 'false'
              " :underline="false" type="success" @click="operate('AgreeRefund', row)">同意退款</el-link>
              <el-link v-if="
                (item.status.includes('ConfirmReceipt') &&
                  row.refund_status === 3) ||
                (row.refund_status === 2 && row.need_return_goods === 'true')
              " :underline="false" type="primary" @click="operate('ConfirmReceipt', row)">确认收货</el-link>
              <el-link v-if="
                (item.status.includes('RefusalReceipt') &&
                  row.refund_status === 3) ||
                (row.refund_status === 2 && row.need_return_goods === 'true')
              " :underline="false" type="danger" @click="operate('RefusalReceipt', row)">拒绝收货</el-link>
              <el-popconfirm title="是否拒绝退款？" v-if="
                (item.status.includes('RefundRefused') &&
                  row.refund_status === 1) ||
                row.refund_status === 3
              " @confirm="operate('RefundRefused', row)">
                <el-link slot="reference" type="danger" :underline="false">拒绝退款</el-link>
              </el-popconfirm>
              <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-link
                type="danger"
                v-if="item.status.includes('Reject')"
                @click="operate('Reject', row)"
                :underline="false"
                >驳回</el-link
              >
              <el-popconfirm
                title="是否重新发布？"
                v-if="item.status.includes('Republish')"
                @confirm="operate('Republish', row)"
              >
                <el-link slot="reference" type="primary" :underline="false"
                  >重新发布</el-link
                >
              </el-popconfirm>
              <el-popconfirm title="是否删除？" v-if="item.status.includes('Deletegoods')"
                @confirm="operate('Deletegoods', row)">
                <el-link slot="reference" type="danger" :underline="false">删除</el-link>
              </el-popconfirm>
              <el-link type="danger" :underline="false" v-if="item.status.includes('OffShelf')"
                @click="operate('OffShelf', row)">下架</el-link>
              <el-link v-if="item.status.includes('ChangePrice')" :underline="false" type="primary"
                @click="operate('ChangePrice', row)">改价</el-link>
              <el-link v-if="item.status.includes('AddOrder')" :underline="false" type="primary"
                @click="operate('AddOrder', row)">补订单</el-link>
              <el-link v-if="item.status.includes('CloseTrade')" :underline="false" type="success"
                @click="operate('CloseTrade', row)">关闭交易</el-link>
              <el-link v-if="
                item.status.includes('Delivery') &&
                (!row.refund_status ||
                  ![1, 2, 3, 5, 8].includes(row.refund_status))
              " :underline="false" type="primary" @click="operate('Delivery', row)">立即发货</el-link>
              <el-link v-if="item.status.includes('LogisticsInfo')" :underline="false" type="primary"
                @click="operate('LogisticsInfo', row)">物流信息</el-link>
              <el-link v-if="item.status.includes('Intercept')" :underline="false" type="primary"
                @click="operate('Intercept', row)">快递拦截</el-link>
              <el-link v-if="item.status.includes('Print')" :underline="false" type="primary"
                @click="operate('Print', row)">打印面单</el-link>

              <el-link type="warning" :underline="false" v-if="item.status.includes('Logs')"
                @click="operate('Logs', row)">日志</el-link>
              <el-link type="success" :underline="false" v-if="item.status.includes('GoAudit')"
                @click="operate('GoAudit', row)">审核</el-link>
            </span>
            <span v-else-if="item.label == '备注' && item.fixed == 'right'">
              <vxe-button type="text" icon="vxe-icon-edit" @click="editEvent(row)" />
              <span>{{ row.remark }}</span>
            </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:"erpXyTable",
  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;
        case "质检码":
          this.$router.push({
            path: "idleFishIssue",
            query: { xy_product_id: row.xy_product_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;
        case "ChangePrice":
          this.$emit("ChangePrice", data);
          break;
        case "Republish":
          this.$emit("Republish", data);
          break;
        case "Deletegoods":
          this.$emit("Deletegoods", data);
          break;
        case "AddOrder":
          this.$emit("AddOrder", data);
          break;
        case "CloseTrade":
          this.$emit("CloseTrade", data);
          break;
        case "Delivery":
          this.$emit("Delivery", data);
          break;
        case "LogisticsInfo":
          this.$emit("LogisticsInfo", data);
          break;
        case "Intercept":
          this.$emit("Intercept", data);
          break;
        case "AgreeReturn":
          this.$emit("AgreeReturn", data);
          break;
        case "RefundRefused":
          this.$emit("RefundRefused", data);
          break;
        case "AgreeRefund":
          this.$emit("AgreeRefund", data);
          break;
        case "ConfirmReceipt":
          this.$emit("ConfirmReceipt", data);
          break;
        case "RefusalReceipt":
          this.$emit("RefusalReceipt", data);
          break;
        case "Print":
          let params = {
            tracking_number: data.express_no,
            express_company_id: data.express_company_id,
          };
          this.$emit("Print", params);
          break;
        case "GoAudit":
          this.$emit("GoAudit", 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;
      }
    },
    // 修改备注
    editEvent(row) {
      const dataToEdit = row.remark;
      let inputValue = dataToEdit; // 使用变量保存输入框的值

      this.$confirm("", "修改备注", {
        cancelButtonText: "重置",
        confirmButtonText: "提交",
        customClass: "custom-prompt",
        inputPlaceholder: "请输入备注",
        inputType: "textarea",
        inputRows: 5,
        inputValue: inputValue,
        showInput: true,
        distinguishCancelAndClose: true,
        beforeClose: (action, instance, done) => {
          // 判断点击的按钮
          if (action === "confirm" || action === "close") {
            done();
          } else if ((instance.inputValue = "cancel")) {
            instance.inputValue = "";
          }
        },
      })
        .then(({ value }) => {
          this.$emit("submitRemark", row, value);
        })
        .catch(() => {
          // 处理取消按钮的逻辑
        });
    },
    // 质检报告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);
    },
    //多选表格
    selectAllEvent(val) {
      this.$emit("selectAllEvent", val.records);
    },
    // 单选表格
    selectEvent(val) {
      this.$emit("selectEvent", val.records);
    },
  },
};
</script>

<style lang="scss" scoped>
// .remark {
//   display: flex;
//   align-items: center;
//   justify-content: center;
// }
// .item {
//   width: 50%;
//   display: inline-block;
//   overflow: hidden;
//   text-overflow: ellipsis;
//   white-space: nowrap;
// }
.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>
