<template>
  <el-dialog
    :title="`${id ? '编辑' : '新增'} - 后装保障需求数据`"
    :visible.sync="dialogVisible"
    custom-class="new-edition-dialog"
    width="60%"
    @closed="closed"
    @open="open"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-position="top"
      label-width="auto"
    >
      <el-row :gutter="24" style="flex-wrap:wrap" type="flex">
        <el-col :span="6">
          <el-form-item label="责任单位" prop="orgName">
            <el-input
              v-model="form.orgName"
              clearable
              disabled
              placeholder="请输入责任单位"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="训练课目" prop="trainSubjectId">
            <el-select
              clearable
              v-model="form.trainSubjectId"
              placeholder="请选择训练课目"
              style="width:100%"
              @change="selectSubject"
              v-on:click.native="subjectDUsers"
            >
              <el-option
                v-for="item in subjectList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="训练内容的场地" prop="spaceId">
            <el-select
              v-model="form.spaceId"
              placeholder="请选择训练场地"
              style="width:100%"
              filterable
            >
              <el-option
                v-for="item in spaceNameList"
                :key="item.name"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="营房" prop="barracks">
            <el-input
              v-model="form.barracks"
              clearable
              placeholder="请输入营房"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="油料" prop="oilseed">
            <el-input
              v-model="form.oilseed"
              clearable
              placeholder="请输入油料"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="物资" prop="materials">
            <el-input
              v-model="form.materials"
              clearable
              placeholder="请输入物资"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="装备" prop="equipment">
            <el-input
              v-model="form.equipment"
              clearable
              placeholder="请输入装备"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="弹药" prop="ammunition">
            <el-input
              v-model="form.ammunition"
              clearable
              placeholder="请输入弹药"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="摩托小时" prop="motorcycleHours">
            <el-input
              v-model="form.motorcycleHours"
              clearable
              placeholder="请输入摩托小时"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="memo">
            <el-input
              v-model="form.memo"
              :autosize="{minRows: 1, maxRows: 3}"
              clearable
              placeholder="请输入备注"
              type="textarea"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button :loading="saveLoading" type="primary" @click="handleSave">
        确 认
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </span>
    <subjectDialog ref="subjectDialog" @getUser="getUser" />
  </el-dialog>
</template>

<script>
import * as api from '@/api/examDataMenu/examSafeguardData/demandData'
import * as examSpaceData from '@/api/examDataMenu/examSafeguardData/examSpaceData.js'
import subjectDialog from '@/components/examDialog/subjectDialog.vue'

export default {
  name: 'AddEditDialog',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    rowInfo: {
      type: Object,
      default: () => ({})
    },
    activeTreeItem: {
      type: Object,
      default: () => ({})
    }
  },
  components: {
    subjectDialog
  },
  data() {
    return {
      rules: {
        trainSubjectId: [
          {required: true, message: '训练课目不能为空', trigger: 'blur'}
        ],
        orgName: [
          {required: true, message: '所属单位不能为空', trigger: 'change'}
        ],
        spaceId: [
          {required: true, message: '训练场地场地不能为空', trigger: 'change'}
        ]
      },
      form: {},
      saveLoading: false,
      subjectList: [],
      spaceNameList: [] //训练场地字典
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    id() {
      return this.rowInfo?.id || ''
    }
  },
  created() {},
  methods: {
    selectSubject() {
      this.subjectList = []
    },
    getUser(val) {
      this.$set(this.form, 'trainSubjectId', val[0].id)
      this.$set(this.form, 'trainSubject', val[0].name)

      this.subjectList = val
    },
    //
    subjectDUsers() {
      this.$refs.subjectDialog.add(this.subjectList)
    },
    // 获取场地数据
    async getLandList() {
      let {rows} = await examSpaceData.tableData({pageSize: -1})

      this.spaceNameList = rows
    },

    // 打开弹层
    open() {
      this.getLandList()
      if (this.id) {
        this.saveLoading = true
        this.getDetail(this.id)
      } else {
        const {name: orgName = '', id: orgId = ''} = this.activeTreeItem || {}
        this.form = {...this.form, orgName, orgId}
      }
    },

    // 关闭弹层后
    closed() {
      const {rules} = this
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {rules})

      this.$nextTick(_ => {
        this.$refs.form.$el.scrollTop = 0
        this.$refs.form.clearValidate()
      })
    },

    // 获取详情
    async getDetail(id) {
      try {
        const {...form} = await api.tableDetail(id)
        this.form = {...form}
        this.subjectList = [
          {
            name: this.form.trainSubject,
            id: this.form.trainSubjectId
          }
        ]
      } finally {
        this.saveLoading = false
      }
    },

    // 保存
    handleSave() {
      this.$refs.form.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          this.saveLoading = true
          const myInterFace = this.id ? api.tableEdit : api.tableAdd
          let params = JSON.parse(JSON.stringify(this.form))
          params.spaceName = this.spaceNameList.filter(item => {
            return item.id == params.spaceId
          })[0].name

          try {
            let {state, message} = await myInterFace({
              ...params
            })

            if (state) {
              this.$emit('submit', this.id ? 'edit' : 'add')
              message = this.id ? '编辑' : '新增'
              this.$message.success(`后装保障需求数据${message}成功`)
              this.dialogVisible = false
            }
          } finally {
            this.saveLoading = false
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
