<template>
  <el-dialog
    :title="`${id ? '编辑' : '新增'} - 装备基础资源数据`"
    :visible.sync="dialogVisible"
    custom-class="new-edition-dialog"
    width="65%"
    @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="name">
            <el-input
              v-model="form.name"
              clearable
              placeholder="请输入装备名称"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="装备分类" prop="type">
            <el-select
              v-model="form.type"
              clearable
              placeholder="请选择装备分类"
              style="width: 100%;"
            >
              <el-option
                v-for="item in getDictionaryByCode('zblx')"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="装备状态" prop="status">
            <el-select
              v-model="form.status"
              clearable
              placeholder="请选择装备状态"
              style="width: 100%;"
            >
              <el-option
                v-for="item in getDictionaryByCode('zbzt')"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="责任人" prop="personLiableId">
            <el-select
              v-model="form.personLiableId"
              placeholder="请选择责任人"
              style="width:100%"
              multiple
              v-on:click.native="getMainPerson"
            >
              <el-option
                v-for="item in mainUserIdList"
                :key="item.fullname"
                :label="item.fullname"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="出厂编号" prop="mfCode">
            <el-input
              v-model="form.mfCode"
              clearable
              placeholder="请输入出厂编号"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="战斗编号" prop="battleCode">
            <el-input
              v-model="form.battleCode"
              clearable
              placeholder="请输入战斗编号"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="列装时间" prop="loadingTime">
            <el-date-picker
              v-model="form.loadingTime"
              format="yyyy-MM-dd"
              placeholder="请选择列装时间"
              style="width: 100%"
              type="date"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="计量单位" prop="unit">
            <el-select
              v-model="form.unit"
              clearable
              placeholder="请选择计量单位"
              style="width: 100%;"
            >
              <el-option
                v-for="item in getDictionaryByCode('jldw')"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="战教区分" prop="zjqf">
            <el-input
              v-model="form.zjqf"
              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>
    <mianPersonVue ref="mianPersonVue" @getUser="getMainUser" />
  </el-dialog>
</template>

<script>
import * as api from '@/api/examDataMenu/examSafeguardData/equipmentBaseData'
import {getDictionaryByCode} from '@/utils/dictionary'
import {getOrgUserQuery} from '@/api/systemInterface'
import {refineRequestBody} from '@/utils/requestWrappers'
import mianPersonVue from '@/components/examDialog/mianPerson.vue'

import moment from 'moment'

export default {
  name: 'AddEditDialog',
  components: {
    mianPersonVue
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    rowInfo: {
      type: Object,
      default: () => ({})
    },
    activeTreeItem: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      rules: {
        orgName: [
          {required: true, message: '所属单位不能为空', trigger: 'blur'}
        ],
        name: [{required: true, message: '名称不能为空', trigger: 'blur'}],
        type: [{required: true, message: '装备分类不能为空', trigger: 'change'}]
      },
      form: {
        type: '1',
        status: '1',
        unit: '个',
        loadingTime: moment().format('YYYY-MM-DD')
      },
      saveLoading: false,
      userList: [],
      mainUserIdList: [] //主训员字典
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    id() {
      return this.rowInfo?.id || ''
    }
  },
  created() {
    // this.getUserList()
  },
  methods: {
    getDictionaryByCode,
    getMainUser(data) {
      this.$set(
        this.form,
        'personLiableId',
        data.map(item => {
          return item.id
        })
      )
      this.$set(
        this.form,
        'personLiable',
        data.map(item => {
          return item.fullname
        })
      )
      this.mainUserIdList = data
    },
    getMainPerson() {
      this.$refs.mianPersonVue.add(this.mainUserIdList)
    },
    // 打开弹层
    open() {
      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, userList} = this
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {
        rules,
        userList
      })

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

    // 获取详情
    async getDetail(id) {
      try {
        let {
          // startTime = '',
          // endTime = '',
          personLiable = [],
          personLiableId = [],
          ...form
        } = await api.tableDetail(id)
        personLiable = personLiable.length ? personLiable.split(',') : []
        personLiableId = personLiableId.length ? personLiableId.split(',') : []
        this.mainUserIdList = personLiable.map((item, i) => {
          return {
            fullname: item,
            id: personLiableId[i]
          }
        })
        // startEndTime = startTime && endTime ? [startTime, endTime] : ''
        this.form = {...form, personLiableId, personLiable}
      } finally {
        this.saveLoading = false
      }
    },

    // // 获得用户列表
    // async getUserList() {
    //   const {rows = []} = await getOrgUserQuery(
    //     refineRequestBody({
    //       querys: [{property: 'DEM_ID_', value: '1258608622670319616'}]
    //     })
    //   )
    //   this.userList = rows
    // },

    // 保存
    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

          const {...addEditForm} = this.form
          console.log(this.form.personLiable)

          let personLiable = this.form.personLiable.join(',')
          let personLiableId = this.form.personLiableId.join(',')

          try {
            let {state, message} = await myInterFace({
              ...addEditForm,
              personLiable,
              personLiableId
            })

            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>
