<template>
  <div class="admin-refresh">
    <div class="section-search">
      <el-form ref="searchFrom" :model="searchFrom" label-width="100px" inline size="small">
        <el-form-item>
          <el-input v-model="searchFrom.user_id" style="width: 100px" placeholder="用户ID"></el-input>
        </el-form-item>
        <!-- <el-form-item label="发货状态">
            <el-select filterable v-model="searchFrom.type" placeholder="请选择"  clearable>
              <el-option
                v-for="(data,index) in logisticsType"
                :key="index"
                :label="data.name"
                :value="data.value">
              </el-option>
            </el-select>
        </el-form-item>-->
        <el-form-item>
          <el-cascader
            placeholder="请选择期数"
            :popper-class="'refresh-cascader-multi width-480'"
            style="width: 480px"
            :options="goodsList"
            :props="{value:'id',label:'name'}"
            @active-item-change="handleItemChange"
            @change="changePeriods"
            filterable
            v-model="selectedGoods"></el-cascader>
        </el-form-item>
        <el-form-item>
          <el-select filterable v-model="searchFrom.theme_id" placeholder="请选择主题" clearable>
            <el-option
              v-for="(data,index) in themeList"
              :key="index"
              :label="data.name"
              :value="data.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="期数id">
          <el-input v-model="searchFrom.periods_id" style="width: 120px"></el-input>
        </el-form-item>-->
        <el-form-item>
          <div class="search-btn-wrapper">
            <el-button type="primary" plain @click="getList">搜索</el-button>
            <el-button type="success" plain @click="reset">重置</el-button>
            <el-button v-if="!$store.state.readonly" type="primary" plain @click="downLoad()">excel模板下载</el-button>
            <el-button type="primary" plain @click="exportTable" v-if="$store.state.export">导出当前待发货</el-button>
            <el-button type="primary" plain @click="exportReceiveInfoTable">按期数导出收货信息</el-button>
            <el-upload
              style="margin-left: 10px;"
              v-if="$store.state.import"
              :show-file-list="false"
              :onSuccess="fileSuccess"
              :headers="uploadHeader"
              :data="{param_token:param_token}"
              action="/api/admin/order/deliver/list/import">
              <el-button type="success" plain>导入发货信息</el-button>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <el-tabs v-model="searchFrom.type" type="card" @tab-click="handleClick" style="padding-top: 10px;background-color: #fff">
      <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-tabs>

    <el-table :data="deliverList" size="mini" style="width: 100%">
      <el-table-column width="200" class="f-c" label="用户">
        <template slot-scope="scope">
          <img style="vertical-align: top" class="avatar" :src="scope.row.user_avatar" />
          <span style="display: inline-block;">
            {{scope.row.user_nickname}}
            <br />
            (ID:{{scope.row.user_id}})
            <br />
            手机：{{scope.row.user_mobile}}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="收货地址">
        <template slot-scope="scope">
          {{scope.row.receive_name}}
          <br/>
          {{scope.row.receive_mobile}}
          <br/>
          {{scope.row.province_name}}{{scope.row.city_name}}{{scope.row.area_name}}{{scope.row.address}}
        </template>
      </el-table-column>
      <!--<el-table-column prop="periods_title" label="期数名称"></el-table-column>-->
      <el-table-column prop="periods_title" label="期数名称">
        <template slot-scope="scope">
          <div v-html="periodName(scope.row)"></div>
          <!--{{periodName(scope.row)}}-->
        </template>
      </el-table-column>
      <el-table-column prop="theme_name" label="主题"></el-table-column>
      <el-table-column prop="deliver_start_at" label="预计发货开始时间" width="100px"></el-table-column>
      <el-table-column prop="deliver_end_at" label="预计发货结束时间" width="100px"></el-table-column>
      <el-table-column prop="deliver_at" label="发货时间" width="100px"></el-table-column>
      <el-table-column prop="status" label="物流状态">
        <template slot-scope="scope">
          {{scope.row.status|LogisticsStatusFil}}<br/>
          <span v-if="searchFrom.type==2">
            名称:{{scope.row.express_name}}<br/>
            单号:{{scope.row.express_no}}
          </span>
        </template>
      </el-table-column>
      <el-table-column width="150" label="操作" v-if="!$store.state.readonly" fixed="right">
        <template slot-scope="scope">
          <el-button @click="editAddress(scope.row)" plain type="info" size="mini">编辑收货地址</el-button>
        </template>
      </el-table-column>
    </el-table>
    <page :nowPage="nowPage" :total="total" @pageChange="onPageChange" @sizeChange="onSizeChange" />
    <address-dialog :dialogObj="dialogObj" @reflash="onUpdateAddress"></address-dialog>
    <receiveInfoDialog
      :goodsList="goodsList"
      :showFlag="showFlag"
      :cancelEvent="cancelEvent"
      :sureEvent="sureEvent"
    />
  </div>
</template>

<script>
import page from "../framework/page";
import md5 from "js-md5";
import addressDialog from "./dialog";
import receiveInfoDialog from "./receiveInfoDialog";
import Cookie from '../../util/cookie'
import CommonJs from '../../util/common';
import {
  getDeliverListApi,
  getPeriodsApi,
  getGoodsListApi,
  getDefaultPeriodsApi,
  exportExcelApi,
  getThemeListApi
} from "../../service/api";
import { LogisticsStatus, GOODSTYPE } from "../../util/wordbook";

export default {
  name: "index",
  components: {
    page,
    addressDialog,
    receiveInfoDialog
  },
  data() {
    let singjson = {
      sing: "singsingenglish21000"
    };
    return {
      dialogObj: {
        show: false
      },
      showFlag: false,
      adressDialog: false,
      searchFrom: {
        user_id: "",
        theme_id: "",
        periods_id: "",
        type: ""
      },
      nowPage: 1,
      total: 0,
      limit: 10,
      deliverList: [],
      selectedGoods: [],
      secGoods: [],
      periodsId: null,
      goods_id: null,
      goodsList: [],
      themeList: [],
      uploadHeader:{token:Cookie.get('cc_token')},
      param_token:CommonJs.md5Code(),
      logisticsType: [
        { value: "0", name: "当前待发货 " },
        { value: "1", name: "所有待发货 " },
        { value: "2", name: "所有已发货 " }
      ]
    };
  },
  filters: {
    LogisticsStatusFil(val) {
      return LogisticsStatus[val];
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    periodName(val) {
      let str = '';
      if (val.goods_id) {
        str += `【${val.goods_id}】`
      }
      if (val.periods_title) {
        str += `${val.periods_title}<br>`
      } else {
        str += `<br>`
      }
      if (val.watch_num) {
        str += `${val.watch_num}课时`
      }
      if (val.start_at) {
        str += `（${val.start_at.slice(5).replace('-', '')}）`
      }
      if (val.has_watch_num || val.has_watch_num == 0) {
        str += `-d${val.has_watch_num}`
      }
      return str
    },
    cancelEvent() {
      this.showFlag = false;
    },
    sureEvent() {
      this.showFlag = false;
    },
    exportReceiveInfoTable() {
      this.showFlag = true;
    },
    downLoad() {
      window.open("/static/待发货模板.xls");
    },
    handleClick(tab) {
      this.searchFrom.type = tab.name;
      this.getList();
    },
    editAddress(row) {
      // this.dialogObj={show:true}
      console.log(row);
      // if (!row || !row.province_name) {
      //   this.dialogObj.province = "";
      //   this.dialogObj.city = "";
      //   this.dialogObj.district = "";
      // } else {
      //   this.dialogObj.province = "";
      //     this.dialogObj.district = "";
      //     this.dialogObj.city = "";
      // }
      this.dialogObj.detail = row.address;
      this.dialogObj.receive_mobile = row.receive_mobile;
      this.dialogObj.receive_name = row.receive_name;
      this.dialogObj.province_name = "";
      this.dialogObj.city_name = "";
      this.dialogObj.district_name = "";
      this.dialogObj.id = row.id;
      this.dialogObj.show = true;
    },
    onUpdateAddress() {
      this.dialogObj.show = false;
      this.getList();
    },
    fileSuccess() {
      this.$message({
        message: "提交成功，请稍后刷新",
        type: "success"
      });
      this.getList();
    },
    init() {
      this.getList();
      let json = {
        page: 1,
        limit: 100,
        goods_type: "1,2"
      };
      getThemeListApi({ page: 1, limit: 100 }).then(res => {
        this.themeList = res.list;
      });
      getGoodsListApi(json).then(res => {
        console.log(res);
        res.list.forEach(i => {
          i.name =
            "[" +
            i.id +
            "]" +
            "[" +
            GOODSTYPE[i.goods_type] +
            "]" +
            "[" +
            i.current_price / 100 +
            "元]" +
            i.name;
          i.children = [];
        });
        this.goodsList = res.list;
        // this.initQuery();
      });
    },
    exportTable() {
      let json = {};
      if (this.searchFrom.user_id) {
        json.user_id = this.searchFrom.user_id;
      }
      if (this.searchFrom.theme_id) {
        json.theme_id = this.searchFrom.theme_id;
      }
      if (this.searchFrom.periods_id) {
        json.periods_id = this.searchFrom.periods_id;
      }
      exportExcelApi("/api/admin/order/deliver/list/export", json,'待发货列表');
    },
    initQuery() {
      let _query = this.$route.query;
      if (_query && _query.goods_id && _query.periods_id) {
        this.goods_id = _query.goods_id;
        this.selectedGoods = [
          parseInt(_query.goods_id),
          parseInt(_query.periods_id)
        ];
        getPeriodsApi({ goods_id: this.selectedGoods[0], limit: 100 }).then(
          res => {
            res.list.forEach(i => {
              i.name = i.title;
            });
            this.goodsList.find(i => {
              return i.id === this.selectedGoods[0];
            }).children = res.list;
            let nowGoods = this.goodsList.find(i => {
              return i.id === this.selectedGoods[0];
            });
            this.periods = nowGoods.children.find(i => {
              return i.id === this.selectedGoods[1];
            });
            console.log(this.periods);
          }
        );
      } else {
        getDefaultPeriodsApi().then(res => {
          console.log(res);
          //
          if (res) {
            this.goods_id = res.goods_id;
            this.selectedGoods = [parseInt(res.goods_id), parseInt(res.id)];
            getPeriodsApi({ goods_id: this.selectedGoods[0], limit: 100 }).then(
              res => {
                res.list.forEach(i => {
                  i.name = i.title;
                });
                this.goodsList.find(i => {
                  return i.id === this.selectedGoods[0];
                }).children = res.list;
                let nowGoods = this.goodsList.find(i => {
                  return i.id === this.selectedGoods[0];
                });
                this.periods = nowGoods.children.find(i => {
                  return i.id === this.selectedGoods[1];
                });
                this.teacher_id = "";
                console.log(this.periods);
                // this.getClassList()
              }
            );
          }
        });
      }
      console.log(this.goodsList);
    },
    onPageChange(val) {
      // console.log(val)
      this.nowPage = val;
      this.getList();
    },
    onSizeChange(val) {
      this.limit = val;
      this.nowPage = 1;
      this.getList();
    },
    getList() {
      let json = {
        limit: this.limit,
        page: this.nowPage
      };
      if (this.searchFrom.user_id) {
        json.user_id = this.searchFrom.user_id;
      }
      if (this.searchFrom.theme_id) {
        json.theme_id = this.searchFrom.theme_id;
      }
      if (this.searchFrom.periods_id) {
        json.periods_id = this.searchFrom.periods_id;
      }
      if (this.searchFrom.type) {
        json.type = this.searchFrom.type;
      }

      getDeliverListApi(json).then(res => {
        this.deliverList = res.list;
        this.total = res.total;
        console.log(this.deliverList);
      });
    },
    reset() {
      this.searchFrom = {
        user_id: "",
        theme_id: "",
        periods_id: "",
        type: ""
      };
      this.getList();
    },
    changePeriods(data) {
      if (data.length > 1) {
        this.goods_id = data[0];
        let nowGoods = this.goodsList.find(i => {
          return i.id === data[0];
        });
        this.periods = nowGoods.children.find(i => {
          return i.id === data[1];
        });
        console.log(this.goodsList);
        console.log(this.periods);
        this.searchFrom.periods_id = this.periods.id;
        // debugger
      }
    },
    handleItemChange(val) {
      getPeriodsApi({ goods_id: val[0], limit: 100 }).then(res => {
        res.list.forEach(i => {
          i.name = i.title;
        });
        this.goodsList.find(i => {
          return i.id === val[0];
        }).children = res.list;
      });
    }
  }
};
</script>

<style scoped>
.sms {
  padding: 20px 0;
}
.avatar {
  width: 50px;
  min-width: 50px;
  margin-right: 10px;
  height: 50px;
  border-radius: 50%;
}
</style>
<style>
.userInfo > div {
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-start;
  align-items: center;
}
.f-c > .cell {
  display: flex !important;
  flex-flow: row;
  justify-content: flex-start;
  align-items: center;
}
</style>
