<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-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.mobile.match(/\d{11}/)" />
          </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 label-width="120">
        <el-form-item label="是否添加赠品:">
          <el-switch
            v-model="isGift"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item v-if="isGift" label="活动赠品:">
          <el-select v-model="activity_id" style="width: 400px">
            <el-option v-for="item in activitys" :key="item.id" :label="item.title" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-if="!this.$route.query.mobile" @click="hanldeBackPrev">上一步</el-button>
          <el-button type="primary" @click="handleAddGift">下一步</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 }}
              <span v-if="item.belong_user" style="color: red">(所属-{{ `昵称:${item.belong_user.nickname}, 真实姓名:${item.belong_user.realname}, 手机号:${item.belong_user.mobile}` }})</span>
            </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" label-width="80px">
        <el-form-item>
          <el-input v-model="message" type="textarea" :placeholder="placeholder" :rows="5" show-word-limit style="width: 500px" /><br>
          <div style="width: 500px;display: flex;justify-content: flex-end;margin-top:10px">
            <el-button type="danger" size="mini" @click="message = ''">清 除</el-button>
            <el-button type="primary" size="mini" @click="text">识 别</el-button>
          </div>
        </el-form-item>
        <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="手机号" :rows="4" maxlength="11" show-word-limit style="width: 500px" />
        </el-form-item>
        <el-form-item label="地区:">
          <el-cascader
            v-model="orderInfo.areaAll"
            :options="provinces"
            style="width: 500px"
          />
          <!-- <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" :rows="4" 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>
    <!-- 订单所属 -->
    <el-dialog
      title="绑定订单所属"
      :visible.sync="dialog.belong"
      :show-close="false"
      :close-on-click-modal="false"
      class="dialog_address"
    >
      <div style="padding: 20px;padding-top: 0;">
        <el-input
          v-model="belongUserParams.search_name"
          type="text"
          style="width: 300px"
          placeholder="所属者 昵称 / 手机号"
        />
        <el-button type="primary" @click="getBelongList">搜索</el-button>
      </div>
      <div class="address_list">
        <el-radio-group v-model="belongId">
          <el-radio v-for="item in belongUserList" :key="item.id" :label="item.id" class="radio_item">
            <div>
              <span>{{ item.nickname }},{{ item.mobile }},{{ levelStatus(item.level).name }}</span>
            </div>
          </el-radio>
        </el-radio-group>
      </div>
      <div class="belongPagination">
        <pagination
          :total="belongUserTotal"
          :limit="belongUserParams.page_size"
          :page="belongUserParams.page_index"
          @pagination="changeBelongPagination"
          @update:limit="changeBelongPagination"
        />
        <div class="btn_main">
          <el-button @click="resetBelong">取消</el-button>
          <el-button type="primary" @click="toPublishBindBelong">确定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// api
// import VDistpicker from 'v-distpicker'
import { getGoodsList } from '@/api/order/list'
import { getUserAddress, addUserAddress, confirmOrder, getCrown, getBelongByUser, publishBindBelong, discernAdress } from '@/api/order/common'
// 手机号验证
import { validateMobile } from '@/filters/validate'
// 代理等级
import { levelStatus } from '@/filters/common'
import { activityList } from '@/api/giftB'
// import { regionData } from 'element-china-area-data'
import provinces from '@/assets/json/area'
import { eachReplaceKey } from '@/utils/city'
import AddressParse from 'address-parse'
export default {
  // components: { VDistpicker },
  data() {
    return {
      radio: '',
      message: '',
      placeholder: '请粘贴或输入整段地址，点击“识别”自动拆分姓名、电话和地址。例如：张三，15100001111，河南省郑州市金水区某路和某路交叉口某小区某号楼',
      stepActive: 0,
      dialogFormVisible: false,
      // provinces: provinces,
      provinces: provinces,
      dialog: {
        belong: false
      },
      selectMemberTel: '',
      goodList: [],
      selelcted: {
        goodId: '',
        num: ''
      },
      crownList: [],
      selectGood: {},
      carArr: [],
      orderInfo: {
        name: '',
        mobile: '',
        areaAll: '',
        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: {},
      isGift: false,
      activitys: [],
      activity_id: '',
      belongUserParams: {
        page_index: 1,
        page_size: 10,
        search_name: ''
      },
      belongUserList: [],
      belongUserTotal: 0,
      belongId: ''
    }
  },
  watch: {
    stepActive(n) {
      if (n > 2) {
        this.getAddress()
      }
    }
  },
  async mounted() {
    const { data: { list }} = await getCrown()
    this.crownList = list
    // console.log(this.$route.query.mobile)
    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
      })
    }
  },
  created() {
    this.activityList()
    this.provinces = eachReplaceKey(provinces)
  },
  methods: {
    // 新增地址识别
    text() {
      if (this.message.length < 1) {
        this.$message.error('请输入需要识别的内容')
      }
      const arr = AddressParse.parse(this.message)[0]
      console.log(arr)
      const arrIndex = this.provinces.findIndex(item => {
        return item.label === arr.province
      })
      if (arr.area === '' || arrIndex === -1) {
        const params = {
          city: arr.city,
          details: arr.details
        }
        if (params.details === '' || params.city === '') {
          this.$message.error('识别失败，请手动填写')
        } else {
          discernAdress(params).then(res => {
            if (res.code === 200) {
              if (!res.data.area) {
                this.$message.error('识别失败，请手动填写')
                return
              }
              this.orderInfo.name = arr.name
              this.orderInfo.mobile = arr.mobile
              this.orderInfo.province = arr.province
              this.orderInfo.city = arr.city
              this.orderInfo.area = res.data.area
              this.orderInfo.address = arr.details
              this.orderInfo.areaAll = [res.data.province, res.data.city, res.data.area]
            } else {
              this.$message.error('识别失败，请手动填写')
            }
          })
        }
      } else {
        this.orderInfo.name = arr.name
        this.orderInfo.mobile = arr.mobile
        this.orderInfo.province = arr.province
        this.orderInfo.city = arr.city
        this.orderInfo.area = arr.area
        this.orderInfo.address = arr.details
        this.orderInfo.areaAll = [arr.province, arr.city, arr.area]
      }
    },
    resetBelong() {
      this.belongUserParams = {
        page_index: 1,
        page_size: 10,
        search_name: ''
      }
      this.belongUserList = []
      this.belongUserTotal = 0
      this.belongId = ''
      this.dialog.belong = false
    },
    toPublishBindBelong() {
      if (!this.belongId) {
        this.$message.error('请选择所属者')
        return false
      }
      const loading = this.$loading()
      publishBindBelong({
        belong_id: this.belongId,
        id: this.radio
      }).then(res => {
        loading.close()
        if (res.code === 200) {
          this.$message.success('绑定所属着成功')
          this.resetBelong()
          this.getAddress()
        } else {
          this.$message.error(res.message || '绑定所属者失败')
        }
      }).catch(() => {
        loading.close()
        this.$message.error('绑定所属者失败')
      })
    },
    changeBelongPagination({ page, limit }) {
      this.belongUserParams.page_size = limit
      this.belongUserParams.page_index = page
      this.getBelongList()
    },
    getBelongList(cb) { // 获取所属
      const loading = this.$loading()
      this.belongUserParams.user_id = this.memberInfo.id
      getBelongByUser(this.belongUserParams).then(res => {
        loading.close()
        if (res.code === 200) {
          this.belongUserList = res.data.list
          this.belongUserTotal = res.data.total
          cb && cb()
        } else {
          this.$message.error(res.message || '获取所属者失败')
        }
      }).catch(() => {
        loading.close()
        this.$message.error('获取所属者失败')
      })
    },
    async activityList() {
      await activityList().then(res => {
        if (res.code === 200) {
          this.activitys = res.data
          res.data.map(item => {
            if (item.is_ing === 1) {
              this.activity_id = item.id
            } else {
              this.activity_id = res.data[0].id
            }
          })
        }
      })
    },
    // 获取地址
    getAddress() {
      this.$request(getUserAddress({ user_id: this.memberInfo.id }), ({ list }) => {
        this.addressList = list
      })
    },
    // 重置搜索状态
    reset() {
      this.goodList = []
      this.memberInfo = {}
      this.carArr = []
      this.selectGood = {}
      this.message = ''
      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)
    },
    handleAddGift() {
      if (this.isGift && !this.activity_id) {
        this.$message.warning('请选择赠品活动')
        return false
      }
      this.stepActive += 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 = 3
      }
    },
    // 提交订单
    handleSubmitOrder() {
      if (this.radio) {
        const belong_user = this.addressList.filter(item => Number(item.id) === Number(this.radio))[0].belong_user
        if (!belong_user) {
          this.$confirm('该地址暂未绑定所属者, 请先绑定所属者?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.getBelongList(() => {
              this.dialog.belong = true
            })
          }).catch(() => {})
          return false
        }
        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,
          activity_id: this.isGift ? this.activity_id : ''
        })
      } 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;
    }
  }
  .dialog_address {
    .title {
      display: flex;
      align-content: flex-start;
      align-items: center;
    }

    .label {
      margin-right: 15px;
    }

    .el-input-group__append {
      cursor: pointer;
      &:hover {
        background: #13C19F;
        color: #fff;
      }
    }

    .add {
      font-size: 12px;
      margin-left: 15px;
      cursor: pointer;
    }
    .el-radio-group {
      width: 100%;
    }

    .radio_item {
      width: 100%;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      padding: 10px 30px;
      &:hover{
        box-shadow: 0 1px 20px rgba(0,0,0,.2);

        & .el-radio__label .right {
          display: block;
        }
      }

      .default {
        font-size: 12px;
        color: #ff973c;
        border: 1px solid rgba(255,151,60,.4);
        display: inline-block;
        padding: 2px;
        border-radius: 2px;
      }

      .el-radio__label {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: #606266;

        .right {
          display: none;
          i {
            margin-left: 10px;

            &:hover {
              color: #13C19F !important;
            }
          }
        }
      }
    }
    .btn_main {
      padding: 15px 30px;
    }
  }
</style>
