<template>
  <div>
    <!-- 增改查弹窗 -->
    <el-dialog :title="titles[mode] || '详情'" :visible.sync="formVisible" class="finish-dialog" :class="mode" width="960px" append-to-body :close-on-click-modal="false">
      {{!-- <div v-if="mode === 'add'" class="alert-box">说明：xxxx</div> --}}
      <el-form v-if="formVisible" ref="detailForm" v-loading="detailLoading" :model="formData" :rules="rules" label-position="right" inline class="detail-dialog" label-width="140px">
        <el-form-item label="名称：">
          <span>
            \{{ formData.name || '--' }}
          </span>
        </el-form-item>
        <el-form-item label="手机号：" prop="phonenum">
          <el-input v-if="isEditAdd" v-model.trim="formData.phonenum" placeholder="请输入" type="number" />
          <span v-else>
            \{{ formData.phonenum || '--' }}
          </span>
        </el-form-item>
        <el-form-item label="开始日期：" prop="startdate">
          <el-date-picker v-if="isEditAdd" v-model.trim="formData.startdate" type="date" value-format="yyyy-MM-dd" placeholder="请输入" :disabled="hadConsume" />
          <span v-else>
            \{{ formData.startdate || '--' }}
          </span>
        </el-form-item>
        <el-form-item label="方案：" prop="consumeway">
          <el-checkbox-group v-model.trim="formData.consumeway" :disabled="!isEditAdd || hadConsume" @change="formData.consumeway = $event">
            <el-checkbox :label="1">方案1</el-checkbox>
            <el-checkbox :label="2">方案2</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="权限开关：" class="fit-width">
          <el-switch v-if="isEditAdd" v-model.trim="formData.isgreater" active-value="1" :inactive-value="2" />
          <span v-else>
            \{{ options.isgreater[formData.isgreater] }}
          </span>
        </el-form-item>
        <el-form-item label="模式：" prop="swapmode" style="width: 100%">
          <template v-if="isEditAdd">
            <el-radio v-model.trim="formData.swapmode" :label="1">模式1</el-radio>
            <el-radio v-model.trim="formData.swapmode" :label="2">模式2</el-radio>
          </template>
          <span v-else>
            \{{ options.swapmode[formData.swapmode] || '--' }}
          </span>
        </el-form-item>
        <el-form-item label="描述：" prop="remark" style="width: 100%">
          <el-input
            v-if="isEditAdd"
            v-model.trim="formData.remark"
            placeholder="请输入"
            type="textarea"
            show-word-limit
            :autosize="{ minRows: 3, maxRows: 4 }"
            :maxlength="100"
          />
          <span v-else>
            \{{ formData.remark || '--' }}
          </span>
        </el-form-item>
        <!-- <el-row class="mb-20">
          <span class="list-title">其他信息</span>
        </el-row> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="detailLoading" @click="formVisible = false">关闭</el-button>
        <el-button v-if="isEditAdd" type="primary" :loading="detailLoading" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { deepClone } from '@/utils'

const defaultFormData = { // 表单初始数据
}

export default {
  name: '',
  inject: ['global', 'refresh'],
  data() {
    const validateDateRange = (rule, value, callback) => {
      if (!this.formData.authorizationstart || !this.formData.authorizationend) {
        return callback()
      } else if (
        dayjs(this.formData.authorizationend).isBefore(this.formData.authorizationstart) &&
        this.formData.authorizationend !== this.formData.authorizationstart
      ) { // 触发条件：开始在结束后 && 开始不等于结束
        return callback(new Error('结束时间不可早于开始时间！'))
      } else {
        const isStartTimeValid = !(dayjs(this.formData.authorizationstart).isBefore(dayjs()) && !dayjs(this.formData.authorizationstart).isSame(dayjs(), 'date'))
        isStartTimeValid && this.$refs.detailForm.clearValidate('authorizationstart')
        this.$refs.detailForm.clearValidate('authorizationend')
        return callback()
      }
    }
    const validateStartTime = (rule, value, callback) => {
      if (this.mode === 'add' && dayjs(value).isBefore(dayjs(), 'date')) {
        return callback(new Error('开始时间不能早于当前时间！'))
      } else {
        return validateDateRange(rule, value, callback)
      }
    }
    const validateEndTime = (rule, value, callback) => {
      if (this.mode === 'add' && dayjs(value).isBefore(dayjs(), 'date')) {
        return callback(new Error('结束时间不能早于当前时间！'))
      } else {
        return validateDateRange(rule, value, callback)
      }
    }
    return {
      detailLoading: false,
      mode: 'see', // 查看see / 编辑edit / 添加add
      titles: { // 弹窗标题(动态)
        see: '查看',
        add: '新增',
        edit: '编辑'
      },
      formVisible: false, // 弹窗显示
      formConfig: {}, // 表单配置
      formData: {}, // 表单数据
      rules: {
        // TODO: 校验规则
        // userid: [
        //   { required: true, message: '用户不能为空', trigger: 'change' }
        // ],
        // starttime: [
        //   { required: true, message: '开始时间不能为空', trigger: 'change' },
        //   { validator: validateStartTime, trigger: 'change' }
        // ],
        // endtime: [
        //   { required: true, message: '结束时间不能为空', trigger: 'change' },
        //   { validator: validateEndTime, trigger: 'change' }
        // ]
      }
    }
  },
  computed: {
    isEditAdd() {
      return this.mode === 'edit' || this.mode === 'add'
    }
  },
  methods: {
    showDialog({ mode, formConfig, formData, formTitle }) {
      this.mode = mode || (this.formData.id ? 'edit' : 'add')
      if (this.mode === 'add') {
        this.formData = { ...defaultFormData }
      } else {
        this.formData = { ...formData }
      }
      this.initFormData()
      this.formVisible = true
    },
    initFormData() { // 表单数据初始化
      // TODO: init formData
      // const {} = this.formData
      // this.$set(this.formData, 'authorizationtype', authorizationtype || 1)
    },
    filterFormData(formData) { // 提交数据过滤
      const data = deepClone(formData)
      // TODO: 自定义数据过滤
      return data
    },
    submit() {
      console.log('output->formData', this.formData)
      this.$refs.detailForm.validate(async(valid) => {
        if (valid) {
          const formData = this.filterFormData(this.formData)
          console.log('FORM', formData)
          this.detailLoading = true
          try {
            let res = {}
            if (this.mode === 'add') {
              // TODO: 提交接口
              // res = await addInvitation(formData)
            } else {
              // TODO: 修改接口
              // res = await updateInvitation(formData)
            }
            if (res.success) {
              this.formVisible = false
              this.refresh()
            }
          } finally {
            this.detailLoading = false
          }
        } else {
          this.$message.warning('校验失败')
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">

.width-clear {
  width: auto
}
.finish-dialog {
  /deep/ .el-form-item {
    &__content  {
      width: calc(100% - 180px); // 减去label宽
      max-width: none;
      .el-checkbox-group {
        line-height: normal;
      }
    }
    &__label {
      padding-right: 12px !important;
    }
    &.fit-width {
      .el-form-item__content {
        width: fit-content;
      }
    }
  }
  &.edit, &.add {
    /deep/ .el-form-item {
      margin-bottom: 22px;
    }
  }
  &.see {
    .detail-dialog {
      // background-color: #f8f8f8;
      padding: 20px;
    }
    /deep/ .el-form-item {
      &__label, &__content { // 统一行高
        line-height: 2;
      }
      margin-bottom: 10px;
    }
  }
}

/* 穿梭框 */
/deep/ .el-transfer {
  &__buttons {
    display: inline-flex;
    flex-direction: column;
    .el-button + .el-button {
      margin-left: 0;
    }
  }
}
</style>
