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

      <template>
        <div class="steps" v-if="!/\/detail/.test($route.path)">
          <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>

          <el-divider></el-divider>

        </div>

        <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 v-if="/\/detail/.test($route.path)" style="margin-top: 10px">
        <div>流转记录</div>
        <vxe-table
          ref="table"
          stripe
          keep-source
          show-overflow
          :column-config="{ resizable: true }"
          :print-config="{}"
          :export-config="{}"
          :custom-config="{ mode: 'popup' }"
          :data="config.logs || []"
        >
          <vxe-column type="seq" width="58" align="center" title="编号"/>
          <vxe-column title="节点名称" align="center" field="node.name"></vxe-column>
          <vxe-column title="办理状态" field="status_label"></vxe-column>
          <vxe-column title="承办人员" field="user.name"></vxe-column>
          <vxe-column title="流转时间" field="created_at"></vxe-column>
          <vxe-column title="退回原因" field="reason"></vxe-column>
          <vxe-column title="办理时间" field="updated_at"></vxe-column>
          <vxe-column title="耗时"></vxe-column>
        </vxe-table>
      </div>

      <div class="btns" ref="btns">
        <template v-if="!/\/detail/.test($route.path)">
          <el-button
            v-if="$route.query.flow_id"
            icon="el-icon-arrow-left"
            type="danger"
            size="small"
            @click=""
          >退回</el-button
          >
          <el-button
            v-if="$route.query.flow_id"
            icon="el-icon-caret-right"
            type="primary"
            plain
            size="small"
            @click=""
          >部门内转办</el-button
          >
          <el-button
            v-if="$route.query.flow_id"
            icon="el-icon-document-add"
            type="info"
            size="small"
            @click="submit('only-submit')"
          >暂存不流转</el-button
          >
          <el-button type="primary" size="small" @click="submit('assign')"
          >保存并流转 <i class="el-icon-right"></i
          ></el-button>
          <el-button
            v-if="!$route.query.flow_id"
            type="info"
            size="small"
            @click="$router.go(-1)"
          >返回</el-button
          >
        </template>
        <template v-else>
          <el-button
            plain
            size="small"
            @click="$router.go(-1)"
          >返回</el-button
          >
          <el-button
            plain
            size="small"
          >打印</el-button
          >
          <el-button
            plain
            size="small"
          >打印(带审批记录)</el-button
          >
          <el-button
            plain
            size="small"
          >下载附件</el-button
          >
        </template>
      </div>
    </el-card>

    <assign
      ref="assign"
      :visible.sync="isShowAssign"
      :config="config"
      :result="result"
    ></assign>

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

<script>
import DesktopForm from "./DesktopForm.vue";
import MobileForm from "./MobileForm.vue";
import assign from "./components/assign.vue";
import { create, deal, fieldConfig, preConfig, preDeal, view } from "@/api/flow";
import { deepCopy } from "@/utils";

export default {
  components: {
    DesktopForm,
    MobileForm,
    assign,
  },
  data() {
    return {
      isShowAssign: false,
      info: [],
      config: {},
      subConfig: new Map(),

      form: {},
      result: {},
      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)",
      });
      //路由为detail为详情
      if(/\/detail/.test(this.$route.path) && this.$route.query.flow_id) {
        try {
          const res = await view(this.$route.query.flow_id);
          console.log('view',res)
          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);
          const { data } = res?.flow;
          for (let key in data) {
            try {
              let jsonObj = JSON.parse(data[key]);
              if (this.form.hasOwnProperty(key)) {
                this.form[key] = jsonObj;
              }
              if (this.fileList.hasOwnProperty(key)) {
                this.fileList[key] = jsonObj.map((i) => ({
                  name: i.name,
                  url: i.url,
                  response: i,
                }));
              }
            } catch (err) {
              if (this.form.hasOwnProperty(key)) {
                this.form[key] = data[key];
              }
            }
          }
          this.fileList = Object.assign({}, this.fileList);
          loading.close();
        } catch (err) {
          console.error(err);
          this.$message.error("配置失败");
          loading.close();
        }
      } else if (!this.$route.query.flow_id) {
        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();
        }
      } else {
        try {
          const res = await preDeal(this.$route.query.flow_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);
          const { data } = res?.flow;
          for (let key in data) {
            try {
              let jsonObj = JSON.parse(data[key]);
              if (this.form.hasOwnProperty(key)) {
                this.form[key] = jsonObj;
              }
              if (this.fileList.hasOwnProperty(key)) {
                this.fileList[key] = jsonObj.map((i) => ({
                  name: i.name,
                  url: i.url,
                  response: i,
                }));
              }
            } catch (err) {
              if (this.form.hasOwnProperty(key)) {
                this.form[key] = data[key];
              }
            }
          }
          this.fileList = Object.assign({}, this.fileList);
          loading.close();
        } catch (err) {
          console.error(err);
          this.$message.error("配置失败");
          loading.close();
        }
      }
    },

    async submit(type) {
      let copyForm,copyFile;
      if (this.device === "desktop") {
        copyForm = deepCopy(this.$refs["desktopForm"].form);
        copyFile = deepCopy(this.$refs["desktopForm"].file);
      } else {
        copyForm = deepCopy(this.$refs["mobileForm"].form);
        copyFile = deepCopy(this.$refs["mobileForm"].file);
      }
      console.log(copyForm,copyFile)
      for (let [key, value] of Object.entries(copyFile)) {
        if (copyForm.hasOwnProperty(key)) {
          copyForm[key] = value.map((i) => i.response?.id)?.toString();
        }
      }
      copyForm["current_node_id"] = this.config.currentNode.id;

      try {
        let callback;
        switch (type) {
          case "only-submit":
            if (this.$route.query.flow_id) {
              copyForm["temporary_save"] = 1;
            }
            callback = () => this.$router.push("/flow/list/todo");
            break;
          case "assign":
            if (this.$route.query.flow_id) {
              copyForm["temporary_save"] = 0;
            }
            callback = () => (this.isShowAssign = true);
            break;
        }
        if (this.$route.query.flow_id) {
          copyForm.id = this.$route.query.flow_id;
          const { flow, is_last_handled_log } = await deal(
            this.$route.query.flow_id,
            copyForm
          );
          this.result = flow;
        } else {
          this.result = await create(this.$route.query.module_id, copyForm);
        }
        callback();
      } catch (err) {
        console.error(err);
      }
    },
  },
  computed: {
    device() {
      return this.$store.state.app.device;
    },
    fields() {
      return this.config?.customModel?.fields || [];
    },
    readableFields() {
      return /\/detail/.test(this.$route.path) ? this.fields?.map(i => i.id) : (this.config?.currentNode?.readable || []);
    },
    writeableFields() {
      return this.config?.currentNode?.writeable || [];
    },
    node() {
      return this.config?.currentNode || {};
    },
    scriptContent() {
      if (this.config?.customModel?.view_js && this.$route.query.flow_id) {
        return this.config?.customModel?.view_js;
      } else if (this.config?.customModel?.js && !this.$route.query.flow_id) {
        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 {
    display: flex;
    justify-content: center;
    margin-top: 10px;
    position: sticky;
    bottom: 20px;
    flex-wrap: wrap;
  }
}
.form-container {
}
@media (max-width: 768px) {
  .container {
    padding: 10px;
  }
}
</style>
