<template>
  <div style="padding: 0 20px">
    <div ref="lxHeader">
      <lx-header icon="md-apps" text="订单管理" style="margin-bottom: 10px; border: 0px; margin-top: 15px">
        <slot>
          <div style="display: flex">
            <Input v-model="select.keyword" class="select" style="width: 200px; margin-right: 10px"
              placeholder="关键字搜索" />
            <Button class="select" type="primary" style="margin-right: 10px;" @click="searchOrder">查询</Button>
            <xy-selectors @search="searchOrder" @reset="resetsearch">
              <template>
                <el-row>
                  <el-col :span="12">
                    <div class="select-content-item">
                      <div class="select-content-item-label">所属商户</div>
                      <div>
                        <el-autocomplete @select="handleSelect" v-model="select.merchant.name"
                          :fetch-suggestions="querySearchAsync" clearable placeholder="请输入选择商家"></el-autocomplete>

                        <el-checkbox style="margin-left: 10px;" v-model="select.is_merchant">包含历史服务商家</el-checkbox>
                      </div>
                    </div>
                  </el-col>

                  <el-col :span="12">
                    <div class="select-content-item">
                      <div class="select-content-item-label">产品类别</div>
                      <div>
                        <el-cascader ref="cascader" :value="select.productTypeName" clearable :show-all-levels="false"
                          size="small" :options="productTypes" :props="{checkStrictly:true,label:'name',value:'id'}"
                          @change="productTypeChange"></el-cascader>
                      </div>
                      <el-checkbox style="margin-left: 10px;" v-model="select.order_paid">待支付</el-checkbox>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div class="select-content-item">
                      <div class="select-content-item-label">订单状态</div>
                      <div>
                        <template v-for="(value,key) of orderStates">
                          <!-- <el-tag size="small" v-if="key!='unpaid'" -->
                          <el-tag size="small"
                            :effect="select.orderStates.key === key ? 'dark' : 'plain'"
                            @click="select.orderStates = {key,value}" style="margin-right: 6px;">{{value}}</el-tag>
                        </template>
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div class="select-content-item">
                      <div class="select-content-item-label">下单日期</div>
                      <div>
                        <el-date-picker @change="changeCreatedDate" v-model="select.createdDate" type="daterange"
                          :picker-options="pickerOptions" value-format="yyyy-MM-dd" range-separator="至"
                          start-placeholder="开始日期" end-placeholder="结束日期" align="right">
                        </el-date-picker>
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div class="select-content-item">
                      <div class="select-content-item-label">更新日期</div>
                      <div>
                        <el-date-picker @change="changeUpdateDate" v-model="select.updateDate" type="daterange"
                          :picker-options="pickerOptions" value-format="yyyy-MM-dd" range-separator="至"
                          start-placeholder="开始日期" end-placeholder="结束日期" align="right">
                        </el-date-picker>
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div class="select-content-item">
                      <div class="select-content-item-label">支付日期</div>
                      <div>
                        <el-date-picker @change="changePayDate" v-model="select.payDate" type="daterange"
                          :picker-options="pickerOptions" value-format="yyyy-MM-dd" range-separator="至"
                          start-placeholder="开始日期" end-placeholder="结束日期" align="right">
                        </el-date-picker>
                      </div>
                    </div>
                  </el-col>
                </el-row>


              </template>
              <template v-slot:selected>
                <div style="display: flex;padding: 0 0 10px 20px;">
                  <span style="padding-right: 6px">当前搜索条件：</span>
                  <div v-if="select.keyword">
                    <el-tag effect="light" size="small" closable @close="select.keyword = ''">
                      {{select.keyword}}
                    </el-tag>,
                  </div>
                  <div v-if="select.productType">
                    <el-tag effect="light" size="small" closable @close="select.productType = ''">
                      {{select.productTypeName}}
                    </el-tag>,
                  </div>
                  <div v-if="select.merchant">
                    <el-tag effect="light" size="small" closable @close="select.merchant = ''">
                      {{select.merchant.name}}
                    </el-tag>,
                  </div>
                  <div v-if="select.orderStates">
                    <el-tag effect="light" size="small" closable @close="select.orderStates = ''">
                      {{select.orderStates.value}}
                    </el-tag>
                  </div>
                </div>
              </template>
            </xy-selectors>
            <Button class="select" type="primary" style="margin-right: 10px;" @click="downloadExel">导出</Button>
          </div>
        </slot>
      </lx-header>
    </div>

    <xy-table :list="list" :table-item="table" :total="total" @pageSizeChange="e => {select.pageSize = e;searchOrder()}"
      @pageIndexChange="pageChange">
      <template v-slot:btns>
        <el-table-column fixed="right" label="操作" width="400" header-align="center">
          <template slot-scope="scope">
            <actions :row="scope.row" @log="showLog(scope.row)" @refresh="getOrders"></actions>
            <!--            <Button icon="ios-chatbubbles-outline" type="primary" style="margin-left: 10px;margin-bottom: 6px;" size="small" ghost>跟进</Button>-->
            <!--            <Button v-show="scope.row.state_name == '待处理'" icon="ios-paper-plane-outline" type="primary" style="margin-left: 10px;margin-bottom: 6px;" size="small" ghost>分发</Button>-->
            <!--            <Button v-show="scope.row.state_name == '待处理'" icon="ios-close" type="primary" style="margin-left: 10px;margin-bottom: 6px;" size="small" ghost>取消</Button>-->
            <!--            <Button v-show="scope.row.state_name == '已发布'" icon="ios-redo" type="primary" style="margin-left: 10px;margin-bottom: 6px;" size="small" ghost>收回</Button>-->
            <!--            <Button icon="ios-clipboard-outline" type="primary" style="margin-left: 10px;margin-bottom: 6px;" size="small" ghost @click="selectId = scope.row.id,isShowLog = true">日志</Button>-->
          </template>
        </el-table-column>
      </template>
    </xy-table>

    <orderLog :id="selectId" :is-show.sync="isShowLog" @refresh="getOrders"></orderLog>
    <orderEdit :id="selectId" :is-show.sync="isShowEdit" @refresh="getOrders"></orderEdit>
  </div>
</template>

<script>
  import {
    getList,
    index as getTypes
  } from "@/api/order"
  import {
    parseTime
  } from "@/utils"
  import {
    download
  } from '@/utils/downloadRequest'
  import {
    index as merchantIndex
  } from '@/api/merchant'

  import orderLog from '@/views/order/component/orderLog'
  import actions from '@/views/order/component/actions'
  import orderEdit from '@/views/order/component/orderEdit'

  export default {
    components: {
      orderLog,
      actions,
      orderEdit
    },
    data() {
      return {
        selectId: null,
        isShowLog: false,
        isShowEdit: false,
        memberId:"",
        merchants: [],
        orderItemStates: [],
        orderStates: [],
        productTypes: [],
        select: {
          page: 1,
          pageSize: 10,
          merchant: {
            name: "",
            id: ""
          },
          keyword: '',
          productType: '',
          orderStates: '',
          productTypeName: "",
          is_merchant: false,
          createdDate: [],
          payDate: [],
          updateDate: [],
          start_created: "",
          end_created: "",
          start_paid: "",
          end_paid: "",
          start_updated: "",
          end_updated: "",
          order_paid: false,
          order_item_id:""
        },
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },

        total: 0,
        list: [],
        table: [{
            prop: "order.serial",
            label: "订单编号",
            width: 150,
            align: 'center',
            fixed: 'left'
          },
          {
            prop: "order_name",
            label: "订单名称",
            width: 220,
            align: 'left'
          },
          {
            prop: 'bookable_name',
            label: "订购类型",
            width: 80
          },
          {
            prop: "order_total",
            label: "金额",
            width: 80,
            align: 'right'
          },
          {
            prop: "created_at",
            label: "下单时间",
            width: 180,
            formatter: (cell, data, value, index) => {
              return parseTime(new Date(value))
            }
          },
          {
            prop: "order.paid_at",
            label: "支付时间",
            width: 180,
            formatter: (cell, data, value, index) => {
              if (value)
                return parseTime(new Date(value))
            }
          },
          {
            prop: "updated_at",
            label: "更新时间",
            width: 180,
            formatter: (cell, data, value, index) => {
              return parseTime(new Date(value))
            }
          },
          {
            prop: "memberPromotion.name",
            label: "推广渠道",
            width: 110
          },
          {
            label: "客户服务地址",
            width: 220,
            align: "left",
            prop:'customAddress',
            customFn: (row) => {
              return ( <div style = {
                  {
                    display: 'flex',
                    alignItems: 'left',
                    justifyContent: 'left',
                    cursor: 'pointer',
                    color: "blue"
                  }
                }
                on = {
                  {
                    ['click']: (e) => {
                      this.selectId = row.order.id;
                      this.isShowEdit = true;
                    }
                  }
                }>
                {
                  row.order.member_address ? row.order.member_address : "修改服务地址"
                } </div> )
              }
            },
                {
                  prop: "member.name",
                  label: "姓名",
                  width: 110
                },
                {
                  prop: "member.wechat_nickname",
                  label: "微信昵称",
                  width: 110
                },
                {
                  label: "头像",
                  prop:'member.avatar',
                  width: 80,
                  customFn: (row) => {
                    return ( < div style = {
                      {
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center'
                      }
                    } > <el-avatar src = {
                      row.member?.avatar
                    } > </el-avatar></div > )
                  }
                },

                {
                  prop: "member.phone",
                  label: "联系电话",
                  width: 120
                },
                {
                  prop: "member.area",
                  label: "区域",
                  width: 110
                },
                {
                  prop: "member.due_date",
                  label: "预产期",
                  width: 120
                },
                {
                      prop: "product_type.name",
                      label: "产品类型",
                      width: 100
                    },
                    {
                      prop: "merchant.username",
                      label: "服务商家",
                      align: "left",
                      width: 160
                    },
                    {
                      label: "历史商家",
                      width: 160,
                      align: "left",
                      customFn: (row) => {
                        return row.assign_merchant.map(item => {
                            return ( <div> {
                                item.username
                              } </div>)
                        })
                      }
                    },
                    {
                      prop: "state_name",
                      label: "状态",
                      width: 120
                    },
            // {
            //   label: "用户信息",
            //   prop: 'member',
            //   multiHd: [{
            //       prop: "name",
            //       label: "姓名",
            //       width: 110,
            //       customFn: (row) => {
            //         return (row.row.member?.name)
            //       }
            //     },
            //     {
            //       prop: "wechat_nickname",
            //       label: "微信昵称",
            //       width: 110,
            //       customFn: (row) => {
            //         return (row.row.member?.wechat_nickname)
            //       }
            //     },
            //     {
            //       label: "头像",
            //       width: 80,
            //       customFn: (row) => {
            //         return ( < div style = {
            //           {
            //             display: 'flex',
            //             alignItems: 'center',
            //             justifyContent: 'center'
            //           }
            //         } > <el-avatar src = {
            //           row.row.member?.avatar
            //         } > </el-avatar></div > )
            //       }
            //     },

            //     {
            //       prop: "phone",
            //       label: "联系电话",
            //       width: 120,
            //       customFn: (row) => {
            //         return (row.row.member?.phone)
            //       }
            //     },
            //     {
            //       prop: "area",
            //       label: "区域",
            //       width: 110,
            //       customFn: (row) => {
            //         return (row.row.member?.area)
            //       }
            //     },
            //     {
            //       prop: "due_date",
            //       label: "预产期",
            //       width: 120,
            //       customFn: (row) => {
            //         return (row.row.member?.due_date)
            //       }
            //     }
            //   ],
            // },
            // {
            //   label: '订单明细',
            //   prop:'orderInfo',
            //   multiHd: [{
            //       prop: "product_type.name",
            //       label: "产品类型",
            //       width: 100
            //     },
            //     {
            //       prop: "merchant.username",
            //       label: "服务商家",
            //       align: "left",
            //       width: 160
            //     },
            //     {
            //       label: "历史商家",
            //       width: 160,
            //       align: "left",
            //       customFn: (row) => {
            //         return row.row.assign_merchant.map(item => {
            //             return ( <div> {
            //                 item.username
            //               } </div>)
            //         })
            //       }
            //     },
            //     {
            //       prop: "state_name",
            //       label: "状态",
            //       width: 120
            //     }
            //   ]
            // },

            {
              prop: "order.member_comment",
              label: "备注",
              align: "left",
              minWidth: 320
            }
          ],
        }
      },
        methods: {
          handleSelect(item) {
            console.log(item)
            this.select.merchant = {
              id: item.id,
              name: item.value
            };
          },
          querySearchAsync(queryString, cb) {
            merchantIndex({
              keyword: queryString,
              page_size: 999
            }).then(res => {
              var data = res.data;
              let _data = [];
              for (var m of data) {
                _data.push({
                  value: m.username,
                  id: m.id
                })
              }
              cb(_data)
            })
          },
          resetsearch() {
            this.select.page = 1;
            this.select.merchant = '';
            this.select.keyword = '';
            this.select.productType = '';
            this.select.orderStates = '';
            this.select.productTypeName = '';
            this.select.is_merchant = false;
            this.select.createdDate = [];
            this.select.payDate = [];
            this.select.updateDate = [];
            this.select.start_created = "";
            this.select.end_created = '';
            this.select.start_paid = '';
            this.select.end_paid = '';
            this.select.start_updated = '';
            this.select.end_updated = '';
            this.select.order_item_id=""
            this.getOrders();
          },
          changeUpdateDate(e) {
            if(e){
              this.select.start_updated = e[0]+' 00:00:00';
              this.select.end_updated = e[1]+' 23:59:59';
            }else{
              this.select.start_updated = ""
              this.select.start_updated = ""
            }
          },
          changePayDate(e) {
            if(e){
              this.select.start_paid = e[0]+' 00:00:00';
              this.select.end_paid = e[1]+' 23:59:59';
            }else{
              this.select.start_paid = "";
              this.select.end_paid = "";
            }

          },
          changeCreatedDate(e) {
            console.log("date",e)
            if(e){
              this.select.start_created = e[0]+' 00:00:00';
              this.select.end_created = e[1]+' 23:59:59';
            }else{
              this.select.start_created = '';
              this.select.end_created = '';
            }

          },
          productTypeChange(e) {
            this.select.productType = this.$refs['cascader'].getCheckedNodes()[0].data.id;
            this.select.productTypeName = this.$refs['cascader'].getCheckedNodes()[0].data.name;
          },
          searchOrder() {
            this.memberId = ""
            this.select.page = 1
            this.getOrders()
          },
          pageChange(e) {
            this.select.page = e
            this.getOrders()
          },

          async getTypes() {
            const res = await getTypes()
            this.merchants = res.merchants
            this.orderItemStates = res.order_item_states
            this.orderStates = res.order_item_states
            this.productTypes = res.product_types
          },

          async getOrders() {
            let is_merchant = this.select.is_merchant
            this.select.is_merchant = is_merchant ? 1 : 0;

            let order_paid = this.select.order_paid
            this.select.order_paid = order_paid ? 1 : '';

            const res = await getList({
              page_size: this.select.pageSize,
              product_type_id: this.select.productType,
              merchant_id: this.select.merchant.id,
              order_state: this.select.orderStates.key,
              member_id:this.memberId,
              sort_name:'paid_at',
              sort_type:'DESC',
              ...this.select
            })
            this.select.is_merchant = is_merchant;
            this.select.order_paid = order_paid;
            this.select.order_item_id=""
            this.total = res.total
            this.list = res.rows
          },

          showLog(row) {
            this.selectId = row.id
            this.isShowLog = true
          },

          downloadExel() {


            let is_merchant = this.select.is_merchant
            this.select.is_merchant = is_merchant ? 1 : 0;

            let order_paid = this.select.order_paid
            this.select.order_paid = order_paid ? 1 : '';
            download(
              '/api/admin/order/get-list',
              'get', {
                order_state: this.select.orderStates.key,
                keyword: this.select.keyword,
                product_type_id: this.select.productType,
                merchant_id: this.select.merchant.id,
                is_export: 1,
                member_id:this.memberId,
                ...this.select
              },
              '订单列表.xlsx')


            this.select.is_merchant = is_merchant;
            this.select.order_paid = order_paid;
          }
        },
        mounted() {
          this.memberId = this.$route.query.user_id
          this.select.order_item_id = this.$route.query.order_item_id?this.$route.query.order_item_id:""
          this.getTypes()
          this.getOrders()
        }

      }
</script>

<style scoped lang="scss">
  .select-content-item {
    display: flex;
    align-items: center;

    margin-bottom: 10px;

    &-label {


      padding: 0 20px;
    }
  }

  $primaryColor: #bf617c;

  ::v-deep .ivu-alert-success {
    color: #fff;
    border-color: $primaryColor !important;
    background: rgba(213, 120, 145, 0.8) !important;

    margin: auto 0;
    margin-right: 10px;
  }

  ::v-deep .ivu-icon-ios-close:before {
    //color: #fff;
  }
</style>
