<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="45%" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="formData.orderNo" placeholder="请输入订单号" disabled/>
        </el-form-item>
        <el-form-item label="用户姓名" prop="userName">
          <el-input v-model="formData.userName" placeholder="请输入用户姓名"/>
        </el-form-item>
        <el-form-item label="用户手机号" prop="userPhone">
          <el-input v-model="formData.userPhone" placeholder="请输入用户手机号"/>
        </el-form-item>
        <el-form-item label="用户身份证号" prop="userNo">
          <el-input v-model="formData.userNo" placeholder="请输入用户身份证号"/>
        </el-form-item>
        <el-form-item label="性别" prop="userSex">
          <el-radio-group v-model="formData.userSex">
            <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.SYSTEM_USER_SEX)"
                      :key="dict.value" :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="课程名字" prop="courseName">
          <el-input v-model="formData.courseName" placeholder="请输入课程名字" disabled/>
        </el-form-item>

        <el-form-item label="负责教练" prop="coachUserName">
          <el-select v-model="formData.coachUserName" placeholder="请选择教练" @change="handleCoachChange">
            <el-option v-for="dict in coachList" :key="dict.userId" :label="dict.name" :value="dict" />
          </el-select>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订金金额" prop="reserveMoney">
              <el-input v-model="formData.reserveMoney" placeholder="请输入订金金额"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="尾款" prop="restMoney">
              <el-input v-model="formData.restMoney" placeholder="请输入尾款"/>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="毕业时间" prop="gradTime">
              <el-date-picker clearable v-model="formData.gradTime" type="date" value-format="timestamp"
                              placeholder="请选择毕业时间"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="拿证时间" prop="passTime">
              <el-date-picker clearable v-model="formData.passTime" type="date" value-format="timestamp"
                              placeholder="请选择拿证时间"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider></el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否终止" prop="ifEnd">
              <el-radio-group v-model="formData.ifEnd">
                <el-radio v-for="item in ifEndRadio"
                          :key="item.value" :label="item.value"
                >{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
              <el-col :span="12">
                <el-form-item label="终止时间" prop="endTime">
                  <el-date-picker clearable v-model="formData.endTime" type="date" value-format="timestamp"
                                  placeholder="选择终止时间"
                  />
                </el-form-item>
              </el-col>
        </el-row>

        <el-form-item label="终止原因" prop="endReason">
          <el-input v-model="formData.endReason" placeholder="请输入终止原因"/>
        </el-form-item>

        <el-divider></el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报名时间" prop="createTime">
              <el-date-picker clearable v-model="formData.createTime" type="datetime" value-format="timestamp"
                              placeholder="选择报名时间"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="缴费时间" prop="payFeesTime">
              <el-date-picker clearable v-model="formData.payFeesTime" type="date" value-format="timestamp"
                              placeholder="选择缴费时间"
              />
            </el-form-item>
          </el-col>
        </el-row>


        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="优惠金额" prop="discount">
              <el-input-number v-model="formData.discount" placeholder="请输入优惠金额" :precision="2"
                               :step="0.1"></el-input-number>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="实付金额" prop="actualPayment">
              <el-input-number v-model="formData.actualPayment" placeholder="请输入实付金额" :precision="2"
                               :step="0.1"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单状态" prop="paymentStatus">
              <el-select v-model="formData.paymentStatus" placeholder="请选择订单状态">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.DRIVE_SCHOOL_ORDER_STATUS)"
                           :key="dict.value" :label="dict.label" :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="是否已面签" prop="isSign">
              <!--          <el-select v-model="formData.isSign" placeholder="请选择是否已面签">-->
              <!--            <el-option label="请选择字典生成" :label="item.label" v-for="item in this.getDictDatas(DICT_TYPE.SYSTEM_USER_SEX)"/>-->
              <!--          </el-select>-->
              <el-radio-group v-model="formData.isSign">
                <el-radio v-for="dict in isSignRadio"
                          :key="dict.value" :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

<!--        <el-form-item label="提成方案" prop="schemeId">
          <el-select v-model="formData.schemeId" placeholder="请选择提成方案">
            <el-option
              v-for="item in schemeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>-->
        <div style="display: flex; flex-direction: row; gap: 10px;">
          <div>
          <el-form-item label="提成方案" prop="schemeId" >
          <el-select v-model="formData.schemeId" placeholder="请选择提成方案" style="width: 300px;">
            <el-option
              v-for="item in schemeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <div style="display: flex; justify-content: space-between; width: 100%">
                <span>{{ item.name }}</span>
                <span style="color: #888; margin-left: 20px;">
              <span style="color: red;">*科1：</span>{{ item.subject1Deduct }}元,
              <span style="color: red;">*科2：</span>{{ item.subject2Deduct }}元,
              <span style="color: red;">*科3：</span>{{ item.subject3Deduct }}元,
              <span style="color: red;">*科4：</span>{{ item.subject4Deduct }}元,
              <span style="color: red;">*业务经理：</span>{{ item.subject0Deduct }}元
            </span>
              </div>
            </el-option>
          </el-select>
          </el-form-item>
          </div>
          <div>
          <el-button type="primary" icon="el-icon-plus" size="small" @click="openSchemeDialog">添加方案</el-button>
          </div>
          <div>
            <span style="color: red">(如果没有合适的方案，请添加)</span>
          </div>
        </div>



        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="支付类型" prop="payType">
              <el-select v-model="formData.payType" placeholder="请选择支付类型">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.DRIVE_SCHOOL_PAY_TYPE)"
                           :key="dict.value" :label="dict.label" :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="支付渠道" prop="payChannel">
              <el-select v-model="formData.payChannel" placeholder="请选择支付渠道">
                <el-option v-for="dict in this.payChannelList"
                           :key="dict.value" :label="dict.label" :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="学员是否确认" prop="ifAgree">
              <el-select v-model="formData.ifAgree" placeholder="请选择学员是否确认">
                <el-option v-for="dict in this.ifAgreeList"
                           :key="dict.value" :label="dict.label" :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="订单备注" prop="orderRemark">
          <el-input type="textarea" v-model="formData.orderRemark" placeholder="请输入订单备注"/>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <SchemeForm ref="schemeFormRef" @success="fetchSchemeList" />
  </div>

</template>

<script>
import * as SchoolCourseOrderApi from '@/views/drivingSchool/DriveSchoolPay/api'
import { getSchemeListByCourseId } from '@/views/drivingSchool/DriveSchoolPay/api'
import SchemeForm from '@/views/drivingSchool/schoolCourse/form/schemeForm.vue'
import { listCoach } from '@/views/drivingSchool/drivingSchoolCar/api/car'
import { getDictDatas } from '@/utils/dict'

export default {
  name: 'SchoolCourseOrderForm',
  components: {
    SchemeForm
  },

  data() {
    return {
      // 弹出层标题
      dialogTitle: '',
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        orderNo: undefined,
        userName: undefined,
        userPhone: undefined,
        userNo: undefined,
        userSex: undefined,
        courseId: undefined,
        courseName: undefined,
        coachUserId: undefined,
        coachUserName: undefined,
        reserveMoney: undefined,
        courseType: undefined,
        ifEnd: undefined,
        endReason: undefined,
        endTime: undefined,
        paymentStatus: undefined,
        isSign: undefined,
        restMoney: undefined,
        payType: undefined,
        passTime: undefined,
        gradTime: undefined,
        schemeId: undefined,
        orderRemark: undefined,
        discount: undefined,
        actualPayment: undefined,

      },
      ifEndRadio: [
        {
          label: '是',
          value: true
        },
        {
          label: '否',
          value: false
        }
      ],
      isSignRadio: [
        {
          label: '是',
          value: 1
        },
        {
          label: '否',
          value: 0
        }
      ],
      payChannelList: [
        {
          label: '线下支付',
          value: '2'
        },
        {
          label: '微信支付',
          value: '1'
        }
      ],
      ifAgreeList: [
        {
          label: '未确认',
          value: '0'
        },
        {
          label: '已同意',
          value: '1'
        },
        {
          label: '未同意',
          value: '2'
        },
        {
          label: '非代报名订单',
          value: null
        }
      ],
      // 表单校验
      formRules: {},
      schemeList: [],
      coachList: [],
    }
  },
  methods: {
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true
      this.reset()
      // 修改时，设置数据
      if (id) {
        this.formLoading = true
        try {
          const res = await SchoolCourseOrderApi.getSchoolCourseOrder(id)
          this.formData = res.data
          this.title = '修改驾照报名订单'
          await this.loadSchemeList(this.formData.courseId);
          const coachRes = await listCoach()
          this.coachList = coachRes.data
          if (this.formData.coachUserId) {
            const selectedCoach = this.coachList.find(c => c.userId === this.formData.coachUserId);
            if (selectedCoach) {
              this.formData.coachUserName = selectedCoach.name;
            }
          }
        } finally {
          this.formLoading = false
        }
      }
      this.title = '新增驾照报名订单'
    },
    openSchemeDialog() {
      this.$refs.schemeFormRef.open(null, this.formData.courseId)
    },
    async fetchSchemeList() {
      // 重新拉取方案列表
      console.log('courseId', this.formData.courseId)
      const res = await getSchemeListByCourseId(this.formData.courseId)
      console.log('res', res)
      this.schemeList = res.data || []
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs['formRef'].validate()
      // 检查是否选择了提成方案
      if (!this.formData.schemeId) {
        try {
          await this.$confirm('该订单尚未选择提成方案，是否继续？', '提示', {
            confirmButtonText: '继续',
            cancelButtonText: '取消',
            type: 'warning'
          })
          // 用户点击继续，继续执行后续操作
        } catch (error) {
          // 用户点击取消，不执行操作
          return
        }
      }
      this.formLoading = true
      try {
        const data = this.formData
        // 修改的提交
        if (data.id) {
          await SchoolCourseOrderApi.updateSchoolCourseOrder(data)
          this.$modal.msgSuccess('修改成功')
          this.dialogVisible = false
          this.$emit('success')
          return
        }
        // 添加的提交
        await SchoolCourseOrderApi.createSchoolCourseOrder(data)
        this.$modal.msgSuccess('新增成功')
        this.dialogVisible = false
        this.$emit('success')
      } finally {
        this.formLoading = false
      }
    },
    async loadSchemeList(courseId) {
      console.log('courseId', courseId)
      if (!courseId) return;
      try {
        const res = await getSchemeListByCourseId(courseId);
        console.log('res', res)
        this.schemeList = res.data || [];
      } catch (error) {
        this.$message.error('获取提成方案失败');
      }
    },
    async getSchemeListByCourseId(courseId){
      await SchoolCourseOrderApi.getSchemeListByCourseId(courseId)
      .then(res => {
        this.schemeList = res.data
      })
    },
    /* handleCoachChange() {
      const selected = this.coachList.find(item => item.userId === this.formData.coachId);
      if (selected) {
        this.formData.coachName = selected.name;
      } else {
        this.formData.coachName = '';
      }
    }, */
    handleCoachChange(selectedCoach) {
      if (selectedCoach) {
        this.formData.coachUserId = selectedCoach.userId;
        this.formData.coachUserName = selectedCoach.name;
      } else {
        this.formData.coachUserId = undefined;
        this.formData.coachUserName = undefined;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        orderNo: undefined,
        userName: undefined,
        userPhone: undefined,
        userNo: undefined,
        userSex: undefined,
        courseId: undefined,
        courseName: undefined,
        coachUserId: undefined,
        coachUserName: undefined,
        reserveMoney: undefined,
        courseType: undefined,
        ifEnd: undefined,
        endReason: undefined,
        endTime: undefined,
        paymentStatus: undefined,
        isSign: undefined,
        restMoney: undefined,
        payType: undefined,
        passTime: undefined,
        gradTime: undefined,
        schemeId: undefined,
        orderRemark: undefined,
        discount: undefined,
        actualPayment: undefined,
      }
      this.resetForm('formRef')
    }
  }
}
</script>
