<template>
  <div class="order-detail-part">
    <div
      v-if="isLoading == 1"
      v-loading="true"
      class="com-loading"></div>
    <template v-else-if="isLoading == 2">
      <!-- <div class="eco-tip"  v-if="orderDetail.Emission_Total_Kg && orderDetail.Emission_Total_Kg != '0'">
        <div class="eco-tip-title">
          <img
            src="@/assets/img/esg/leaf.png"
            alt="eco"
            class="eco-tip-icon" />
          <span> Protecting Nature Starts with Your Choice</span>
        </div>
        <div class="eco-tip-desc">
          Your Eco-Friendly Purchase Generated
          <span class="eco-tip-co2"
            >{{ orderDetail.Emission_Total_Kg || 0 }} KG</span
          >
          Of Carbon Emissions. Together, We<br />
          Embrace Enyironmental Responsibility For A More Sustainable Future.
        </div>
      </div> -->
      <section class="main-header">
        <div class="main-header-mid flex between">
          <h1>Job Name：{{ orderDetail.Sales_Order_Title_Job_Name }}</h1>
          <img
            :src="orderDetail.user_logo"
            class="user_logo"
            v-if="orderDetail.user_logo" />
        </div>
        <div class="main-header-mid">
          <ul class="left">
            <li
              class="left-i link-div"
              v-if="isShow">
              <div @click="shareDialogVisible = true">
                <i class="el-icon-share"></i>
                <span>Client Tracking Share</span>
              </div>
              <!-- <div v-for="(item) in orderDetail.crm_esg_res?.flat()"
              @click="downloadEsg(item)" 
              :key="item.id">
                <img src="@/assets/img/order/cer.png" />
                <span> DownLoad {{ item.name }}</span>
              </div> -->
            </li>
            <li
              class="left-i"
              v-if="orderDetail.crm_pr_res?.length">
              <image-list :data="orderDetail.crm_pr_res" />
            </li>
          </ul>
          <ul class="right">
            <li v-if="orderDetail.Job_Group && isShow">
              Order Type: {{ orderDetail.Job_Group }}
            </li>
            <li>Order No: {{ orderDetail.Reference }}</li>
            <li>
              Order Date: {{ formatStepDesc(orderDetail.Sales_Order_Created) }}
            </li>
            <li v-if="orderDetail.Expected_Delivery_Date">
              ETA: {{ formatStepDesc(orderDetail.Expected_Delivery_Date) }}
            </li>
            <li v-if="isShow">
              Payment Status: {{ orderDetail.Payment_Status1 }}
            </li>
          </ul>
        </div>
        <div class="steps margin-b-30">
          <p class="steps-title margin-b-50">Bulk Production</p>
          <el-steps
            :active="comOrderState"
            align-center
            :direction="computedStepDirection"
            finish-status="success"
            process-status="wait">
            <el-step
              title="Confirmed"
              :description="formatStepDesc(orderDetail.Order_Confirm)">
            </el-step>
            <el-step
              title="In Production"
              :description="
                formatStepDesc(orderDetail.Sampling_Factory_Confirm)
              "></el-step>
            <el-step
              title="QC Inspection"
              :description="formatStepDesc(orderDetail.GZ_WH)"></el-step>
            <el-step
              title="International Shipment"
              :description="
                formatStepDesc(orderDetail.International_transshipment)
              "></el-step>
            <el-step
              title="UK Warehouse"
              :description="formatStepDesc(orderDetail.AU_WH)"></el-step>
            <el-step
              :title="
                orderDetail.Order_Stage === 'Bulk Production Shipping'
                  ? 'Domestic Delivery'
                  : 'Shipped'
              "
              :description="formatStepDesc(orderDetail.AU_WH_Client)"></el-step>
            <el-step
              title="Delivered"
              :description="formatStepDesc(orderDetail.Delivered)"></el-step>
          </el-steps>
        </div>
        <div
          class="steps"
          :class="{ 'margin-b-30': stepShow }"
          v-if="orderDetail.Sample_Stage">
          <p
            class="steps-title pointer"
            :class="{ 'margin-b-50': stepShow }"
            @click="toggleStep">
            Sample Dispatch
            <i
              :class="
                stepShow ? 'el-icon-arrow-down' : 'el-icon-arrow-right'
              "></i>
          </p>
          <el-steps
            :active="comSampleState"
            align-center
            :space="180"
            v-if="stepShow"
            :direction="computedStepDirection"
            finish-status="success"
            process-status="wait">
            <el-step
              title="Factory Process"
              :description="
                formatStepDesc(orderDetail.Sample_Factory_Confirmed)
              ">
            </el-step>
            <el-step
              title="Sample Dispatching"
              :description="
                formatStepDesc(orderDetail.Sample_Dispatching)
              "></el-step>
            <el-step
              title="Sample Delivered"
              :description="
                formatStepDesc(orderDetail.Sample_Delivered)
              "></el-step>
          </el-steps>
        </div>
      </section>
      <section class="main-custom">
        <p class="sharing-title">Customer information</p>
        <div>
          <p class="sharing-subtitle">
            {{ isShow ? 'Billing' : 'Supplier' }} Address
          </p>
          <div class="sharing-address">
            <p>{{ orderDetail.Account_Name_name }}</p>
            <p>{{ orderDetail.Billing_Unit_Building_Name }}</p>
            <p>{{ orderDetail.Billing_Street }}</p>
            <p>{{ orderDetail.Billing_City }}</p>
            <p>{{ orderDetail.Billing_State }}</p>
            <p>{{ orderDetail.Billing_Code }}</p>
            <p>{{ orderDetail.Billing_Country }}</p>
          </div>
        </div>
        <div>
          <p class="sharing-subtitle">Shipping Address</p>
          <div class="sharing-address">
            <p>{{ orderDetail.Shipping_Unit_Building_Name }}</p>
            <p>{{ orderDetail.Shipping_Street }}</p>
            <p>{{ orderDetail.Shipping_City }}</p>
            <p>{{ orderDetail.Shipping_State }}</p>
            <p>{{ orderDetail.Shipping_Code }}</p>
            <p>{{ orderDetail.Shipping_Country }}</p>
          </div>
        </div>
      </section>
      <section>
        <p class="sharing-title">Shipping information</p>
        <el-table
          :data="orderDetail.shipping_tracking"
          style="width: 100%"
          :header-cell-style="{
            background: '#F7F8FC',
            color: '#101010',
            fontWeight: 'normal',
          }">
          <el-table-column
            type="expand"
            style="padding: 0">
            <template slot-scope="props">
              <el-table
                :data="props.row.test_pkg_details"
                style="margin-left: 50px; width: calc(100% - 50px)"
                :header-cell-style="{
                  background: '#F7F8FC',
                  color: '#101010',
                  fontWeight: 'normal',
                }">
                <el-table-column
                  prop="Product_name"
                  label="Item & Description"></el-table-column>
                <el-table-column
                  prop="Quantity_to_pack"
                  label="QTY"
                  width="450"></el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column
            prop="Title"
            label="Job Name"
            width="190"></el-table-column>
          <el-table-column
            prop="Courier"
            label="Carrier"
            width="190"></el-table-column>
          <el-table-column
            prop="Tracking_No"
            label="Tracking#"
            width="190"></el-table-column>
          <el-table-column
            prop="Package_Status"
            label="Shipment Status"
            width="190"></el-table-column>
          <el-table-column
            label="Delivery Address"
            width="250">
            <template slot-scope="scope">
              <span>
                {{ scope.row.Shipping_Unit_Building_Name }}<br />
                {{ scope.row.Shipping_Street }}<br />
                {{ scope.row.Shipping_City }}<br />
                {{ scope.row.Shipping_State }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="Tracking_URL"
            label=""
            width="200">
            <template
              slot-scope="scope"
              v-if="scope.row.Tracking_URL">
              <el-button
                size="mini"
                @click.native="openTracking_URL(scope.row.Tracking_URL)"
                style="background-color: rgb(0, 33, 59); color: #fff"
                plain
                >TRACK SHIPMENT</el-button
              ></template
            >
          </el-table-column>
        </el-table>
      </section>
      <section class="orderTable">
        <p class="sharing-title">Products Information</p>
        <el-table
          :data="orderDetail.sales_orders_details"
          style="width: 100%"
          :header-cell-style="{
            background: '#fff',
            color: '#101010',
            fontWeight: 'normal',
          }">
          <el-table-column
            type="index"
            label="S.NO"
            width="70"
            fixed>
          </el-table-column>
          <el-table-column
            label="Product Name"
            min-width="300">
            <template slot-scope="scope">
              <p class="colorBlue">{{ scope.row.product_name }}</p>
              <!-- <p class="table-list-co2" v-if="scope.row.Emision_Details_value && scope.row.Emision_Details_value != '0'">
                  <img src="@/assets/img/esg/co2_green.png" alt="CO2" class="co2-icon" />
                  <span>{{ scope.row.Emision_Details_value }} kg CO₂e</span>
                </p> -->
              <p v-html="scope.row.product_description"></p>
              <!-- <p :class="scope.row.showMore?'ellipsis':''" v-html="scope.row.product_description"></p>
                    <p class="colorBlue cursor" @click="toggleShow(scope.row)" v-if="scope.row.product_description">{{scope.row.showMore?'Show More':'Conceal'}}<i  :class="scope.row.showMore?'el-icon-caret-bottom':'el-icon-caret-top'"></i></p> -->
            </template>
          </el-table-column>
          <el-table-column
            prop="quantity"
            label="Quantity"
            align="left"
            :width="isShow ? 125 : 200">
          </el-table-column>
          <template v-if="isShow">
            <el-table-column
              prop="list_price"
              :label="`List Price(${comCurrency})`"
              width="125">
              <template slot-scope="scope">
                {{ transformNumber(scope.row.list_price) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="amount"
              :label="`Amount(${comCurrency})`"
              width="125">
              <template slot-scope="scope">
                {{ transformNumber(scope.row.amount) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="Tax"
              :label="`Tax(${comCurrency})`"
              width="125">
              <template slot-scope="scope">
                {{ transformNumber(scope.row.Tax) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="Discount"
              :label="`Discount(${comCurrency})`"
              width="125">
              <template slot-scope="scope">
                {{ transformNumber(scope.row.Discount) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="net_total"
              :label="`Total(${comCurrency})`"
              width="125">
              <template slot-scope="scope">
                {{ transformNumber(scope.row.net_total) }}
              </template>
            </el-table-column>
          </template>
        </el-table>
        <div
          class="table-wrap"
          v-if="isShow">
          <table class="total">
            <tr>
              <td>Sub Total</td>
              <td>
                {{ comCurrency }} {{ transformNumber(orderDetail.Sub_Total) }}
              </td>
            </tr>
            <tr>
              <td>Total Taxes</td>
              <td>
                {{ comCurrency }} {{ transformNumber(orderDetail.Tax_Total) }}
              </td>
            </tr>
            <tr>
              <td>Total Discount</td>
              <td>
                {{ comCurrency }}
                {{ transformNumber(orderDetail.Total_Including_Discount) }}
              </td>
            </tr>
            <tr>
              <td>Adjustment</td>
              <td>
                {{ comCurrency }}
                {{ transformNumber(orderDetail.Total_Adjustment) }}
              </td>
            </tr>
            <tr>
              <td>Grand Total</td>
              <td>
                {{ comCurrency }} {{ transformNumber(orderDetail.Grand_Total) }}
              </td>
            </tr>
          </table>
        </div>
      </section>
      <!-- <section 
        v-if="orderDetail.Order_Stage === 'Sales Order Created'" style="text-align: right;border: none;">
        <el-button
        v-if="orderDetail.Order_Stage === 'Sales Order Created'"
        @click="openApproved(orderDetail)"
        size="small"
        style="background-color: rgb(0, 33, 59); color: #fff;"
        plain
        >Approved</el-button>
      </section> -->
    </template>
    <div v-else>
      <el-empty description="No Data"></el-empty>
    </div>
    <el-dialog
      :lock-scroll="false"
      :visible.sync="urlDialogShow"
      center
      width="850px"
      top="20vh">
      <iframe
        :src="Tracking_URL"
        style="width: 100%; height: 500px"
        frameborder="0"></iframe>
    </el-dialog>
    <export-dialog
      :emailForm="shareForm"
      :visible.sync="shareDialogVisible"
      :title="'Client Tracking Share (no pricing displayed)'"
      :labelShow="false"></export-dialog>
  </div>
</template>

<script>
import throttle from 'lodash.throttle'
import { mapMutations } from 'vuex'
import { round } from '@/utils/price.js'

export default {
  name: 'OrderDetailPart',
  props: {
    isShow: {
      // 订单分享页面隐藏元素
      type: Boolean,
      default: true,
    },
    hasUid: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      orderDetail: {},
      isLoading: 1,
      packageTable: [],
      stepShow: false,
      urlDialogShow: false,
      shareDialogVisible: false,
      loginCount: 0,
      shareForm: {
        Link: '',
      },
      Tracking_URL: '',
      stepConfig: {
        'Order Confirmed': 1,
        'Factory Confirmed': 2,
        'GZ WH': 3,
        Transshipment: 4,
        'AU WH': 5,
        'AUWH - Client': 6,
        'Bulk Production Shipping': 6,
        'Bulk Production Delivered': 7,
        'Completed Sales Order': 7,
        'Factory Process': 1,
        'Sample Dispatching': 2,
        'Sample Delivered': 3,
      },
      computedStepDirection: 'horizontal',
    }
  },
  computed: {
    loginSuccess() {
      return this.$store.state.loginSuccess
    },
    comCurrency() {
      return this.orderDetail.Currency
    },
    comOrderState() {
      if (this.orderDetail.Order_Stage === 'Cancelled') {
        return 0
      }
      return this.stepConfig[this.orderDetail.Order_Stage]
    },
    comSampleState() {
      return this.stepConfig[this.orderDetail.Sample_Stage]
    },
  },
  watch: {
    loginSuccess(newVal) {
      if (newVal) {
        this.getOrderDetail() // 当登录成功后调用获取订单详情
        this.$store.commit('setLoginSuccess', false)
      }
    },
  },
  beforeMount() {
    window.addEventListener('resize', this.judgeStepDirection, false)
    this.judgeStepDirection()
  },
  created() {
    this.getOrderDetail()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.judgeStepDirection, false)
  },
  methods: {
    ...mapMutations({ openDialog: 'openDialog' }),
    judgeStepDirection: throttle(function () {
      this.computedStepDirection =
        window.document.body.clientWidth >= 1000 ? 'horizontal' : 'vertical'
    }, 300),
    toggleStep() {
      this.stepShow = !this.stepShow
    },
    getOrderDetail() {
      let path = ''
      let data = {}
      if (this.isShow) {
        const { id } = this.$store.state.userInfo
        const { crm, id: queryId } = this.$route.query

        path = '/uk-api/crmdata/orders_detail'
        this.shareForm.Link = `https://www.trackship.com.au/orderShare/${id}/${crm}/${queryId}`
        data = { accounts_id: crm, id: queryId }
      } else {
        path = '/uk-api/crmdata/showOrdersDetail'
        if (this.hasUid) {
          const { uid, aid, id } = this.$route.params
          data = { user_id: uid, accounts_id: aid, id }
        } else {
          const { aid, id } = this.$route.params
          data = { accounts_id: aid, id }
        }
      }
      this.$axios
        .post(path, data)
        .then(res => {
          if (res.result === null) {
            this.handleBranchLogic()
          }
          this.orderDetail = res.result
          if (this.orderDetail.shipping_tracking?.length) {
            const isDelivered = true

            for (const items of this.orderDetail.shipping_tracking) {
              if (items.test_pkg_details?.length) {
                items.test_pkg_details.forEach(item => {
                  item.Courier = items.Courier
                  item.Tracking_No = items.Tracking_No
                  item.Package_Status = items.Package_Status
                  item.Tracking_URL = items.Tracking_URL
                })
              }
            }
          }
          if (this.orderDetail.sales_orders_details?.length) {
            if (this.isShow) {
              this.orderDetail.sales_orders_details.forEach(items => {
                this.$set(items, 'showMore', true)
              })
            } else {
              this.orderDetail.sales_orders_details =
                this.orderDetail.sales_orders_details
                  .filter(item => {
                    return (
                      item.product_Product_Code !== 'PC Setup Service' &&
                      item.product_Product_Code !== 'PC Freight'
                    )
                  })
                  .map(item => {
                    this.$set(item, 'showMore', true)
                    return item
                  })
            }
          }
          this.isLoading = 2
        })
        .catch(() => {
          this.handleBranchLogic()
        })
    },
    handleBranchLogic() {
      this.isLoading = 3
      if (this.loginCount) {
        this.$router.push('/')
        return
      }
      this.isShow &&
        setTimeout(() => {
          this.openDialog()
          this.loginCount = 1
        }, 1000)
    },
    transformNumber(value) {
      return round(Number(value)).toFixed(2)
    },
    formatStepDesc(date, isUnix = false) {
      return this.$utils.formatTime(date, 'DD/MM/YYYY', isUnix)
    },
    toggleShow(row) {
      row.showMore = !row.showMore
    },
    openTracking_URL(url) {
      this.Tracking_URL = url
      this.urlDialogShow = true
    },
    download(url) {
      var urlStr = url.match('[^/]+(?!.*/)')[0]
      this.$utils.downloadBlob(url, urlStr)
    },
    downloadEsg(item) {
      if (!item.id) {
        this.$message.error('No report available for download')
        return
      }

      this.$axios
        .post('Crmdata/downloadreport', { id: item.id, name: item.name })
        .then(res => {
          if (res.result) {
            this.$utils.downloadBlob(
              res.result?.data,
              decodeURIComponent(res.result?.url_name)
            )
          } else {
            this.$message.error('Download failed, please try again later')
          }
        })
        .catch(() => {
          this.$message.error('Download failed, please try again later')
        })
    },
    openApproved(row) {
      this.$confirm(
        `
        <div style="text-align:center;">
          <h3 style="margin:0 0 10px;color:#333;">Ready to order?</h3>
          <p style="margin:0;font-size:16px;color:#333;">Your total is <b>${this.transformNumber(
            row.Grand_Total
          )}</b>. Confirm to place your order.</p>
        </div>
        `,
        '',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          confirmButtonClass: 'el-button',
          cancelButtonClass: 'el-button--info',
          center: true,
          showClose: false,
          confirmButtonClass: 'com-btnblack',
        }
      ).then(() => {
        this.$router.push({
          path: '/so-confirm',
          query: { id: row.sales_orders_id, pc_psw: row.HASH },
        })
      })
    },
  },
}
</script>

<style lang="scss" scoped>
@import '../detail.scss';
</style>
