<template>
  <div class="container">
    <el-card shadow="always" class="card">
      <template #header>
        <p>{{ config.customModel ? config.customModel.name : '办理' }}</p>
      </template>

      <template>
        <div class="steps">
          <el-steps :space="120" finish-status="success" align-center>
            <el-step :title="node.name" status="finish" icon="el-icon-edit"></el-step>
            <el-step v-for="nextNode in node.nextNodes"
                     :key="nextNode.id"
                     :title="nextNode.name"
                     icon="el-icon-right"
                     status="wait"></el-step>
          </el-steps>
        </div>

        <el-divider></el-divider>

        <div class="form-container">
          <template v-if="device === 'desktop'">
            <DesktopForm :device="device"
                         ref="desktopForm"
                         :sub-form="subConfig"
                         :fields="fields"
                         :original-form="form"
                         :readable="readableFields"
                         :file-list="fileList"
                         :script-content="scriptContent"
                         :writeable="writeableFields"></DesktopForm>
          </template>
          <template v-else>
            <MobileForm :device="device"
                        ref="mobileForm"
                        :sub-form="subConfig"
                        :fields="fields"
                        :original-form="form"
                        :readable="readableFields"
                        :file-list="fileList"
                        :script-content="scriptContent"
                        :writeable="writeableFields"></MobileForm>
          </template>
        </div>
      </template>


      <div class="btns" ref="btns">
        <el-button type="primary" size="small" @click="submit">保存并流转 <i class="el-icon-right"></i></el-button>
      </div>
    </el-card>

    <el-backtop></el-backtop>
  </div>
</template>

<script>
import DesktopForm from "./DesktopForm.vue";
import MobileForm from "./MobileForm.vue";
import { preConfig, preDeal, create, fieldConfig, getNextNodeUsers, checkIsThroughNode } from "@/api/flow"
import { deepCopy } from "@/utils";
export default {
  components: {
    DesktopForm,
    MobileForm
  },
  data() {
    return {
      info: [],
      config: {},
      subConfig: new Map(),

      form: {},
      fileList: {}
    }
  },
  methods: {
    generateForm(object,fields) {
      fields.forEach(field => {
        if(field.type === 'file') {
          this.fileList[field.name] = []
        }
        if(field.type === 'relation') {
          object[field.name] = [{}]

          this.generateForm(object[field.name][0], this.subConfig.get(field.sub_custom_model_id)?.customModel?.fields)
        } else {
          object[field.name] = ""
        }
      })
    },
    async getConfig() {
      const loading = this.$loading({
        lock: true,
        text: '拼命加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)'
      });
      try {
        const res = await preConfig(this.$route.query.module_id)
        const { fields } = res?.customModel;
        let subFormRequest = []
        const getSubForm = (id) => {
          subFormRequest.push(fieldConfig(id))
        }
        fields.forEach(field => {
          if(field.sub_custom_model_id) {
            getSubForm(field.sub_custom_model_id)
          }
        })
        const subConfigs = await Promise.all(subFormRequest)
        subConfigs.forEach(sub => {
          if(sub.customModel?.id) {
            this.subConfig.set(sub.customModel?.id, sub)
          }
        })
        this.config = res;
        this.generateForm(this.form, fields)
        this.form = Object.assign({},this.form)
        loading.close()
      } catch (err) {
        console.error(err)
        this.$message.error("配置失败")
        loading.close()
      }
    },

    async submit() {
      if(this.device === 'desktop') {
        console.log(this.$refs['desktopForm'].form)
        let copyForm = deepCopy(this.$refs['desktopForm'].form)
        let copyFile = deepCopy(this.$refs['desktopForm'].file)
        for (let [key, value] of Object.entries(copyFile)) {
          if (copyForm.hasOwnProperty(key)) {
            copyForm[key] = value.map(i => i.response?.id)?.toString()
          }
        }
        // for (let key in copyForm) {
        //   if(copyForm[key] instanceof Array && copyForm[key][0]) {
        //     let formatObj = {}
        //     let subKeys = Object.keys(copyForm[key][0])
        //     subKeys.forEach(key => {
        //       formatObj[key] = []
        //     })
        //     copyForm[key].forEach(item => {
        //       subKeys.forEach(subKey => {
        //         formatObj[subKey].push(item[subKey])
        //       })
        //     })
        //     delete formatObj['_X_ROW_KEY']
        //     copyForm[key] = formatObj
        //
        //   }
        // }

        try {
          const res = await create(copyForm,this.$route.query.module_id)
          await getNextNodeUsers({
            id: res.id,
            next_node_id: this.config?.currentNode?.nextNodes[0]?.id
          })
        } catch(err) {
          console.error(err)
        }
      }
    }
  },
  computed: {
    device() {
      return this.$store.state.app.device
    },
    fields() {
      return this.config?.customModel?.fields || []
    },
    readableFields() {
      return this.config?.currentNode?.readable || []
    },
    writeableFields() {
      return this.config?.currentNode?.writeable || []
    },
    node() {
      return this.config?.currentNode || {}
    },
    scriptContent() {
      if(this.config?.customModel?.js) {
        return this.config?.customModel?.js
      }
    }
  },
  created() {
    this.getConfig()
  },
  mounted() {
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-card__header {

}
.container {
  padding: 20px;

  .card {
    position: relative;
  }
  .btns {

    margin-top: 10px;
    position: sticky;
    bottom: 20px;
  }
}
.form-container {
}
@media (max-width: 768px) {
  .container {
    padding: 10px;
  }
}
</style>
