<template>
    <!-- 组件功能：普通新增编辑（目前只有主表）参数配置从api获取 -->
    <el-dialog
      :visible.sync="show"
      :modal="false"
      :modal-append-to-body="false"
      :show-close="true"
      @close="close"
      class="searchPageComponents"
      :fullscreen="true"
      style="width:calc(100% - 28px);left:14px;top:14px;height:calc(100% - 28px)"
      v-loading="Loading.addEditApiLoading"
    >
      <!-- 表单 -->
      <div v-if="active === 0" style="height: 100%;">
        <!-- 标题 -->
        <div class="dialogOuterTitle">{{formTitle}}</div>
        <!-- 表单 -->
        <el-form 
          class="addEditFrom"
          ref="addEditFrom_Ref"
          v-if="formData"
          :model="formData"
          :rules="formRules"
        >
          <el-row :gutter="40">
            <el-col
              :span="item.colSpan || 12"
              v-for="(item, index) in formItemData"
              :key="index"
            >
              <el-form-item 
                :label="item.label"
                :prop="item.prop"
              >
                <!-- 数值 -->
                <el-input-number
                  v-if="item.apiBaseType === 'number'"
                  v-model="formData[item.prop]"
                  :min="item.minimum || undefined"
                  :max="item.maximum || undefined"
                  :maxlength="item.maxLength || undefined"
                  :minlength="item.minLength || undefined"
                  :disabled="Boolean(item.disabled)"
                  :placeholder="item.placeholder || '请输入' + item.label"
                  @change="changeValue(item.prop,item,$event)"
                  @clear="clearValue(item.prop,$event)"
                ></el-input-number>
  
                <!-- 时间转换 -->
                <el-date-picker
                  v-else-if="item.apiBaseType === 'datetime'"
                  v-model="formData[item.prop]"
                  type="datetime"
                  placeholder="选择日期时间"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-ddTHH:mm:ss"
                  :disabled="Boolean(item.disabled)"
                ></el-date-picker>
  
                <!-- 布尔、枚举 -->
                <el-select 
                  v-else-if="item.isEnums || item.apiBaseType === 'boolean'"
                  v-model="formData[item.prop]" 
                  :placeholder="item.placeholder || '请选择' + item.label"
                  :disabled="Boolean(item.disabled)"
                >
                  <el-option
                    v-for="item in getItemEnums(item)"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
  
                <!-- 文本框 -->
                <!-- <el-input
                  v-else
                  type="textarea"
                  autosize
                  resize="none"
                  v-model="formData[item.prop]"
                  :placeholder="item.placeholder || '请输入' + item.label"
                  :disabled="Boolean(item.disabled)"
                ></el-input> -->
                <el-input 
                  v-else
                  v-model="formData[item.prop]"
                  :placeholder="item.placeholder || '请输入' + item.label"
                  :disabled="Boolean(item.disabled)"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!-- 操作按钮 -->
        <div slot="footer" class="dialog-footer">
          <el-button @click="show = false">取 消</el-button>
          <el-button type="primary" @click="submitHandle()">确 定</el-button>
        </div>
      </div>
      <!-- 成功提示 -->
      <div v-if="active === 1">
        <el-result icon="success" title="成功提示" :subTitle="formTitle + '成功'">
          <template slot="extra">
            <el-button type="primary" size="medium" @click="exitHandle"
              >退出</el-button
            >
          </template>
        </el-result>
      </div>
      <!-- 错误提示 -->
      <div v-if="active === 2">
        <el-result icon="error" title="错误提示" :subTitle="formTitle + '失败'">
          <template slot="extra">
            <el-button type="primary" size="medium" @click="changeActive(0)"
              >返回</el-button
            >
            <el-button type="primary" size="medium" @click="exitHandle"
              >退出</el-button
            >
          </template>
        </el-result>
      </div>
    </el-dialog>
  </template>
  <script>
  import { ApiTypePost, ApiTypePut } from "@/api/wms-api"
  import { LoadingMixins } from "@/mixins/LoadingMixins";
  import { tableMixins } from "@/mixins/TableMixins"
  export default {
    name:"addEditFromApiPop",
    mixins:[ LoadingMixins,tableMixins ],
    props: {
      // 编辑行数据
      editRowData:{
        type: Object,
        default: null
      },
      // 操作类型：add/edit
      handleType:{
        type: String,
        default: null
      },
      // 提交事件
      submitForm:{
        type:Function,
        default:null
      },
      // 特殊的【新增】接口，如果没有就走路由下的配置文件
      addSubmitUrl:{
        type: String,
        default: null
      },
      // 特殊的【编辑】接口，如果没有就走路由下的配置文件
      editSubmitUrl:{
        type: String,
        default: null
      }
    },
    data () {
      return {
        currentDtos:this.$store.getters.dtoColumnTypes[this.$route.name],
        active:0,//显示内容：0表单 1成功 2失败
        show:true,
        formTitle:null,//form名称
        formData:{},//表单数据
        formItemData:null,//表单item配置
        formRules: {},//表单验证
      }
    },
    mounted(){
      this.initTitle()
      this.initFormItems()
    },
    methods: {
      // 初始化form名称
      initTitle(){
        if(this.handleType){
          this.formTitle = this.handleType == 'add' ? '新增'+this.$route.name : '编辑'+this.$route.name
        }
      },
      // 初始化表单配置、rules
      initFormItems(){
        let _dtoList_type = this.handleType == 'add' ? 'C' : 'U'
        let _dtoList = this.currentDtos[_dtoList_type].dtoList
        this.formItemData = JSON.parse(JSON.stringify(_dtoList))
        // 编辑格式：特殊处理默认值
        if(this.handleType == 'edit' && this.editRowData){
          this.formData = JSON.parse(JSON.stringify(this.editRowData))
        }else{
          this.formData = {}
        }
        // 表单验证格式化
        this.formRules={}
        _dtoList.forEach(item=>{
          if(item.isRequired){
            this.formRules[item.prop] = [{ required: true, trigger: "blur", message: "不可为空" }]
          }
        })
      },
      // 获取枚举、布尔
      getItemEnums(item){
        let _option = []
        // 布尔
        if(item.apiBaseType == 'boolean'){
          _option = [{
            value: true,
            label: '是'
          },{
            value: false,
            label: '否'
          },]
        }
        if(item.isEnums){
          _option = item.enums_list
        }
        return _option
      },
      // 关闭弹窗
      close() {
        this.show = false
        this.$emit("closePop")
      },
      // 提交表单
      submitHandle(){
        this.$refs.addEditFrom_Ref.validate((valid) => {
          if(this.submitForm){
            this.submitForm(valid,this.formData,this.handleType,this.formItemData,this.formRules)
            return
          }
          this.Loading.addEditApiLoading = true
          if (valid) {
            // 新增
            if(this.handleType == 'add'){
              ApiTypePost(
                this.formData, 
                this.currentDtos.C.actionsUrl
              ).then(res => {
                this.changeActive(1)
              }).catch(err => {
                this.changeActive(2)
              })
            }
            // 编辑
            else{
              ApiTypePut(
                this.formData, 
                this.formData.id, 
                this.currentDtos.U.actionsUrl
              ).then(res => {
                this.changeActive(1)
              }).catch(err => {
                this.changeActive(2)
              })
            }
          } else {
            return false;
          }
        });
      },
      // 结果页退出
      exitHandle(){
        this.close()
        if(this.active == '1')this.oldSkipCount = 1;
        this.show = false
        this.paging()
        this.$nextTick(()=>{
          this.active = 0
        })
      },
      // 更改页面步骤
      changeActive(sta){
        this.active = sta
        this.Loading.addEditApiLoading = false
      },
      // 值更改函数
      changeValue(prop,item,val) {
        this.$emit("changeValue", prop, item, val)
      },
      // 值清除函数
      clearValue(prop,item,val) {
        this.$emit("clearValue", prop, item, val)
      },
    }
  }
  </script>
      
  <style  lang="scss" scoped>
    ::v-deep .el-dialog__header{
      padding:  0 !important;
    }
    ::v-deep .el-row{
      width: 100%;
    }
    ::v-deep .addEditFrom{
      height: calc(100% - 120px);
      overflow: auto;
    }
    ::v-deep .el-form-item__label{
      float: unset;
    }
  
    ::v-deep .el-input,.el-select,.el-input-number{
      width: 100% !important;
    }
  
    .dialog-footer{
      padding-top: 15px;
      text-align: right;
    }
  </style>