<template>
  <div class="app-container">
    <el-steps :active="stepActive" finish-status="success" align-center>
      <el-step v-if="!this.$route.query.mobile" title="选择代理" icon="el-icon-user-solid" />
      <el-step title="添加商品" icon="el-icon-s-goods" />
      <el-step title="添加物流" icon="el-icon-location" />
    </el-steps>
    <!-- 选择代理 -->
    <div v-show="stepActive === 0">
      <el-form label-width="80px" class="form">
        <el-form-item label="查询代理:">
          <el-select v-model="selectMemberTel" filterable placeholder="请输入代理手机号">
            <el-option v-for="item in crownList" :key="item.id" :label="item.name" :value="item.name.match(/\d{11}$/)[0]" />
          </el-select>
          <!-- <el-input v-model="selectMemberTel" placeholder="请输入代理手机号" maxlength="11" minlength="11" show-word-limit style="width: 300px" /> -->
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getGoodsList">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 选择商品 -->
    <div v-show="stepActive === 1">
      <el-form label-width="80px" class="form">
        <div style="display: flex">
          <el-form-item label="订单代理:" style="flex: 1">
            <el-input :value="memberInfo.nickname" disabled style="width: 205px;" />
            <el-input :value="memberInfo.mobile" disabled style="width: 205px;" />
            <el-input :value="levelStatus(memberInfo.level).name" disabled style="width: 205px;" />
          </el-form-item>
          <el-form-item label="选择商品:" style="flex: 1">
            <el-select v-model="selelcted.goodId" placeholder="选择商品" @change="handleSureGood">
              <el-option v-for="item in goodList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-input v-model="selelcted.num" type="number" placeholder="输入数量" min="1" style="width:200px" />
            <el-button type="primary" @click="handleAddCar">添加到购物车</el-button>
          </el-form-item>
        </div>
        <el-form-item label="购物车:">
          <div v-if="carArr.length > 0">
            <div v-for="(item, index) in carArr" :key="index" class="car">
              <div class="flex thumb_title">
                <el-image :src="item.main_img" fit="fill" class="thumb" />
                <p>{{ item.name }}</p>
                <p>单价: ￥{{ item.money }}</p>
                <p>数量: {{ item.num }}件</p>
                <p>小计: ￥{{ item.money * item.num }}</p>
                <i class="el-icon-delete carDelete" @click="handleCarDelete(index)" />
              </div>
            </div>
          </div>
          <p v-else style="margin:0">请选择商品并添加</p>
        </el-form-item>
        <el-form-item label="合计金额:">
          ￥ <span style="color:red; font-size: 24px;">{{ carArr.reduce((t, e) => t + e.num * e.money, 0) | toThousandFilter }}</span>
        </el-form-item>
        <el-form-item>
          <el-button v-if="!this.$route.query.mobile" @click="hanldeBackPrev">上一步</el-button>
          <el-button type="primary" @click="handleAddAddress">下一步</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 添加物流信息 -->
    <div v-show="stepActive >= 2">
      <el-form ref="orderInfo" :model="orderInfo" :rules="orderRules" label-width="80px" class="form" @validate="handleOrderValidate">
        <el-form-item>
          <el-radio-group v-model="radio" class="flex" style="display: flex;flex-direction: column">
            <el-radio v-for="(item, index) in addressList" :key="index" :label="item.id" style="margin: 24px 0">
              {{ item.con_name }}-{{ item.con_mobile }}-{{ item.provice }}-{{ item.city }}-{{ item.area }}-{{ item.address }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="dialogFormVisible = true">新增地址</el-button>
        </el-form-item>
        <el-form-item label="备注:" prop="remark">
          <el-input v-model="orderInfo.remark" type="textarea" placeholder="备注信息" maxlength="200" show-word-limit style="width: 500px" />
        </el-form-item>
        <el-form-item>
          <el-button @click="hanldeBackPrev">上一步</el-button>
          <el-button type="primary" @click="handleSubmitOrder">提交</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-dialog title="新增收货地址" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :destroy-on-close="true">
      <el-form :model="orderInfo">
        <el-form-item label="收货人:" prop="name">
          <el-input v-model="orderInfo.name" placeholder="收货人姓名" style="width: 500px" />
        </el-form-item>
        <el-form-item label="手机号:" prop="mobile">
          <el-input v-model="orderInfo.mobile" placeholder="手机号" minlength="11" maxlength="11" show-word-limit style="width: 500px" />
        </el-form-item>
        <el-form-item label="地区:">
          <VDistpicker @province="province => orderInfo.province = province.value" @city="city => orderInfo.city = city.value" @area="area => orderInfo.area = area.value" />
        </el-form-item>
        <el-form-item label="地址:" prop="address">
          <el-input v-model="orderInfo.address" type="textarea" placeholder="地址" maxlength="50" show-word-limit style="width: 500px" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAddress">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// api
import VDistpicker from 'v-distpicker'
import { getGoodsList } from '@/api/order/list'
import { getUserAddress, addUserAddress, confirmOrder, getCrown } from '@/api/order/common'
// 手机号验证
import { validateMobile } from '@/filters/validate'
// 代理等级
import { levelStatus } from '@/filters/common'

export default {
  components: { VDistpicker },
  data() {
    return {
      radio: '',
      stepActive: 0,
      dialogFormVisible: false,
      selectMemberTel: '',
      goodList: [],
      selelcted: {
        goodId: '',
        num: ''
      },
      crownList: [],
      selectGood: {},
      carArr: [],
      orderInfo: {
        name: '',
        mobile: '',
        province: '',
        city: '',
        area: '',
        address: '',
        remark: ''
      },
      addressList: [],
      orderRules: {
        name: [
          { required: true, message: '请输入收件人姓名', trigger: 'blur' }
        ],
        mobile: [
          { required: true, validator: validateMobile, trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入收件人地址', trigger: 'blur' }
        ]
      },
      memberInfo: {}
    }
  },
  watch: {
    stepActive(n) {
      if (n >= 2) {
        this.getAddress()
      }
    }
  },
  async mounted() {
    const { data: { list }} = await getCrown()
    this.crownList = list
    if (this.$route.query.mobile) {
      this.selectMemberTel = this.$route.query.mobile
      await this.getGoodsList()
      this.carArr = JSON.parse(sessionStorage.getItem('good'))
      this.carArr.forEach(e => {
        e.money /= e.num
      })
    }
  },
  methods: {
    // 获取地址
    getAddress() {
      this.$request(getUserAddress({ user_id: this.memberInfo.id }), ({ list }) => {
        this.addressList = list
      })
    },
    // 重置搜索状态
    reset() {
      this.goodList = []
      this.memberInfo = {}
      this.carArr = []
      this.selectGood = {}
      this.orderInfo.name = ''
      this.orderInfo.mobile = ''
      this.orderInfo.address = ''
      this.orderInfo.remark = ''
    },
    addAddress() { // 新增地址
      const { name, mobile, province, city, area, address } = this.orderInfo
      if (name && mobile && province && city && area && address) {
        this.$request(addUserAddress({ user_id: this.memberInfo.id, name, mobile, province, city, area, address }), data => {
          this.dialogFormVisible = false
          this.getAddress()
        })
      } else {
        this.$message.error('请输入完整地址')
      }
    },
    // 获取商品
    async getGoodsList() {
      if (!this.selectMemberTel) {
        this.$message.warning('请输入下单的代理手机号')
        return false
      }
      this.reset()
      const res = await getGoodsList({ mobile: this.selectMemberTel })
      try {
        const { message, code } = res
        if (code === 200) {
          const { data: { good, user }} = res
          good.forEach(e => {
            e.name += `-${e.size}`
          })
          this.goodList = good
          this.memberInfo = user
          this.stepActive += 1
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        let message = res.message ? res.message : e.message
        message = e.message ? e.message : '请求失败'
        this.$message.error(message)
      }
    },
    // 代理显示
    levelStatus(level) {
      return levelStatus(level)
    },
    // 确定选择的商品
    handleSureGood(id) {
      this.selelcted.num = ''
      this.selectGood = this.goodList.filter(item => {
        return item.id === id
      })[0]
    },
    // 添加到购物车
    handleAddCar() {
      if (!this.selelcted.goodId || !this.selelcted.num || this.selelcted.num === '0') {
        this.$message.warning('请选择并正确填写商品数量')
        return false
      }
      const index = this.carArr.findIndex(e => e.id === this.selelcted.goodId)
      if (index === -1) {
        this.carArr.push({ num: this.selelcted.num, ...this.goodList.find(e => e.id === this.selelcted.goodId) })
      } else {
        this.carArr[index].num = Number(this.carArr[index].num) + Number(this.selelcted.num)
      }
      this.selelcted.goodId = ''
      this.selelcted.num = ''
    },
    // 购物车显示sku
    skuShow(id, arr) {
      return arr.filter(item => {
        return item.sku_id === id
      })[0]
    },
    // 删除购物车
    handleCarDelete(index) {
      this.carArr.splice(index, 1)
    },
    // 填写物流信息
    handleAddAddress() {
      if (this.carArr.length < 1) {
        this.$message.warning('请先添加商品')
        return false
      }
      this.stepActive += 1
    },
    // 验证物流表单
    handleOrderValidate() {
      const { name, mobile, address } = this.orderInfo
      if (name && mobile && address) {
        this.stepActive += 1
      } else {
        this.stepActive = 2
      }
    },
    // 提交订单
    handleSubmitOrder() {
      if (this.radio) {
        this.addOrder({
          user_id: this.memberInfo.id,
          address_id: this.radio,
          money: this.carArr.reduce((t, e) => t + e.money * e.num, 0),
          num: this.carArr.map(e => e.num),
          remark: this.orderInfo.remark,
          size_id: this.carArr.map(e => e.id),
          total: this.carArr.reduce((t, e) => t + Number(e.num), 0),
          type: this.carArr.length
        })
      } else {
        this.$message.error('地址未选择')
      }
    },
    // 提交订单
    async addOrder(data) {
      this.$request(confirmOrder(data), data => {
        this.$message.success('代下单成功')
        this.$event.$emit('REFRESHTAG', this.$store.state.tagsView.visitedViews.find(e => e.title === '代下单'))
      })
    },
    // 返回上一步
    hanldeBackPrev() {
      this.stepActive--
    }
  }
}
</script>
<style lang="scss" scoped>
  .form{
    padding: 30px 0;
    .el-select {
      width: 360px;
    }
  }
  .car {
    width: 98%;
    &:nth-last-of-type(1){
      border: none
    }
    .thumb{
      display: block;
      width: 40px;
      height: 40px;
    }
    .good{
      display: flex;
      justify-content: space-around;
      flex-direction: column;
      width: 100%;
      padding: 15px 0;
      border-bottom: 1px solid #ccc;
      position: relative;
      &:nth-last-of-type(1){
        border: none
      }
      p{
        margin: 0;
        line-height: 1 !important;
      }
    }
    .thumb_title{
      width: 100%;
      border-bottom: 1px solid #ccc;
    }
    .flex{
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
</style>
