<template>
  <div>
    <!-- <el-button type="primary" @click="test">Submit</el-button> -->
    <div class="designer-box" id="containt" style="margin-bottom: 0">
      <v-form-designer ref="designer" :reportTemplate.sync="reportTemplate"
      :designer-config="designerConfig" :field-list-data="fieldListData"
      @field-widget-used="handleFWU" @field-widget-removed="handleFWR"
      @form-json-updated="handleFJU" @reflushTemplateList="reflushTemplateList"
      v-if="showDesinger" :readonly="readonly" :columnFlag="columnFlag"
      :sourceData="sourceData" sourceData:="sourceData" @customConfirm="customConfirm" />
    </div>
    <!--
    <el-tabs v-model="activeName" class="tab-boxCard tabCard-sty1" v-if="showDesinger">
      <el-tab-pane label="设计器" name="first">

      </el-tab-pane>
    </el-tabs> -->
  </div>
</template>

<script>
import { loadExtension } from "@base/components/xform/extension/extension-loader";

loadExtension();
import VFormDesigner from "@base/components/xform/form-designer/index.vue";
import { deepClone, overwriteObj } from "@base/components/xform/utils/util";
import { formFieldMapping } from "./formFieldMapping";

export default {
  name: "vform-designer:edit",
  props: {
    formCode: String,
    readonly: Boolean,
    formTemplate: Object,
    widgetList: Array,
    columnFlag: Boolean,
    sourceData: Object,
    jsonFlag: Boolean,
  },
  components: {
    VFormDesigner,
  },
  data() {
    return {
      formJson: {},
      formData: {},
      optionData: {},
      reportTemplate: {},
      showDesinger: false,
      activeName: "first",
      showRequestaccessList: false,
      showFunctionScriptList: false,
      designerConfig: {
        componentLib: false,
        formTemplates: false,
        eventCollapse: true,
        metadataLib: true,
        logoHeader: false,
        exportCodeButton: false,
        generateSFCButton: false,
        toolbarMaxWidth: 300,
      },
      fieldListData: {},
      layoutId: null,
      formOptionData: {},

      meteFieldsResult: null,
      usedFieldNames: {},
      entity: null,
      entityLabel: null,
    };
  },
  computed: {},
  watch: {
    activeName(val) {
      if (this.showRequestaccessList === false && val == "second") {
        this.showRequestaccessList = true;
      }
    },
  },
  mounted() {
    this.getTemplate();
  },
  methods: {
    test() {
      let that = this;
      let designer = this.$refs.designer;
      let json = designer.getFormJson();
      designer.setFormJson(this.formJson);
    },
    getTemplate() {
      if (this.columnFlag) {
        this.reportTemplate = this.formTemplate;
        this.showDesinger = true;
        this.$nextTick(() => {
          let formJson = this.$baseLodash.cloneDeep({
            widgetList: this.widgetList,
            formConfig: {},
          });
          this.$refs.designer.setFormJson(formJson);
        });
      } else if (this.jsonFlag && this.formTemplate) {
        this.reportTemplate = this.$baseLodash.cloneDeep(this.formTemplate);
        this.showDesinger = true;
        this.$nextTick(() => {
          this.$refs.designer.setFormJson(this.reportTemplate.formViewContent);
        });
      } else {
        this.$http({
          aes: true,
          url: USER_PREFIX + `/formTemplate/getByFormCode`,
          method: `post`,
          data: {
            stringOne: this.formCode,
          },
          isLoading: true,
          modalStrictly: true,
          success: (res) => {
            if (!res.objx) {
              this.$baseAlert(this.$t1("获取报表模板失败"));
              return;
            }
            let reportTemplate = res.objx || {};
            this.reportTemplate = reportTemplate;
            this.showDesinger = true;
            this.$nextTick(() => {
              this.$refs.designer.setFormJson(reportTemplate.formViewContent);
            });
          },
        });
      }
    },
    loadFieldListData(res) {
      this.entity = "User";
      this.entityLabel = "用户";
      /*res = {
        "code": 200, "error": null, "message": "success", "data": {
          "subFormList": [],
          "storageSetting": [{"cloudStorage": "false"}],
          "fieldList": [
            /!*{
              "name": "userId",
              "label": "用户Id主键",
              "type": "PrimaryKey",
              "required": "1"
            }, {"name": "createdOn", "label": "创建时间", "type": "DateTime", "required": "1"}, {
              "searchDialogWidth": "520px",
              "name": "createdBy",
              "label": "创建用户",
              "type": "Reference",
              "required": "1"
            },*!/ {
              "name": "modifiedOn",
              "label": "最近修改时间",
              "type": "DateTime",
              "required": "0"
            }, /!*{
              "searchDialogWidth": "520px",
              "name": "modifiedBy",
              "label": "修改用户",
              "type": "Reference",
              "required": "0"
            }, {
              "searchDialogWidth": "520px",
              "name": "ownerUser",
              "label": "所属用户",
              "type": "Reference",
              "required": "1"
            }, {
              "searchDialogWidth": "520px",
              "name": "ownerDepartment",
              "label": "所属部门",
              "type": "Reference",
              "required": "1"
            }, {
              "searchDialogWidth": "510px",
              "name": "departmentId",
              "label": "部门",
              "type": "Reference",
              "required": "1"
            },*!/ {"name": "userName", "label": "用户名称", "type": "Text", "required": "1"}, {
              "name": "loginPwd",
              "label": "登录密码",
              "type": "Password",
              "required": "1"
            }, {"name": "loginName", "label": "登录账号名", "type": "Text", "required": "1"}, {
              "name": "jobTitle",
              "label": "职务",
              "type": "Option",
              "required": "1"
            }, {"name": "roles", "label": "权限角色", "type": "ReferenceList", "required": "0"}, {
              "name": "disabled",
              "label": "是否禁用",
              "type": "Boolean",
              "required": "1"
            }, {"name": "mobilePhone", "label": "手机号", "type": "Text", "required": "0"}, {
              "name": "email",
              "label": "邮箱",
              "type": "Text",
              "required": "0"
            },/!* {"name": "ownerTeam", "label": "所属团队", "type": "ReferenceList", "required": "0"}, {
              "name": "avatar",
              "label": "头像",
              "type": "Picture",
              "required": "0"
            },*!/ {"name": "dingTalkUserId", "label": "钉钉用户ID", "type": "Text", "required": "0"}]
        }
      };*/
      res = {
        code: 200,
        error: null,
        message: "success",
        data: {
          subFormList: [{ name: "Jinjilianxiren", label: "员工-紧急联系人" }],
          storageSetting: [{ cloudStorage: "false" }],
          fieldList: [
            /*{
            "name": "yuangongdanganId",
            "label": "id主键",
            "type": "PrimaryKey",
            "required": "1"
          },*/ {
              name: "createdOn",
              label: "创建时间",
              type: "DateTime",
              required: "1",
            },
            /*{
            "searchDialogWidth": "520px",
            "name": "createdBy",
            "label": "创建用户",
            "type": "Reference",
            "required": "1"
          },*/ {
              name: "modifiedOn",
              label: "最近修改时间",
              type: "DateTime",
              required: "0",
            },
            /*{
            "searchDialogWidth": "520px",
            "name": "modifiedBy",
            "label": "修改用户",
            "type": "Reference",
            "required": "0"
          }, {
            "searchDialogWidth": "520px",
            "name": "ownerUser",
            "label": "所属用户",
            "type": "Reference",
            "required": "1"
          }, {
            "searchDialogWidth": "520px",
            "name": "ownerDepartment",
            "label": "所属部门",
            "type": "Reference",
            "required": "1"
          },*/ {
              name: "gonghao",
              label: "工号",
              type: "Text",
              required: "0",
              maxLength: "200",
            },
            {
              name: "xingming",
              label: "姓名",
              type: "Text",
              required: "1",
              maxLength: "200",
            },
            /*{
            "searchDialogWidth": "520px",
            "name": "bumen",
            "label": "部门",
            "type": "Reference",
            "required": "1"
          },*/ {
              name: "gangwei",
              label: "岗位",
              type: "Text",
              required: "1",
              maxLength: "200",
            },
            /*{
            "searchDialogWidth": "520px",
            "name": "yuangongchengyuan",
            "label": "员工成员",
            "type": "Reference",
            "required": "0"
          },*/ {
              name: "shenfenzhenghao",
              label: "身份证号",
              type: "Text",
              required: "0",
              maxLength: "200",
            },
            { name: "xingbie", label: "性别", type: "Option", required: "1" },
            {
              name: "chushengriqi",
              label: "出生日期",
              type: "Date",
              required: "0",
            },
            /*{
            "name": "jiguan",
            "label": "籍贯",
            "type": "AreaSelect",
            "areaDataType": "2",
            "required": "0"
          },*/ {
              name: "hujisuozaidi",
              label: "户籍所在地",
              type: "Text",
              required: "0",
              maxLength: "200",
            },
            { name: "hujileixing", label: "户籍类型", type: "Option", required: "0" },
            {
              name: "minzu",
              label: "民族",
              type: "Text",
              required: "0",
              maxLength: "200",
            },
            {
              name: "hunyinzhuangtai",
              label: "婚姻状态",
              type: "Option",
              required: "0",
            },
            {
              name: "zhengzhimianmao",
              label: "政治面貌",
              type: "Option",
              required: "0",
            },
            /*{
            "name": "yuangongzhaopian",
            "label": "员工照片",
            "type": "Picture",
            "required": "0"
          },*/ {
              name: "pinyongxingshi",
              label: "聘用形式",
              type: "Option",
              required: "0",
            },
            {
              name: "yuangongzhuangtai",
              label: "员工状态",
              type: "Option",
              required: "1",
            },
            {
              name: "canjiagongzuoriqi",
              label: "参加工作日期",
              type: "Date",
              required: "0",
            },
            {
              name: "ruzhiriqi",
              label: "入职日期",
              type: "Date",
              required: "1",
            },
            {
              name: "shiyongqitianshu",
              label: "试用期天数（天）",
              type: "Integer",
              required: "1",
            },
            { name: "zhuanzhengriqi", label: "转正日期", type: "Date", required: "0" },
            {
              min: "-999999999",
              max: "999999999",
              precision: "2",
              name: "shiyongqixinzi",
              label: "试用期薪资",
              type: "Money",
              required: "0",
            },
            {
              min: "-999999999",
              max: "999999999",
              precision: "2",
              name: "zhengshixinzi",
              label: "正式薪资",
              type: "Money",
              required: "0",
            },
            /*{
            "searchDialogWidth": "520px",
            "name": "zhijieshangji",
            "label": "直接上级",
            "type": "Reference",
            "required": "0"
          }, {
            "searchDialogWidth": "520px",
            "name": "fuzeHR",
            "label": "负责HR",
            "type": "Reference",
            "required": "0"
          },*/ {
              name: "shebaozhanghao",
              label: "社保账号",
              type: "Text",
              required: "0",
              maxLength: "200",
            },
            {
              name: "gongjijinzhanghao",
              label: "公积金账号",
              type: "Text",
              required: "0",
              maxLength: "200",
            },
            {
              name: "yinhangkahao",
              label: "银行卡号",
              type: "Text",
              required: "0",
              maxLength: "200",
            },
            {
              name: "kaihuxing",
              label: "开户行",
              type: "Text",
              required: "0",
              maxLength: "200",
            },
            {
              name: "shoujihao",
              label: "手机号",
              type: "Text",
              required: "0",
              maxLength: "200",
            },
            /*{
            "name": "changzhudizhi",
            "label": "常住地址",
            "type": "AreaSelect",
            "areaDataType": "2",
            "required": "0"
          },*/ {
              name: "jutidizhi",
              label: "具体地址",
              type: "Text",
              required: "0",
              maxLength: "200",
            },
            { name: "zuigaoxueli", label: "最高学历", type: "Option", required: "0" },
            {
              name: "biyeshijian",
              label: "毕业时间",
              type: "Date",
              required: "0",
            },
            { name: "aa", label: "aa", type: "Integer", required: "1" },
            /*{
            "detailEntity": "Jinjilianxiren",
            "name": "jinjilianxirenId",
            "label": "员工-紧急联系人.id主键",
            "type": "PrimaryKey",
            "required": "1"
          },*/ {
              detailEntity: "Jinjilianxiren",
              name: "createdOn",
              label: "员工-紧急联系人.创建时间",
              type: "DateTime",
              required: "1",
            },
            /*{
            "searchDialogWidth": "520px",
            "detailEntity": "Jinjilianxiren",
            "name": "createdBy",
            "label": "员工-紧急联系人.创建用户",
            "type": "Reference",
            "required": "1"
          },*/ {
              detailEntity: "Jinjilianxiren",
              name: "modifiedOn",
              label: "员工-紧急联系人.最近修改时间",
              type: "DateTime",
              required: "0",
            },
            /*{
            "searchDialogWidth": "520px",
            "detailEntity": "Jinjilianxiren",
            "name": "modifiedBy",
            "label": "员工-紧急联系人.修改用户",
            "type": "Reference",
            "required": "0"
          }, {
            "searchDialogWidth": "520px",
            "detailEntity": "Jinjilianxiren",
            "name": "mdYuangongdanganId",
            "label": "员工-紧急联系人.主从关联Id",
            "type": "Reference",
            "required": "1"
          },*/ {
              detailEntity: "Jinjilianxiren",
              name: "shouji",
              label: "员工-紧急联系人.手机",
              type: "Text",
              required: "0",
              maxLength: "200",
            },
            {
              detailEntity: "Jinjilianxiren",
              name: "jinjilianxirenxingming",
              label: "员工-紧急联系人.紧急联系人姓名",
              type: "Text",
              required: "0",
              maxLength: "200",
            },
          ],
        },
      };
      if (res.data.fieldList) {
        this.fieldListData.fieldList = res.data.fieldList;
        if (res.data.subFormList) {
          this.fieldListData.subFormList = res.data.subFormList;
        }
        this.meteFieldsResult = res;
        const metaFields = this.buildMetaFields(this.meteFieldsResult);
        this.$refs.designer.setFieldListData(this.fieldListData);
        this.$refs.designer.setMetaFields(metaFields);
      }
    },

    buildMetaFields(mdResult) {
      const result = {
        main: {
          entityName: this.entity,
          entityLabel: this.entityLabel,
          fieldList: [],
        },
        detail: [],
      };

      if (mdResult && mdResult.data?.fieldList) {
        mdResult.data.fieldList.forEach((fld) => {
          if (!fld.detailEntity && fld.type !== "PrimaryKey") {
            //跳过id主键
            if (fld.name === "loginPwd") {
              return;
            }

            if (fld.type === "AnyReference" || fld.type === "ReferenceList") {
              return;
            }

            if (this.usedFieldNames.hasOwnProperty(fld.name)) {
              return; //跳过本次循环
            }

            const fieldNewProps = deepClone(formFieldMapping[fld.type]);
            const fieldSchema = deepClone(
              this.$refs.designer.designer.getFieldWidgetByType(fieldNewProps.type)
            );
            overwriteObj(fieldSchema.options, fieldNewProps.options);

            fieldSchema.displayName = fld.label;
            fieldSchema.nameReadonly = true;
            fieldSchema.options.name = fld.name;
            fieldSchema.options.label = fld.label;
            this.adjustFieldSchema(fieldSchema, fld, mdResult);
            result.main.fieldList.push(fieldSchema);
          }
        });
      }

      if (mdResult && mdResult.data?.subFormList) {
        mdResult.data.subFormList.forEach((sf) => {
          const deName = sf.name;
          const deLabel = sf.label;
          const detailDataItem = {
            entityName: deName,
            entityLabel: deLabel,
            fieldList: [],
          };

          mdResult.data.fieldList.forEach((fld) => {
            if (
              fld.detailEntity &&
              fld.detailEntity === deName &&
              fld.type !== "PrimaryKey"
            ) {
              //跳过id主键
              if (fld.type === "AnyReference" || fld.type === "ReferenceList") {
                return;
              }

              if (this.usedFieldNames.hasOwnProperty(fld.name)) {
                return; //跳过本次循环
              }

              const fieldNewProps = deepClone(formFieldMapping[fld.type]);
              const fieldSchema = deepClone(
                this.$refs.designer.designer.getFieldWidgetByType(fieldNewProps.type)
              );
              overwriteObj(fieldSchema.options, fieldNewProps.options);

              fieldSchema.displayName = fld.label;
              fieldSchema.nameReadonly = true;
              fieldSchema.options.name = fld.name;
              fieldSchema.options.label = fld.label;
              this.adjustFieldSchema(fieldSchema, fld, mdResult);
              detailDataItem.fieldList.push(fieldSchema);
            }
          });

          result.detail.push(detailDataItem);
        });
      }

      return result;
    },

    adjustFieldSchema(fieldSchema, fldObj, mdResult) {
      // 处理图片、文件上传字段！！
      let cloudStorageFlag = false;
      let cloudStorageType = "";
      if (mdResult.data.storageSetting) {
        cloudStorageFlag = mdResult.data.storageSetting[0].cloudStorage === "true";
        if (cloudStorageFlag) {
          cloudStorageType = mdResult.data.storageSetting[0].cloudStorageType;
        }
      }

      if (fldObj.type === "Picture" || fldObj.type === "File") {
        if (cloudStorageFlag) {
          //设置withCredentials
          fieldSchema.options.withCredentials = false;

          //设置onBeforeUpload事件代码(还需要生成uuid新文件名)
          fieldSchema.options.onBeforeUpload =
            "const gDSV = this.getGlobalDsv();\nconst wType = this.field.type;\nif (wType === 'picture-upload') {\n  this.field.options.uploadURL = gDSV.picUploadURL;\n} else if (wType === 'file-upload')  {\n  this.field.options.uploadURL = gDSV.fileUploadURL;\n}\n\nconst cloudStorage = gDSV.cloudStorage;\nif (cloudStorage === \"true\") {\n  this.field.options.withCredentials = false\n  const token = gDSV.cloudUploadToken;\n  this.setUploadData('token', token);\n  \n  const randomNum = Math.floor(Math.random() * 100);\n  const newFileName = new Date().getTime() + randomNum+ '_' + file.name;\n  this.setUploadData('key', newFileName);\n} else {\n  //this.field.options.withCredentials = true\n}\n";

          //设置onUploadSuccess事件代码(上传返回结果需要设置QiNiu=前缀)
          fieldSchema.options.onUploadSuccess =
            "const gDSV = this.getGlobalDsv();\nconst cloudStorage = gDSV.cloudStorage;\nif (cloudStorage === \"true\") {\n  const wType = this.field.type;\n  let downloadPrefix = \"\"\n  if (wType === 'picture-upload') {\n    downloadPrefix = gDSV.picDownloadPrefix;\n  } else if (wType === 'file-upload')  {\n    downloadPrefix = gDSV.fileDownloadPrefix;\n  }\n  \n  let downUrl = downloadPrefix + result.key;\n  const paramName = (downUrl.indexOf(\"?\") === -1) ? '?fileName=' : '&fileName=';\n  return {\n    name: file.name,\n    url: downUrl + paramName + file.name\n  }\n} else {\n  const paramName = (result.url.indexOf(\"?\") === -1) ? '?fileName=' : '&fileName=';\n  return {\n    name: file.name,\n    url: result.url + paramName + file.name\n  }\n}\n";
        }
      }
      // 处理图片、文件上传字段 -- 结束

      /* 处理文本、长文本字段 */
      if (fldObj.type === "Text" || fldObj.type === "TextArea") {
        fieldSchema.options.maxLength = !fldObj.maxLength
          ? fieldSchema.options.maxLength
          : fldObj.maxLength * 1;
      }

      /* 处理精度小数字段 */
      if (
        fldObj.type === "Integer" ||
        fldObj.type === "Percent" ||
        fldObj.type === "Money" ||
        fldObj.type === "Decimal"
      ) {
        fieldSchema.options.precision = !fldObj.precision
          ? fieldSchema.options.precision
          : fldObj.precision * 1;
        fieldSchema.options.min = !fldObj.min ? fieldSchema.options.min : fldObj.min * 1;
        fieldSchema.options.max = !fldObj.max ? fieldSchema.options.max : fldObj.max * 1;
      }

      /* 处理地区选择字段 */
      if (fldObj.type === "AreaSelect") {
        fieldSchema.optionItemsReadonly = true;
        fieldSchema.options.areaDataType = !fldObj.areaDataType
          ? fieldSchema.options.areaDataType
          : fldObj.areaDataType * 1;
      }

      /* 处理一对一字段 */
      if (fldObj.type === "Reference") {
        fieldSchema.options.searchDialogWidth = !fldObj.searchDialogWidth
          ? fieldSchema.options.searchDialogWidth
          : fldObj.searchDialogWidth;
      }

      /* 处理单选项字段 */
      if (fieldSchema.options.hasOwnProperty("optionItems")) {
        if (this.formOptionData.hasOwnProperty(fieldSchema.options.name)) {
          fieldSchema.options.optionItems = deepClone(
            this.formOptionData[fieldSchema.options.name]
          );
        }

        if (fldObj.type === "Boolean") {
          fieldSchema.options.optionItems = [
            { value: true, label: "是" },
            { value: false, label: "否" },
          ];
        }

        fieldSchema.optionItemsReadonly = true;
      }

      /* 设置字段必填校验 */
      if (fldObj.hasOwnProperty("required")) {
        fieldSchema.options.required = fldObj["required"] === "1";
      }

      /* 取消系统字段的必填校验 */
      if (
        fieldSchema.options.name === "createdOn" ||
        fieldSchema.options.name === "createdBy" ||
        fieldSchema.options.name === "modifiedOn" ||
        fieldSchema.options.name === "modifiedBy" ||
        fieldSchema.options.name === "ownerUser" ||
        fieldSchema.options.name === "ownerDepartment" ||
        fieldSchema.options.name === "approvalConfigId" ||
        fieldSchema.options.name === "approvalStatus" ||
        fieldSchema.options.name === "lastApprovedBy" ||
        fieldSchema.options.name === "lastApprovedOn"
      ) {
        fieldSchema.options.required = false;
      }

      //
    },

    handleFWU(fwName) {
      this.usedFieldNames[fwName] = 1;

      /* 必须延时处理，否则draggable会报错 */
      setTimeout(() => {
        const metaFields = this.buildMetaFields(this.meteFieldsResult);
        this.$refs.designer.setMetaFields(metaFields);
      }, 800);
    },

    handleFWR(fwName) {
      delete this.usedFieldNames[fwName];

      /* 必须延时处理，否则draggable会报错 */
      setTimeout(() => {
        const metaFields = this.buildMetaFields(this.meteFieldsResult);
        this.$refs.designer.setMetaFields(metaFields);
      }, 800);
    },

    handleFJU() {
      this.handleUsedFields();
      setTimeout(() => {
        const metaFields = this.buildMetaFields(this.meteFieldsResult);
        this.$refs.designer.setMetaFields(metaFields);
      }, 300);
    },

    /**
     * 过滤已使用字段组件
     */
    handleUsedFields() {
      this.usedFieldNames = {};
      const allFieldWidgets = this.$refs.designer.getFieldWidgets();
      allFieldWidgets.forEach((fwItem) => {
        this.usedFieldNames[fwItem.name] = 1;
      });
    },
    initField() {
      this.$http({
        aes: true,
        url: USER_PREFIX + "/szTaMb/listPage",
        data: {},
        success: (res) => {},
      });
    },
    reflushTemplateList() {
      this.$emit("reflushTemplateList");
    },
    customConfirm(json) {
      this.$emit("customConfirm", json);
    },
  },
};
</script>

<style lang="scss" scoped>
body {
  margin: 0; /* 如果页面出现垂直滚动条，则加入此行CSS以消除之 */
}

#app .main-container {
  margin-left: 0px;
}
</style>
