<template>
  <el-dialog
    :title="formTitle"
    v-loading="loading"
    v-if="displayDialog.newDialog"
    :visible="true"
    :fullscreen="true"
    :append-to-body="false"
    :modal="false"
    :modal-append-to-body="false"
    :show-close="false"
  >
    <div id="stepsForm">
      <el-steps
        :active="active"
        process-status="finish"
        finish-status="success"
        :align-center="true"
      >
        <el-step
          v-for="(item, index) in stepFilters"
          :key="index"
          :title="item"
        ></el-step>
      </el-steps>
      <curren-Form
        v-if="active == 0"
        class="page1"
        size="medium"
        ref="page1"
        :searchData="CreateFormData"
        :searchForm="CreateForm"
        :searchOptions="Options"
        :searchHandle="editHandle"
        :rules="Rules"
        @changeInput="changeInput"
        @changeSelect="changeSelect"
        @push="DataPush(arguments)"
        @submitForm="editFormClick(arguments)"
      >
      </curren-Form>
      <curren-Form
        v-if="active === 1"
        class="page2"
        size="medium"
        :searchData="CreateFormData"
        :searchHandle="editHandle"
        :rules="Rules"
        @submitForm="editFormClick(arguments)"
      >
        <template>
          <el-form-item class="formTable-box" prop="details" v-if="active == 1">
            <div class="heder">
              <el-button
                v-if="addClick"
                type="primary" 
                @click="openAddNew"
                icon="el-icon-plus" 
                size="mini"
              >添加一行</el-button>

              <el-button 
                v-if="importFormButton"
                type="success" 
                icon="el-icon-download" 
                @click="openImportForm"
                size="mini"
              >导入</el-button>
            </div>
            <currenTable
              :tableData="CreateFormData.details"
              :searchOptions="Options"
              :tableColumns="detailsTableColumns"
              :selectionTable="false"
              @push="detailsDataPush(arguments)"
              @clear="detailsClear(arguments)"
            >
              <template v-if="showDeleteButton">
                <el-table-column
                  label="操作"
                  align="center"
                  fixed="right"
                  width="100px"
                >
                  <template slot-scope="scope">
                    <div class="childTable" @click="childTable($event, scope)">
                      <span>删除</span>
                    </div>
                  </template>
                </el-table-column>
              </template>
            </currenTable>
          </el-form-item>
        </template>
      </curren-Form>
      <curren-Form
        v-if="active === 2"
        size="medium"
        class="page3"
        :searchData="previewFormData"
        :searchForm="CreateForm | formData"
        :searchHandle="editHandle"
        :rules="Rules"
        @submitForm="editFormClick(arguments)"
      >
        <template>
          <el-form-item class="formTable-box" prop="details">
            <currenTable
              :tableData="previewFormData.details"
              :tableColumns="detailsTableColumns | formDataDetails"
              :selectionTable="false"
            >
              <template v-if="showPreviewFormDeleteButton">
                <el-table-column
                  label="操作"
                  align="center"
                  fixed="right"
                  width="100px"
                >
                  <template slot-scope="scope">
                    <div @click="previewChildRemove($event, scope)">
                      <span style="color:red">删除</span>
                    </div>
                  </template>
                </el-table-column>
              </template>
            </currenTable>
          </el-form-item>
        </template>
      </curren-Form>
      <div
        v-if="active === step.length - 1 && pageStatus === 'success'"
        class="page4"
      >
        <el-result
          icon="success"
          title="成功提示"
          :subTitle="formTitle + '成功'"
        >
          <template slot="extra">
            <!-- <el-button type="primary" size="medium" @click="tuoFormPrint"
              >打印托标签</el-button
            >
            <el-button type="primary" size="medium" @click="xbqFormPrint"
              >打印箱标签</el-button
            > -->
            <el-button
              v-for="item in successHandle"
              :key="item.label"
              :type="item.type"
              size="medium"
              @click="successClick(item.click())"
              >{{ item.label }}</el-button
            >
            <el-button type="primary" size="medium" @click="close(1)"
              >退出</el-button
            >
          </template>
        </el-result>
      </div>
      <div
        v-if="active === step.length - 1 && pageStatus === 'error'"
        class="page4"
      >
        <el-result icon="error" title="错误提示" :subTitle="formTitle + '失败'">
          <template slot="extra">
            <el-button type="primary" size="medium" @click="close(1)"
              >退出</el-button
            >
          </template>
        </el-result>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import currenForm from "@/components/currenForm"
import currenTable from "@/components/currenTable"
export default {
  name: 'stepsForm',
  components: {
    currenForm,
    currenTable
  },
  watch: {
    active (val) {
      if (val != 0) {
        this.editHandle=[
          { label: "上一步", name: "cancel" },
          { label: "下一步", type: "primary", name: "determine" },
        ];
      } else {
        if(this.hideFirstActiveCancel){
          this.editHandle=[
            { label: "下一步", type: "primary", name: "determine" },
          ];
        }else{
          this.editHandle=[
            { label: "取消", name: "cancel" },
            { label: "下一步", type: "primary", name: "determine" },
          ];
        }
      }
    },
    stepArray(newVal, oldVal){
      this.step = newVal
    }
  },
  filters: {
    formData (val) {
      let data = JSON.parse(JSON.stringify(val))
      val.forEach((key, index) => {
        data[index].disabled = "true"
        delete data[index].focus
        if (key.type == "autocomplete" || key.type == "import") {
          data[index].type = "input"
        }
      });
      return data
    },
    formDataDetails (val) {
      let data = JSON.parse(JSON.stringify(val))
      val.forEach((key, index) => {
        data[index].disabled = true
        delete data[index].focus
        delete data[index].rules
        if (key.type == "autocomplete" || key.type == "import") {
          delete data[index].type
        } else if (key.type == "objectAutocomplete") {
          data[index].type = "object"
        } else if (key.prop == "containerCode" && key.type == "input") {
          data[index].disabled = false
        } else if (key.isChange) {
          // 针对第三步预览特殊情况处理
          data[index].disabled = false
        }
      });
      return data
    }
  },
  props: {
    //名称
    formTitle: {
      type: String,
      default: ''
    },
    //是否弹窗
    displayDialog: {
      type: Object,
      default: () => {
        return {
          newDialog: false
        }
      }
    },
    //主表提交数据
    CreateFormData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    //主表显示form
    CreateForm: {
      type: Array,
      default: () => {
        return []
      }
    },
    //预览数据
    previewFormData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    //检验
    Rules: {
      type: Object,
      default: () => {
        return {}
      }
    },
    //下拉选择
    Options: {
      type: Object,
      default: () => {
        return {}
      }
    },
    //子表table显示
    detailsTableColumns: {
      type: Array,
      default: () => {
        return []
      }
    },
    //子表提交数据
    childTableData: {
      type: Array,
      default: () => {
        return []
      }
    },
    //成功后的操作
    successHandle: {
      type: Array,
      default: () => {
        return []
      }
    },
    //步骤标题
    stepArray: {
      type: Array,
      default: () => {
        return ["总体信息", "明细", "预览", "结果"]
      }
    },
    //添加一行
    addClickButton: {
      type: Boolean,
      default: () => {
        return true
      }
    },
    //导入按钮
    importFormButton: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    //删除行记录
    isShowDeleteButton: {
      type: Boolean,
      default: () => {
        return true
      }
    },
    // 隐藏第一步骤的取消按钮
    isHideFirstActiveCancel:{
      type: Boolean,
      default: () => {
        return false
      }
    },
    // 预览视图显示删除按钮
    showPreviewFormDeleteButton:{
      type: Boolean,
      default: () => {
        return false
      }
    }
  },
  computed: {
    stepFilters () {
      let stepFilters = []
      const routeName = this.$route.meta.title
      this.step.forEach(key => {
        stepFilters.push(routeName.concat(key))
      })
      return stepFilters
    },
  },
  data () {
    return {
      active: 0,
      formReveal: 1,
      activeStep: 1,
      pageStatus: '',
      addClick: this.addClickButton,//添加一行按钮
      importForm:this.importFormButton,//导入按钮
      showDeleteButton: this.isShowDeleteButton,//操作-删除按钮
      hideFirstActiveCancel:this.isHideFirstActiveCancel,// 隐藏第一步骤的取消按钮
      loading: false,
      session: null,
      step: this.stepArray,
      editHandle: [
        { label: "取消", name: "cancel" },
        { label: "下一步", type: "primary", name: "determine" },
      ],
    }
  },
  mounted () {
    this.session = JSON.parse(JSON.stringify(this.CreateFormData))
    if(this.hideFirstActiveCancel){
      this.editHandle=[
        { label: "下一步", type: "primary", name: "determine" },
      ];
    }
  },
  methods: {
    //结束退出
    close (val) {
      this.active = 0
      //   const pageRef = this.Refs[1]
      const data = JSON.parse(JSON.stringify(this.session))
      this.$emit('close', data, val)
    },
    //autoComplete主表
    DataPush (val) {
      this.$emit("DataPush", val)
    },
    //autoComplete子表
    detailsDataPush (val) {
      this.$emit("detailsDataPush", val)
    },
    detailsClear(val) {
      this.$emit("detailsClear", val)
    },
    // //打印托标签
    // tuoFormPrint () {
    //   this.$emit('tuoFormPrint')
    // },
    // //打印箱标签
    // xbqFormPrint () {
    //   this.$emit('xbqFormPrint')
    // },
    successClick (val) {
      this.loading = true
      val.then(res => {
        this.loading = false
      }, reason => {
        this.loading = false
      }).catch(err=>{
        this.loading = false
      })
    },
    editFormClick (val) {
      //   Moment(this.CreateFormData.arriveTime).format()
      // if (val[0] == 0) {
      if (val[2].name == "cancel") {
        if (this.active == 0) {
          // debugger
          //   this.active = ''
          this.close(0)
        } else {
          if (this.active == 2) {
            this.active = this.active - this.activeStep
          } else {
            this.active--
          }
        }
      } else {
        val[1].validate((valid) => {
          if (valid) {
            const parent = this.$parent
            if (this.active < this.step.length - 1) {
              this.loading = true
              if (this.active == this.step.length - 2) {
                parent.stepsSubmit().then(res => {
                  if (res == '质检校验返回') {
                    this.loading = false
                  } else {
                    this.pageStatus = 'success'
                    this.active++
                    this.loading = false
                  }
                }, reason => {
                  this.loading = false
                  if(reason=="return")return
                  this.pageStatus = 'error'
                  this.active++
                  this.loading = false
                }).catch(err=>{
                  this.loading = false
                })
              } else if (this.active == this.step.length - 3) {
                parent.PalletlFunction().then(res => {
                  // 针对特殊环境 跳过步骤 直接到最后完成
                  if (res == '质检任务跳过详情') {
                    parent.stepsSubmit().then(res => {
                      this.pageStatus = 'success'
                      this.active = this.active + 2
                      this.loading = false
                    }, reason => {
                      this.pageStatus = 'error'
                      this.active = this.active + 2
                      this.loading = false
                    }).catch(err=>{
                      this.loading = false
                    })
                  } else {
                    this.active++
                  }
                  this.loading = false
                }, reason => {
                  this.loading = false
                }).catch(err=>{
                  this.loading = false
                })
              } else {
                parent.stepsHandelOne().then(res => {
                  if (res) {
                    this.addClick = res.open
                    this.active = this.active + res.index
                    this.activeStep = res.index
                  } else {
                    this.activeStep = 1
                    this.active++
                  }
                  this.loading = false
                }, reason => {
                  this.loading = false
                }).catch(err=>{
                  this.loading = false
                })
              }
            }
          } else {
            this.$errorMsg('请检查表单')
          }
        })
      }
    },
    //添加子表
    openAddNew () {
      const parent = this.$parent
      parent.openAddNew()
    },
    // 导入
    openImportForm(){
      const parent = this.$parent
      parent.openImportFormHandle()
      // this.displayDialog.importDialog = true
    },
    childTable (e, val) {
      const parent = this.$parent
      parent.childTable(e, val)
    },
    changeInput(prop,val){
      this.$emit("changeInput", prop, val)
    },
    changeSelect(prop,val){
      this.$emit("changeSelect", prop, val)
    },
    //预览步骤删除操作（第三步）
    previewChildRemove(e, val) {
      this.$confirm('您确定删除吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
          this.previewFormData.details.splice(val.$index, 1)
          // this.$emit("removePreviewFormRow",this.previewFormData)
      }).catch(() => {

      });
    },
  }
}
</script>
<style lang="scss" scoped>
@import "./style/index.scss";
</style>