<template>
  <div class="order">
    <div class="frame">
      <el-input class="mr20" v-model="parameter.params.id" placeholder="订单Id" clearable></el-input>
      <!-- <autocomplete
          class="mr20"
          :params="parameter.params"
          :config="configAutocomplete"
        /> -->
        <!-- 炼厂名称 -->
      <autocomplete
        class="mr20"
        :params="parameter.params"
        :config="configAutocompleteLc"
      />
      <!-- <el-select style="margin-right: 20px;" v-model="parameter.params.id" placeholder="用户名称" clearable>
        <el-option
          v-for="item in refineryList"
          :key="item.id"
          :label="item.refineryName"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <el-select v-model="parameter.params.id" placeholder="炼厂名称" clearable>
        <el-option
          v-for="item in refineryList"
          :key="item.id"
          :label="item.refineryName"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <el-select v-model="parameter.params.id" placeholder="产品名称" clearable>
        <el-option
          v-for="item in refineryList"
          :key="item.id"
          :label="item.refineryName"
          :value="item.id"
        >
        </el-option>
      </el-select> -->
      <div class="buttons">
        <el-button icon="el-icon-search" @click="handleCurrentChange(1)"
          >查询</el-button
        >
        <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
      </div>
    </div>
    <div class="table">
      <div class="operation">
        <!-- <el-button icon="el-icon-upload2" @click="addition">炼厂入驻</el-button> -->
      </div>
      <el-table
        v-if="tableHeight"
        ref="multipleTable"
        :height="tableHeight"
        :data="tableData"
        style="width: 100%"
      >
      <el-table-column
          prop="id"
          label="订单ID"
          show-overflow-tooltip
          minWidth="250"
        >
      </el-table-column>
        <el-table-column label="购方客户信息" minWidth="250">
          <template slot-scope="{ row }">
            <p class="gray">
              <span>{{ row.customerName }}</span>
            </p>
            <p class="gray">
              <span>{{ row.customerId || "暂无" }}</span>
            </p>
          </template>
        </el-table-column>
        <el-table-column label="炼厂&产品" minWidth="250">
          <template slot-scope="{ row }">
            <p class="gray">
              炼厂名称 <span>{{ row.refineryName }}</span>
            </p>
            <p class="gray">
              产品名称 <span>{{ row.productName }}</span>
            </p>
          </template>
        </el-table-column>

        <el-table-column 
        prop="salePrice" label="价格" minWidth="90">
        </el-table-column>

    
        <el-table-column prop="payStatus" label="支付状态" minWidth="120" show-overflow-tooltip>
          <template slot-scope="{ row }">
            <el-tag :effect="payTagType(row.payStatus).effect" :type="payTagType(row.payStatus).type">{{ payTagType(row.payStatus).label }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="订单状态" minWidth="120">
          <template slot-scope="{ row }">
            <el-tag :effect="orderTagType(row.orderStatus).effect" :type="orderTagType(row.orderStatus).type">{{ orderTagType(row.orderStatus).label }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="orderSerialNumber"
          label="订单提货量(实际/预约)"
          minWidth="180"
        >
          <template slot-scope="{ row }">
            <span>{{ row.actQuantity|toNumberFixed }} / {{ row.preQuantity?row.preQuantity:'--' }} 吨</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="orderSerialNumber"
          label="订单金额(实际/预约)"
          minWidth="180"
        >
          <template slot-scope="{ row }">
            <span>{{ row.actAmount|toNumberFixed }} / {{ row.preAmount|toNumberFixed }} 元</span>
          </template>
        </el-table-column>
        <el-table-column label="时间" minWidth="235">
          <template slot-scope="{ row }">
            <p class="gray">
              创建时间 <span>{{ row.createTime }}</span>
            </p>
            <p class="gray">
              更新时间 <span>{{ row.updateTime || "暂无" }}</span>
            </p>
          </template>
        </el-table-column>
        <el-table-column prop="orderSerialNumber" fixed="right" label="操作" width="250">
          <template slot-scope="{ row }">
            <el-link type="primary" :underline="false" @click="detail(row)"
              >详情</el-link
            >
            <el-link v-show="row.orderStatus!=='SUBMITED'&&row.orderStatus!=='ORDER_LOCKED'" type="primary" :underline="false" @click="billOfLading(row)"
              >提货单</el-link
            >
            <el-popconfirm
              title="是否确认订单锁定？"
              icon-color="red"
              @confirm="deleteRow(row)"
            >
              <el-link v-show="row.orderStatus=='SUBMITED'" slot="reference" type="primary" :underline="false"
                >订单锁定</el-link
              >
            </el-popconfirm>
            <el-popconfirm
              title="是否确认取消订单？"
              icon-color="red"
              @confirm="deleteRow(row,'delete')"
            >
              <el-link v-show="row.orderStatus=='SUBMITED'" slot="reference" type="primary" :underline="false"
                >订单取消</el-link
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="parameter.currentPage"
        :page-size="parameter.pageSize"
        :popper-append-to-body="false"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-drawer
      title="详情"
      direction="ltr"
      size="60%"
      :withHeader="false"
      :visible="controlWindows.detail"
    >
      <general-details
        title="详情"
        :isHeader="true"
        v-if="controlWindows.detail"
        :sourceData="oilCompanyMatch"
        :mappingData="mappingData"
        @close="controlWindows.detail = false"
      >
      </general-details>
    </el-drawer>
    <!-- 提货单 -->
    <billOfLading @billOfLading="billOfLading" :billData="billData" :controlWindows="controlWindows" @closeWindow="handleCurrentChange" />
  </div>
</template>

<script>
import serve from "api/refineryInfo.js";
import order from "api/order.js";
import generalDetails from "components/generalDetails/index.vue";
import commonServe from "api/common.js";
import billOfLading from "./components/billOfLading.vue";
import autocomplete from "components/autocomplete/index.vue";
import { mapGetters } from "vuex";

export default {
  filters:{
    toNumberFixed(val){
      if(val){
        return Number(val).toFixed(2)
      }else{return '--'}
    }
  },
  data() {
    return {
      controlWindows: {
        add: false,
        addInfo: {

        },
        detail: false,
        bill: false,
      },
      refineryTypeEnum: [
        {
          label: "普通炼厂",
          value: "COMMON",
        },
      ],
      configAutocomplete: {
        serveTarget: commonServe.getRefineryCompanyList,
        autocompleteKey: "name",
        labelKey: "name",
        valueKey: "id",
        placeholder: "企业名称",
        querykey: "customerId",
      },
      configAutocompleteLc: {
        serveTarget: serve.findByEntity,
        autocompleteKey: "name",
        labelKey: "refineryName",
        valueKey: "id",
        placeholder: "炼厂名称",
        querykey: "refineryId",
      },
      refineryList: [],
      tableHeight: 0,
      tableData: [],
      total: 0,
      parameter: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        params: {
        },
      },
      oilCompanyMatch: {},
      billData:[],
      mappingData: [
        {
          carTitle: "",
          carItems: [
            { label: "订单ID", value: "id" },
            { label: "炼厂ID", value: "refineryId" },
            { label: "支付状态", value: "payStatus" },
            { label: "订单状态", value: "orderStatus" },
            { label: "提货单数量", value: "deliveryCount" },
            // { label: "创建用户ID", value: "createUser" },
            // { label: "创建时间", value: "createTime" },
            // { label: "修改用户ID", value: "updateUser" },
            // { label: "修改时间", value: "updateTime" },
          ],
        },
      ],
    };
  },
  computed: {
    ...mapGetters(["company_id"]),
  },
  components: {
    generalDetails,
    billOfLading,
    autocomplete
  },
  mounted() {
    this.$nextTick(() => {
      this.heightHandle();
    });
    window.addEventListener(
      "resize",
      this.$utils.debounce(this.heightHandle, 500)
    );
  },
  created() {
    this.findByEntity();
    this.getByPage();
    console.log(this.$store.state.user.companyId,'ssssssssssss')
  },
  methods: {
    payTagType(val){
      switch(val){
        case 'PREPAID': return {label:'预支付',type:'info'}
        case 'PAYING': return {label:'支付中',type:'warning'}
        case 'SUCCESS': return {label:'支付成功',type:'success',effect:'dark'}
        case 'FAILURE': return {label:'支付失败',type:'danger',effect:'dark'}
        case 'CANCELED': return {label:'支付取消',type:'info'}
        case 'REFUNDED': return {label:'退款成功',type:'danger',effect:'dark'}
        case 'REFUNDING': return{label:'退款中',type:'warning'}
        case 'REFUNDFAIL': return{label:'退款失败',type:'info',effect:'dark'}
      }
      return {label:val?val:'暂无数据',type:'info',effect:'plain'}
    },
    orderTagType(val){
      switch(val){
        case 'SUBMITED': return {label:'订单提交 ',type:'info'}
        case 'ORDER_LOCKED': return {label:'订单锁定',type:'warning'}
        case 'ORDER_SUCCESS': return {label:'下单成功',type:'success',effect:'dark'}
        case 'DELIVERING': return {label:'提货中', type: ''}
        case 'COMPLETE': return {label:'订单完成',type:'success',effect:'dark'}
        case 'CANCELED': return {label:'订单取消',type:'info'}
      }
      return {label:val?val:'暂无数据',type:'info'}
    },
    // currentPage change
    handleCurrentChange(page) {
      this.parameter.currentPage = page;
      this.getByPage();
    },
    // pageSize change
    handleSizeChange(size) {
      this.parameter.currentPage = 1;
      this.parameter.pageSize = size;
      this.getByPage();
    },
    //table list
    getByPage() {
      this.parameter.params.customerId=this.$store.state.user.companyId
      order.getByPage(this.parameter).then((res) => {
        this.tableData = res.data.list;
        this.total = res.data.totalCount;
      });
    },
    //炼厂list
    findByEntity() {
      serve.findByEntity().then((res) => {
        this.refineryList = res.data;
      });
    },
    //新增
    addition() {
      this.controlWindows.addInfo.title = "炼厂入驻";
      this.controlWindows.add = true;
    },
    //提货单
    async billOfLading(row,selectIndex){
      this.controlWindows.addInfo.title = "";
      if(!selectIndex||selectIndex==1){
        await order.findDeliveryByOrderId(row.id).then((res) => {
        this.billData.list = res.data
      });
      }
      if(!selectIndex||selectIndex==2){
        await order.findByOrderId(row.id).then((res) => {
          console.log('更新',res)
        this.billData.orderInfo = Object.assign(res.data,{id:row.id})
      });
      }
      this.controlWindows.addInfo = row
      this.controlWindows.bill = true
    },
    //详情
    detail(row) {
      this.oilCompanyMatch = [row];
      this.controlWindows.detail = true;
    },
    //订单锁定
    deleteRow(row,type) {
      let api = type&&type=='delete'?'cancel':'orderLock';
      let data = {id:row.id};
      (api=='cancel')&&(data['orderStatus']='CANCELED');
      order[api](data).then((res) => {
        if(res.code == 20000){
          this.getByPage()
        }
      });
    },
    //启用禁用
    switchTrigger(val, row) {
      row.enableMark = row.enableMark;
      serve
        .update({
          id: row.id,
          enableMark: val,
        })
        .then((res) => {
          if (res.code === 20000) {
            this.getByPage();
          } else this.$message.error(res.msg);
        });
    },
    //重置
    reset() {
      this.parameter = {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        params: {},
      };
    },
    // table height
    heightHandle() {
      let bodyHeight = document.body.clientHeight;
      let frameHeight = this.obtainElement(".frame").clientHeight;
      let operationHeight = this.obtainElement(".operation").clientHeight;
      let paginationHeight = this.obtainElement(".el-pagination").clientHeight;
      this.tableHeight =
        bodyHeight - frameHeight - operationHeight - paginationHeight - 145;
    },
    obtainElement(className) {
      return document.documentElement.querySelector(className);
    },
  },
};
</script>

<style lang="scss" scoped>
.order {
  .frame {
    margin: 20px;
    padding: 20px;
    // width: 100%;
    border-radius: 6px;
    border: 1px solid #e3e3e5;
    background: #fff;
    .el-input,
    .el-select {
      width: 183px;
      height: 40px;
    }
    .el-input + .el-input,
    .el-input + .el-select,
    .el-select + .el-select,
    .el-select + .el-input {
      margin-right: 20px;
      margin-bottom: 15px;
    }
    .mr20 {
      margin-right: 20px;
    }
    .buttons {
      text-align: right;
    }
  }

  .table {
    overflow: hidden;
    margin: 0 20px;
    padding-bottom: 20px;
    background: #fff;
    border-radius: 6px;
    border: 1px solid #e3e3e5;
    > .operation {
      box-sizing: content-box;
      // padding: 15px;
    }
    .gray {
      color: #999;
      span {
        color: #333;
      }
    }
    .el-table {
      margin-bottom: 20px;
      border-radius: 10px 10px 0px 0px;
    }
    .el-link {
      margin-right: 10px;
    }
  }
}
</style>
