<script>
import {deepCopy} from "@/utils";
import formBuilder from "@/utils/formBuilder";
import {PopupManager} from "element-ui/lib/utils/popup";
import request from '@/utils/request'
import moment from "moment/moment";
import {defaultModalSize} from "@/settings";
import {getToken} from '@/utils/auth'
export default {
  props: {
    config: {
      type: Object
    },
    isFirstNode: {
      type: Boolean,
      default: true,
    },
    readable: {
      type: Array,
      default: () => [],
      required: true,
    },
    writeable: {
      type: Array,
      default: () => [],
      required: true,
    },
    originalForm: {
      type: Object,
      default: () => ({}),
      required: true,
    },
    subForm: {
      type: Map,
      default: () => new Map(),
    },
    device: {
      type: String,
      default: "desktop",
      required: true,
    },
    fields: {
      type: Array,
      default: () => [],
      required: true,
    },
    scriptContent: String,
    rules: {
      type: Object,
      default: () => ({}),
    },
    subRules: {
      type: Object,
      default: () => ({}),
    },
    logs: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // 脚本注入控制的modal弹窗
      defaultModalSize,
      zIndex: PopupManager.nextZIndex(),
      isShowModal: false,
      modalRender: () => {},

      action: process.env.VUE_APP_BASE_API,
      form: {},

      jointlySignLog: [], // 所有会签log记录
      datetimeFormat: 'yyyy-MM-dd HH:mm',
      copyShortcuts: [
        {
          text: "一年前",
          onClick(picker) {
            picker.$emit(
              "pick",
              moment().subtract(1, "years").toDate()
            );
          },
        },
        {
          text: "一月前",
          onClick(picker) {
            picker.$emit(
              "pick",
              moment().subtract(1, "months").toDate()
            );
          },
        },
        {
          text: "一周前",
          onClick(picker) {
            picker.$emit(
              "pick",
              moment().subtract(1, "weeks").toDate()
            );
          },
        },
        {
          text: "今天",
          onClick(picker) {
            picker.$emit("pick", new Date());
          },
        },
        {
          text: "一周后",
          onClick(picker) {
            picker.$emit("pick", moment().add(1, "weeks").toDate());
          },
        },
        {
          text: "一月后",
          onClick(picker) {
            picker.$emit("pick", moment().add(1, "months").toDate());
          },
        },
        {
          text: "一年后",
          onClick(picker) {
            picker.$emit("pick", moment().add(1, "years").toDate());
          },
        },
      ],
      shortcuts: [
        {
          text: "一年前",
          onClick(picker) {
            picker.$emit(
              "pick",
              moment().subtract(1, "years").toDate()
            );
          },
        },
        {
          text: "一月前",
          onClick(picker) {
            picker.$emit(
              "pick",
              moment().subtract(1, "months").toDate()
            );
          },
        },
        {
          text: "一周前",
          onClick(picker) {
            picker.$emit(
              "pick",
              moment().subtract(1, "weeks").toDate()
            );
          },
        },
        {
          text: "今天",
          onClick(picker) {
            picker.$emit("pick", new Date());
          },
        },
        {
          text: "一周后",
          onClick(picker) {
            picker.$emit("pick", moment().add(1, "weeks").toDate());
          },
        },
        {
          text: "一月后",
          onClick(picker) {
            picker.$emit("pick", moment().add(1, "months").toDate());
          },
        },
        {
          text: "一年后",
          onClick(picker) {
            picker.$emit("pick", moment().add(1, "years").toDate());
          },
        },
      ],
      flows: {},
    };
  },
  methods: {
    getToken,
    request,
    async validate() {
      const $elForm = this.$refs['elForm']
      if ($elForm) {
        await this.$refs['elForm'].validate()
      }
      let subFormName = this.fields.filter(i => i.type === 'relation').map(i => i.name)
      for (let i = 0;i < subFormName.length;i++) {
        let $subForm = this.$refs[`subForm-${subFormName[i]}`]
        if ($subForm) {
          const errMap = await this.$refs[`subForm-${subFormName[i]}`].validate(true)
          if (errMap) {
            throw new Error(errMap)
          }
        }
      }
    },
  },
  computed: {},
  watch: {
    info(newVal) {
      let keys = newVal.map((i) => i.name);
      keys.forEach((key) => {
        this.form[key] = "";
      });
    },
    originalForm(newVal) {
      this.form = deepCopy(newVal);
    },
    scriptContent(newVal) {
      if (newVal) {
        try {
          new Function(newVal).bind(this)();
        } catch (err) {
          console.error(err);
        }
      }
    },
    isShowModal(newVal) {
      if (newVal) {
        this.zIndex = PopupManager.nextZIndex();
      }
    },
    logs: {
      handler: function (newVal) {
        if (newVal && newVal instanceof Array && newVal.length > 0) {
          this.jointlySignLog = newVal.filter(log => {
            try {
              JSON.parse(log.data)
              return log.is_jointly_sign && /custom_field_id/g.test(log.data)
            } catch (e) {
              return false
            }
          })
        } else {
          this.jointlySignLog = []
        }
      },
      immediate: true
    }
  },
  render(h) {
    const authFields = this.fields.map((field) => ({
      ...field,
      _readable:
        this.readable.indexOf(field.id) !== -1 || field.type === "label",
      _writeable: this.writeable.indexOf(field.id) !== -1,
    }));
    authFields.unshift({
      name: "flow_title",
      label: "工作名称",
      type: "text",
      gs_x: 0,
      gs_y: 0,
      gs_width: 12,
      gs_height: 1,
      label_show: 1,
      _readable: !this.isFirstNode,
      _writeable: this.isFirstNode,
    });
    return h("div", [
      h(
        "el-form",
        {
          ref: "elForm",
          class: "form",
          props: {
            model: this.form,
            "label-position": "right",
            "label-width": "120px",
            rules: this.rules,
            "inline-message": true,
          },
        },
        authFields.map((field) => formBuilder.bind(this)(this.device, field, h))
      ),
      // 用于编写脚本中弹窗
      h(
        "vxe-modal",
        {
          props: {
            zIndex: this.zIndex,
            value: this.isShowModal,
            height: defaultModalSize.height,
            width: defaultModalSize.width,
            resize: true,
            transfer: true,
            "show-zoom": true,
            "esc-closable": true,
          },
          on: {
            input: (e) => {
              this.isShowModal = e;
            },
          },
        },
        [this.modalRender.bind(this)(h)]
      ),
    ]);
  },
  created() {},
};
</script>

<style scoped lang="scss">
.form {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
}
::v-deep .el-form-item {
  border: 1px solid #dee2e6;
  padding: 8px 12px;
  margin: -1px 0 0 -1px;
}
::v-deep .el-form-item__content {
}
::v-deep .el-radio, .el-radio__input {
  line-height: 1.5;
}
</style>
