<template>
  <div>
    <div class="con-title">毕业典礼申请</div>
    <div class="con-box">
      <el-button type="text" @click="goBack">返回列表</el-button>
      <div class="main-form">
        <el-form label-width="100px" ref="ruleForm" :model="ruleForm" :rules="rules">
          <!-- <el-form-item label="本人参与方式" prop="product_id">
            <el-radio-group v-model="ruleForm.product_id" size="small">
              <el-radio border :label="item.id" v-for="item in selfProductList" :key="item.id">
                {{ item.name }}
              </el-radio>
              <el-radio border>其他</el-radio>
            </el-radio-group>
            <el-popover placement="top-start" width="400" trigger="hover">
              <i class="el-icon-question" slot="reference"></i>
              <div>
                <ol>
                  <li v-for="item in selfProductList" :key="item.id">
                    {{ item.name }}：{{ item.desc }} {{ item.price / 100 }}元
                  </li>
                </ol>
              </div>
            </el-popover>
          </el-form-item> -->
          <template v-if="ruleForm.product_id">
            <el-form-item label="姓名" prop="personal_name">
              <el-input v-model="ruleForm.personal_name" disabled />
            </el-form-item>
            <el-form-item label="手机号" prop="telephone">
              <el-input v-model="ruleForm.telephone" disabled />
            </el-form-item>
            <el-form-item label="班级" prop="class_name">
              <el-input v-model="ruleForm.class_name" disabled />
            </el-form-item>
            <!-- <el-form-item label="邮寄地址" prop="address">
              <el-input type="textarea" v-model="ruleForm.address" />
            </el-form-item> -->
          </template>
          <el-form-item label="添加随同" prop="has_children">
            <el-radio-group v-model="ruleForm.has_children" size="small">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="ruleForm.has_children">
            <div class="children" v-for="(child, index) in ruleForm.children" :key="index">
              <i class="el-icon-error" @click="handleRemoveChild(index)"></i>
              <el-form-item
                label="随同关系"
                :prop="'children.' + index + '.product_id'"
                :rules="{ required: true, message: '请选择', trigger: 'blur' }"
              >
                <el-select v-model="child.product_id">
                  <el-option
                    :value="item.id"
                    :label="item.name"
                    :key="item.id"
                    v-for="item in otherProductList"
                  ></el-option>
                </el-select>
                <el-popover placement="top-start" width="400" trigger="hover">
                  <i class="el-icon-question" slot="reference"></i>
                  <div>
                    <ol>
                      <li v-for="item in otherProductList" :key="item.id">{{ item.name }}：{{ item.desc }}</li>
                    </ol>
                  </div>
                </el-popover>
              </el-form-item>
              <el-form-item
                label="姓名"
                :prop="'children.' + index + '.personal_name'"
                :rules="{ required: true, message: '请输入姓名', trigger: 'blur' }"
              >
                <el-input v-model="child.personal_name" />
              </el-form-item>
              <el-form-item
                label="手机号"
                :prop="'children.' + index + '.telephone'"
                :rules="{ required: true, message: '请输入手机号', trigger: 'blur' }"
              >
                <el-input v-model="child.telephone" />
              </el-form-item>
            </div>
            <div style="text-align: right">
              <el-button type="text" @click="handleAddChild">新增随同</el-button>
            </div>
          </template>
          <el-form-item label="支付方式" prop="payment">
            <el-radio-group v-model="ruleForm.payment">
              <el-radio :label="item.value" v-for="item in payList" :key="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="支付金额" prop="payment"><em class="price">￥</em>{{ payPrice }} </el-form-item>
          <el-form-item>
            <el-button type="primary" :disabled="disabled" @click="handleSubmit">立即支付</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <el-dialog title="支付" width="400px" :visible.sync="payVisible">
      <pay :payment="ruleForm.payment" :productId="productId" @success="handlePaySuccess" v-if="payVisible"></pay>
    </el-dialog>
  </div>
</template>

<script>
import * as api from '../../api'
import Pay from '../../components/pay'
export default {
  components: { Pay },
  data() {
    return {
      productList: [],
      ruleForm: {
        product_id: '',
        personal_name: '',
        telephone: '',
        class_name: '',
        address: '',
        has_children: 0,
        payment: '2',
        children: [{ product_id: '', personal_name: '', telephone: '' }]
      },
      rules: {
        personal_name: [{ required: true, message: '请输入您的姓名', trigger: 'blur' }],
        telephone: [{ required: true, message: '请输入您的手机号', trigger: 'blur' }],
        class_name: [{ required: true, message: '请输入您的班级', trigger: 'blur' }]
        // address: [{ required: true, message: '请输入邮寄地址', trigger: 'blur' }]
      },
      payList: [
        { label: '微信支付', value: '2' },
        { label: '支付宝支付', value: '1' }
      ],
      payVisible: false,
      submitDisabled: false,
      productId: ''
    }
  },
  computed: {
    affairId() {
      return this.$route.query.id
    },
    selfProductList() {
      return this.productList.slice(0, this.productList.length - 1)
    },
    otherProductList() {
      return this.productList.slice(this.productList.length - 1)
    },
    disabled() {
      return (!this.ruleForm.product_id && !this.ruleForm.has_children) || this.submitDisabled
    },
    payPrice() {
      let price = 0
      if (this.ruleForm.product_id) {
        const found = this.productList.find(item => item.id === this.ruleForm.product_id)
        price += parseFloat(found.price)
      }
      if (this.ruleForm.has_children && this.ruleForm.children.length) {
        this.ruleForm.children.forEach(item => {
          if (item.product_id) {
            const found = this.productList.find(product => product.id === item.product_id)
            price += parseFloat(found.price)
          }
        })
      }
      return price / 100
    }
  },
  methods: {
    // 返回
    goBack() {
      this.$router.push({ path: '/app/offices', query: { id: this.affairId } })
    },
    // 获取学生信息
    getStudent() {
      api.getStudent().then(response => {
        const data = this.$_.pick(response, ['personal_name', 'telephone', 'class_name', 'address'])
        Object.assign(this.ruleForm, data)
      })
    },
    getProductList() {
      api.getGraduationProductList().then(response => {
        const { list = [] } = response
        const [first] = list
        this.productList = list
        if (first) {
          this.ruleForm.product_id = first.id
        }
      })
    },
    // 添加随同
    handleAddChild() {
      this.ruleForm.children.push({ product_id: '', personal_name: '', telephone: '' })
    },
    // 删除随同
    handleRemoveChild(index) {
      this.ruleForm.children.splice(index, 1)
      if (!this.ruleForm.children.length) {
        this.ruleForm.has_children = 0
      }
    },
    // 提交
    handleSubmit() {
      this.$refs.ruleForm.validate().then(this.mergeProduct)
    },
    // 合并商品
    mergeProduct() {
      const params = []
      // 个人商品数据
      if (this.ruleForm.product_id) {
        const product = this.productList.find(product => product.id === this.ruleForm.product_id)
        params.push({
          id: this.ruleForm.product_id,
          num: 1,
          comment: `${product.name}:${product.desc}`,
          personal_name: this.ruleForm.personal_name,
          telephone: this.ruleForm.telephone,
          class_name: this.ruleForm.class_name,
          address: this.ruleForm.address,
          has_children: this.ruleForm.has_children,
          is_self: 1,
          product: JSON.stringify(product)
        })
      }
      // 随同商品数据
      if (this.ruleForm.has_children && this.ruleForm.children.length) {
        this.ruleForm.children.forEach(item => {
          const product = this.productList.find(product => product.id === item.product_id)
          params.push(
            Object.assign(
              {
                id: item.product_id,
                num: 1,
                comment: `${product.name}:${product.desc}`,
                product: JSON.stringify(product)
              },
              item
            )
          )
        })
      }
      this.submitDisabled = true
      api
        .mergeGraduationProduct({ params })
        .then(response => {
          this.productId = response.product_id
          this.payVisible = true
        })
        .finally(() => {
          this.submitDisabled = false
        })
    },
    handlePaySuccess() {
      this.$message({ type: 'success', message: '支付成功' })
      this.payVisible = false
      this.$router.replace({ path: '/app/offices', query: { id: this.affairId } })
    }
  },
  beforeMount() {
    // 获取学生信息
    this.getStudent()
    this.getProductList()
  }
}
</script>

<style lang="scss" scoped>
.main-form {
  max-width: 600px;
  margin: 0 auto;
}
.price {
  font-style: normal;
  color: #b80037;
  font-size: 20px;
}
.children {
  position: relative;
  padding: 20px 0;
  border-top: 1px solid #dcdfe6;
  &:hover {
    padding: 20px 20px 20px 0;
    background-color: #dcdfe6;
    .el-icon-error {
      display: block;
    }
  }
  .el-icon-error {
    display: none;
    position: absolute;
    right: -10px;
    top: -10px;
    font-size: 20px;
    cursor: pointer;
  }
}
.el-icon-question {
  font-size: 20px;
}
.el-radio.is-bordered {
  margin-right: 10px;
}
</style>
