<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <el-form-item label="盲票组名称"  prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入盲票组名称"
          clearable
          size="small"
          style="width: 240px"
          @change="pageParams.pageNum = 1;handleQuery()"
        />
      </el-form-item>

      <el-form-item label="订单类型" prop="orderId">
        <el-select v-model="queryParams.type" placeholder="请选择订单类型" style="width: 100%;" clearable :filter-method="dataFilter" @change="pageParams.pageNum = 1;handleQuery()" >
          <el-option label="全部" value="" />
          <el-option v-for="(item,index) in typeList"  :label="item.dictLabel" :value="Number(item.dictValue)" :key="index"/>
        </el-select>
      </el-form-item>

      <el-form-item label="订单号" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="输入订单编号"
          clearable
          size="small"
          style="width: 240px"
          @change="pageParams.pageNum = 1;handleQuery()"
        />
      </el-form-item>
      <el-form-item label="门店" prop="channelId">
        <el-select
          v-model="queryParams.channelId"
          placeholder="请选择门店"
          style="width: 100%;"
          filterable
          clearable
          :filter-method="dataFilter"
          @change="pageParams.pageNum = 1;handleQuery()"
        >
          <el-option
            v-for="(item, index) in siteList"
            :key="item.channelId"
            :label="item.name"
            :value="item.channelId">
            <div>
              <span style="float: left;">{{item.name}} </span>
              <span style="float: right;">{{item.mobile}}</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="门店">
        <el-select
          v-model="queryParams.channelId"
          placeholder="可输入门店名称/手机号码搜索"
          clearable
          filterable
          size="small"
          style="width: 240px"
          @change="handleQuery"
        >
          <el-option
            v-for="item in merchantArr"
            :key="item.areaId"
            :label="item.areaName"
            :value="item.areaId"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="下单时间">
        <el-date-picker
          v-model="tradeTimeArr"
          type="datetimerange"
          size="small"
          value-format="timestamp"
          range-separator="至"
          start-placeholder="时间选择"
          end-placeholder="时间选择"
          @change="tardeTime"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="pageParams.pageNum = 1;handleQuery()"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="infor"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleOrderExport"
          v-hasPermi="['order:channel:export']"
          >导出订单</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <!-- 订单状态 -->
    <el-tabs type="card" v-model="state" @tab-click="handleClick">
      <el-tab-pane label="全部订单" name="null"></el-tab-pane>
      <el-tab-pane label="待付款" name="0"></el-tab-pane>
      <el-tab-pane label="待发货" name="1"></el-tab-pane>
      <el-tab-pane label="已发货" name="2"></el-tab-pane>
      <el-tab-pane label="已完成" name="3"></el-tab-pane>
      <el-tab-pane label="已取消" name="-1"></el-tab-pane>
    </el-tabs>
    <!-- 列表 -->
    <el-table ref="table" v-loading="loading" :data="list">
      <!-- 展开 -->
      <el-table-column type="expand">
        <template slot-scope="{ row }">
          <el-table :data="row.items">
            <el-table-column label="盲票组图片" min-width="80">
              <div slot-scope="{ row }">
                <el-image
                  style="width: 100px; height: 100px"
                  :src="row.picUrl"
                  :preview-src-list="[row.picUrl]"
                />
              </div>
            </el-table-column>
            <el-table-column label="盲票组名称" prop="title" min-width="80" />
            <el-table-column v-if="row.type && JSON.parse(row.type).value == 1 " label="采购单价(元/包)" min-width="100">
              <template slot-scope="{ row }">
                <div>{{ $numberFormat(row.pkgSalePrice) }}</div>
              </template>
            </el-table-column>
            <el-table-column v-else label="预付票售价(元/包)" min-width="100">
              <template slot-scope="{ row }">
                <div>{{ $numberFormat(row.pkgSalePrice) }}</div>
              </template>
            </el-table-column>
            <el-table-column label="数量" prop="orderNum" min-width="85">
              <template slot-scope="{ row }">
                <div>{{ row.orderNum }}包</div>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="订单号" prop="orderId" min-width="80" />
      <el-table-column label="订单类型" prop="orderId" min-width="80" align="center">
        <template slot-scope="{ row }">
          <div>
            <div v-if="row.type && JSON.parse(row.type).value == 1">普通票</div>
            <div v-if="row.type && JSON.parse(row.type).value == 2" style="color: red">线下预付票</div>
            <div v-if="row.type && JSON.parse(row.type).value == 3">线上预付票</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" min-width="100">
        <template slot-scope="{ row }">
          <div>
            {{ parseTime(row.createdTime) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="数量" prop="pkgNum" min-width="65">
        <template slot-scope="{ row }">
          <div>{{ row.pkgNum }}包</div>
        </template>
      </el-table-column>
      <el-table-column label="实付金额(元)" min-width="65">
        <template slot-scope="{ row }">
          <div>{{ $numberFormat(row.payAmt) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="门店" prop="channelName" min-width="80" />
      <el-table-column label="收货人/收货地址" prop="addr" min-width="120">
        <template slot-scope="{ row }">
          <div>
            {{
              `${row.receiver}，${row.tel}，${row.province}${row.city}${row.area}${row.address}`
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="上级渠道" prop="parentName" min-width="80" />
      <el-table-column label="订单状态" align="center">
        <template slot-scope="{ row }">
          <div>
            <el-tag :type="row.status.value === 1 ? 'success' : 'info'" v-if="row.status.value !== 2">{{
              row.status.desc
            }}</el-tag>
            <el-tag type="info" v-else>已发货</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="80">
        <template slot-scope="{ row }">
          <div>
            <el-button
              v-hasPermi="['order:channel:query']"
              type="text"
              @click="getDetail(row)"
            >查看详情</el-button>
            <el-button
              v-if="row.status.value === 1"
              type="text"
              @click="cancellationOrder(row)"
            >取消订单</el-button>
            <el-button
              v-if="row.status.value === 1"
              v-hasPermi="['order:channel:ship']"
              type="text"
              @click="toGoods(row)"
              >发货</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="pageParams.pageNum"
      :limit.sync="pageParams.pageSize"
      @pagination="getList"
    />

    <!-- 发货 -->
    <send-goods
      :send-show="goodsShow"
      :goods-info="goodsInfo"
      :channel-list="boxData"
      @close="close"
    />
  </div>
</template>
<script>
import { getOrderList, companyList, boxList, channelOrderExport, removeChannelOrder} from "@/api/business/order";
import { listAllSaleSite} from "@/api/admin/salesite";
import { publicFileGetUrl } from "@/api/common";
import SendGoods from "./components/SendGoods";
export default {
  name: "Channel",
  components: {
    SendGoods,
  },
  data() {
    return {
      loading: false,
      showSearch: true,
      // 筛选
      queryParams: {
        title: "",
        orderId: "",
        startTime: "",
        endTime: "",
        channelId: "",
        status: null,
      },
      // 分页
      pageParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 总条数
      total: 0,
      list: [],
      // 门店
      merchantArr: [],
      // 下单时间
      tradeTimeArr: [],
      // 订单列表状态
      state: "null",
      // 弹框显示
      goodsShow: false,
      // 订单详情
      goodsInfo: {},
      // 盲票组下拉列表
      boxData: [],
      siteList:[],
      siteCopyList:[],
      typeList: []
    };
  },
  mounted() {
    this.getSaleSiteList()
  },
  created() {
    this.getList();
    this.getTypeList()
  },
  methods: {
    // 订单列表
    getList() {
      this.loading = true;
      getOrderList(
        "pageNum=" +
          this.pageParams.pageNum +
          "&pageSize=" +
          this.pageParams.pageSize +
          "&",
        this.queryParams
      )
        .then((res) => {
          this.loading = false;
          if (res.code == 0) {
            res.rows.forEach((item) => {
              let items = item.items;
              items.forEach((item) => {
                let picUrlArr = item.picUrl.split(",");
                item.picUrl = publicFileGetUrl + picUrlArr[0];
              });
              item.status = JSON.parse(item.status);
            });
            this.total = res.total;
            this.list = res.rows;
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },

    //订单类型筛选列表
    getTypeList(){
      this.getDicts('channel_order_type').then(res=>{
        this.typeList = res.data
      })
    },

    // 盲票组列表
    getBoxList(row) {
      boxList({ orderId: row.orderId }).then((res) => {
        this.boxData = res.data;
      });
    },

    // 获取门店下拉列表
    getSaleSiteList(){
      listAllSaleSite({}).then(response => {
         this.siteList = response.data || [];
         this.siteCopyList = response.data || [];
      });
    },


    dataFilter(val) {
      if (val) { //val存在
        this.siteList = this.siteCopyList.filter((item) => {
          if (!!~item.mobile.indexOf(val) || !!~item.mobile.toUpperCase().indexOf(val.toUpperCase())
                 || !!~item.name.indexOf(val) || !!~item.name.indexOf(val)) {
             return true
          }
        })
      } else { //val为空时，还原数组
        this.siteList = this.siteCopyList;
      }
    },

    //搜索
    handleQuery() {
      this.siteList = this.siteCopyList;
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 重置
    resetQuery() {
      this.queryParams = {
        title: "",
        orderId: "",
        startTime: "",
        endTime: "",
        channelId: "",
        status: null,
      };
      this.state = "null"
      this.tradeTimeArr = [];
      this.getList();
    },

    // 选择下单时间
    tardeTime(e) {
      if (e) {
        this.queryParams.startTime = e[0];
        this.queryParams.endTime = e[1];
        this.pageParams.pageNum = 1
        this.handleQuery();
      } else {
        this.queryParams.startTime = "";
        this.queryParams.endTime = "";
        this.pageParams.pageNum = 1
        this.handleQuery();
      }
    },

    // 订单切换
    handleClick(e) {
      this.queryParams.status = Number(e.name);
      this.getList();
    },

    // 查看详情
    getDetail(row) {
      this.$router.push({ name: "ChannelDetail", query: { id: row.orderId } });
    },

    // 点击发货
    toGoods(row) {
      this.goodsShow = true;
      this.goodsInfo = row;
      this.getBoxList(row);
    },

    //取消订单
    cancellationOrder(row){
      this.$confirm('确定要取消订单吗？取消后实付金额将原路返回', '取消订单', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.vloading = this.$loading({
          lock: true,
          text: "正在取消订单.....",
          background: "rgba(0, 0, 0, 0.7)",
        });
        let data = {
          orderId:row.orderId
        }
        return  removeChannelOrder(data)
      }).then(()=>{
        this.vloading.close();
        this.getList()
        this.$message({
          type: 'success',
          message: '取消订单成功!'
        })
      }).catch(() => {
        this.vloading.close();
      });
    },

    // 关闭发货弹框
    close() {
      this.goodsShow = false;
      this.getList();
    },

    // 导出订单
    handleOrderExport() {
      this.$confirm("是否确认导出订单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.vloading = this.$loading({
            lock: true,
            text: "正在导出订单.....",
            background: "rgba(0, 0, 0, 0.7)",
          });
          return channelOrderExport(this.queryParams);
        })
        .then((response) => {
          this.vloading.close();
          this.download(response.msg);
        })
        .catch(() => {
          this.vloading.close();
        });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-tabs--border-card > .el-tabs__content {
  padding: 0;
}
.el-button {
  margin-left: 0;
}
</style>
