<template>
  <div class="page-wrapper cp-add-page" style="overflow: auto">
    <div class="page-container">
      <a-form-model
        ref="addForm"
        :model="addForm"
        :rules="addFormRules"
        class="addForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-collapse
          :bordered="false"
          default-active-key="a"
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel key="a" :header="$t('BASE_INFO')">
            <a-row type="flex">
              <a-col :span="8">
                <a-form-model-item
                  prop="componentCode"
                  :label="$t('COMPONENT_CODE')"
                >
                  <a-input
                    v-model="addForm.componentCode"
                    :placeholder="$t('PLACEENTER')"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  prop="componentName"
                  :label="$t('COMPONENT_NAME')"
                >
                  <a-input
                    v-model="addForm.componentName"
                    :placeholder="$t('PLACEENTER')"
                    allow-clear
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  prop="componentType"
                  :label="$t('COMPONENT_TYPE')"
                >
                  <a-select
                    v-model="addForm.componentType"
                    :placeholder="$t('PLACESELECT')"
                  >
                    <a-select-option
                      v-for="item in cpTypeList"
                      :key="item.value"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  prop="componentPath"
                  :label="$t('COMPONENT_ADDRESS')"
                >
                  <a-input
                    v-model="addForm.componentPath"
                    :placeholder="$t('PLACEENTER')"
                    allow-clear
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item prop="icon" :label="$t('ICON')">
                  <MegaSelectIcon v-model="addForm.icon" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item prop="remark" :label="$t('REMARK')">
                  <a-input
                    v-model="addForm.remark"
                    :placeholder="$t('PLACEENTER')"
                    allow-clear
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>

        <a-collapse
          :bordered="false"
          default-active-key="b"
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel key="b" :header="$t('COMPONENT_ATTR')">
            <MomTable
              row-key="id"
              :columns="columns"
              :data-source="addForm.attributeList"
              :pagination="false"
              :action-buttons="actionButtons"
              :mega-extend="{
                rowAction: {
                  width: 90,
                },
              }"
            >
              <div slot="toolbar">
                <a-button type="primary" icon="plus" @click="handleAddAttr">
                  {{ $t("ADD") }}
                </a-button>
              </div>
              <template slot="attrKey" slot-scope="text, record, index, col">
                <div
                  :class="{
                    'has-error': !attrKeyValidate(record),
                  }"
                >
                  <a-input
                    :value="text"
                    :placeholder="$t('PLACEENTER')"
                    @change="
                      (e) =>
                        handleCellChange(e.target.value, index, col.dataIndex)
                    "
                  />
                </div>
              </template>
              <template slot="attrName" slot-scope="text, record, index, col">
                <div
                  :class="{
                    'has-error': !attrNameValidate(record),
                  }"
                >
                  <I18nSelect
                    v-if="clientTypeList.length && i18nTypeList.length"
                    ref="select"
                    :value="text"
                    :client-type-list="clientTypeList"
                    :i18n-type-list="i18nTypeList"
                    @change="(e) => handleCellChange(e, index, col.dataIndex)"
                  ></I18nSelect>
                </div>
              </template>
              <template slot="attrMust" slot-scope="text, record, index, col">
                <a-switch
                  :checked="[1, 'Y'].includes(text)"
                  :disabled="index > 9"
                  size="small"
                  @change="(e) => handleCellChange(e, index, col.dataIndex)"
                />
              </template>
              <template
                slot="attrValueType"
                slot-scope="text, record, index, col"
              >
                <div
                  :class="{
                    'has-error': !attrValueTypeValidate(record),
                  }"
                >
                  <a-select
                    :value="text"
                    :placeholder="$t('PLACESELECT')"
                    style="width: 100%"
                    @change="(e) => handleCellChange(e, index, col.dataIndex)"
                  >
                    <a-select-option
                      v-for="item in attrValueTypeList"
                      :key="item.value"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </div>
              </template>
              <template
                slot="attrValueLength"
                slot-scope="text, record, index, col"
              >
                <div
                  :class="{
                    'has-error': !attrValueLengthValidate(record),
                  }"
                >
                  <a-input-number
                    :value="text"
                    :precision="0"
                    :placeholder="$t('PLACEENTER')"
                    style="width: 100%"
                    @change="(e) => handleCellChange(e, index, col.dataIndex)"
                  />
                </div>
              </template>
              <template
                slot="defaultValue"
                slot-scope="text, record, index, col"
              >
                <a-textarea
                  :value="text"
                  :placeholder="$t('PLACEENTER')"
                  @change="
                    (e) =>
                      handleCellChange(e.target.value, index, col.dataIndex)
                  "
                />
              </template>
              <template slot="inputMode" slot-scope="text, record, index, col">
                <div>
                  <a-select
                    :value="text"
                    :placeholder="$t('PLACESELECT')"
                    style="width: 100%"
                    @change="(e) => handleCellChange(e, index, col.dataIndex)"
                  >
                    <a-select-option
                      v-for="item in attrInputModeList"
                      :key="item.value"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </div>
              </template>
              <template
                slot="valueSource"
                slot-scope="text, record, index, col"
              >
                <div
                  :class="{
                    'has-error': !attrValueSourceValidate(record),
                  }"
                >
                  <a-input
                    :value="text"
                    :placeholder="$t('PLACEENTER')"
                    @change="
                      (e) =>
                        handleCellChange(e.target.value, index, col.dataIndex)
                    "
                  />
                </div>
              </template>
            </MomTable>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
    </div>
    <div class="page-bottom-op">
      <a-button type="primary" @click="confirm">
        <MegaIcon type="icon-cur-save_1" :size="18" />
        {{ $t("SAVE") }}
      </a-button>
      <a-button @click="cancel">
        <MegaIcon type="icon-dir-f-rollback" :size="18" />
        {{ $t("CANCEL") }}
      </a-button>
    </div>
  </div>
</template>

<script>
import {
  Icon as MegaIcon,
  IconList as MegaSelectIcon,
} from "@mega-design/ui-vue";
import cloneDeep from "lodash/cloneDeep";
import ApiConstant from "~/api/ApiConstant";
import I18nSelect from "@/components/I18nSelect";

export default {
  components: {
    MegaIcon,
    MegaSelectIcon,
    I18nSelect,
  },
  data() {
    return {
      addForm: {
        componentCode: undefined,
        componentName: undefined,
        componentType: undefined,
        componentPath: undefined,
        icon: undefined,
        remark: undefined,
        attributeList: [
          {
            id: 0,
            attrKey: undefined, // 属性key
            attrName: undefined, // 属性名称
            attrMust: "N", // 属性是否必填
            attrValueType: undefined, // 属性值类型
            attrValueLength: undefined, // 属性值长度
            defaultValue: undefined, // 默认属性值
            inputMode: "MANUAL", // 输入方式
            valueSource: undefined, // 属性值来源
          },
        ],
      },
      clientTypeList: [],
      i18nTypeList: [],
      cpTypeList: [],
      attrValueTypeList: [],
      attrInputModeList: [],
      columns: [
        {
          title: () => `${this.$t("ATTRIBUTE")} Key`,
          scopedSlots: { customRender: "attrKey" },
          dataIndex: "attrKey",
          width: 200,
          sorter: false,
        },
        {
          title: () => this.$t("ATTR_NAME"),
          scopedSlots: { customRender: "attrName" },
          dataIndex: "attrName",
          width: 280,
          sorter: false,
        },
        {
          title: () => this.$t("IS_REQUIRED"),
          scopedSlots: { customRender: "attrMust" },
          dataIndex: "attrMust",
          width: 140,
          sorter: false,
        },
        {
          title: () => this.$t("VALUE_TYPE"),
          scopedSlots: { customRender: "attrValueType" },
          dataIndex: "attrValueType",
          width: 240,
          sorter: false,
        },
        {
          title: () => this.$t("VALUE_LENGTH"),
          scopedSlots: { customRender: "attrValueLength" },
          dataIndex: "attrValueLength",
          width: 180,
          sorter: false,
        },
        {
          title: () => this.$t("DEFAULT_VALUE"),
          scopedSlots: { customRender: "defaultValue" },
          dataIndex: "defaultValue",
          sorter: false,
          minWidth: 200,
        },
        {
          title: () => this.$t("INPUT_MODE"),
          scopedSlots: { customRender: "inputMode" },
          dataIndex: "inputMode",
          width: 240,
          sorter: false,
        },
        {
          title: () => this.$t("VALUE_SOURCE"),
          scopedSlots: { customRender: "valueSource" },
          dataIndex: "valueSource",
          width: 300,
          sorter: false,
        },
      ],
      actionButtons: [
        (h, { index }) => (
          <a-button
            type="error"
            icon="delete"
            title={this.$t("DELETE")}
            disabled={this.addForm.attributeList.length === 1}
            onClick={() => this.handleDelete(index)}
          ></a-button>
        ),
      ],
    };
  },
  computed: {
    addFormRules() {
      return {
        componentCode: [this.validateFieldLength(0, 32)],
        componentName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          this.validateFieldLength(1, 32),
        ],
        componentType: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        componentPath: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          this.validateFieldLength(1, 50),
        ],
        icon: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        remark: [this.validateFieldLength(0, 64)],
      };
    },
  },
  created() {
    this.getDictByCode("DIC:CORE:MOM_VERSION").then((res) => {
      this.clientTypeList = res.data.data || [];
    });
    this.getDictByCode("DIC:CORE:I18N_TYPE").then((res) => {
      this.i18nTypeList = res.data.data || [];
    });
    this.getDictByCode("DIC:IDE:COMPONENT_TYPE").then((res) => {
      this.cpTypeList = res.data.data || [];
    });
    this.getDictByCode("DIC:IDE:ATTR_VALUE_TYPE").then((res) => {
      this.attrValueTypeList = res.data.data || [];
    });
    this.getDictByCode("DIC:COMP:ATTR_INPUT_MODE").then((res) => {
      this.attrInputModeList = res.data.data || [];
    });
  },
  methods: {
    handleDelete(index) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.addForm.attributeList.splice(index, 1);
        },
      });
    },
    handleAddAttr() {
      this.$set(this.addForm.attributeList, this.addForm.attributeList.length, {
        id: this.addForm.attributeList.length,
        attrKey: undefined, // 属性key
        attrName: undefined, // 属性名称
        attrMust: "N", // 属性是否必填
        attrValueType: undefined, // 属性值类型
        attrValueLength: undefined, // 属性值长度
        defaultValue: undefined, // 默认属性值
        inputMode: "MANUAL", // 输入方式
        valueSource: undefined, // 属性值来源
      });
    },
    handleCellChange(value, index, attr) {
      if (["attrMust"].includes(attr)) {
        this.addForm.attributeList[index][attr] = value ? "Y" : "N";
      } else if (attr === "attrValueLength") {
        `${value}`.length < 17
          ? (this.addForm.attributeList[index][attr] = value)
          : (this.addForm.attributeList[index][attr] = undefined);
      } else {
        this.addForm.attributeList[index][attr] = value;
      }
    },
    getReqData() {
      const items = [];
      for (let i = 0; i < this.addForm.attributeList.length; i += 1) {
        const record = this.addForm.attributeList[i];

        const valid =
          this.attrKeyValidate(record) &&
          this.attrNameValidate(record) &&
          this.attrValueTypeValidate(record) &&
          this.attrValueLengthValidate(record) &&
          this.attrValueSourceValidate(record);
        if (valid) {
          if (record.attrKey) {
            const tmp = cloneDeep(record);
            items.push(tmp);
          }
        } else {
          return false;
        }
      }
      return items;
    },
    attrKeyValidate(record) {
      if (record.attrKey && record.attrKey.length > 32) {
        return false;
      }
      return true;
    },
    attrNameValidate(record) {
      if (record.attrKey && !record.attrName) {
        return false;
      }
      if (record.attrName && record.attrName.length > 64) {
        return false;
      }
      return true;
    },
    attrValueTypeValidate(record) {
      if (record.attrKey && !record.attrValueType) {
        return false;
      }
      return true;
    },
    attrValueLengthValidate(record) {
      if (
        record.attrKey &&
        record.attrValueType &&
        ["String", "Integer", "Float"].includes(record.attrValueType) &&
        !record.attrValueLength
      ) {
        return false;
      }
      if (record.attrValueLength && `${record.attrValueLength}`.length > 10) {
        return false;
      }
      return true;
    },
    attrValueSourceValidate(record) {
      if (
        record.attrKey &&
        record.inputMode !== "MANUAL" &&
        !record.valueSource
      ) {
        return false;
      }
      return true;
    },
    confirm() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          const items = this.getReqData();
          if (typeof items === "object") {
            this.$axios
              .post(`${ApiConstant.PREFIX_CORE}/api/idewebcomponent`, {
                ...this.addForm,
                attributeList: items,
              })
              .then(() => {
                this.$message.success(this.$t("ADD_SUCCESS"));
                this.$store.dispatch("tagsView/jumpBeforeView", {
                  to: { path: "/upms/devCenter/tools/component-mgmt" },
                  vm: this,
                });
              });
          } else {
            this.$message.error({
              content: (h) => (
                <span>
                  <span>{this.$t("RED_AREA_DATA_PLACE_ENTER")}</span>
                  <br />
                  <span>
                    {`${this.$t("ATTRIBUTE")} Key`}:
                    {this.validateLengthMsg(0, 32)}
                    <br />
                    {this.$t("ATTR_NAME")}: {this.validateLengthMsg(0, 64)}
                    <br />
                    {this.$t("VALUE_LENGTH")}:{this.validateLengthMsg(0, 10)}
                    <br />
                    {this.$t("VALUE_SOURCE")}:{this.validateLengthMsg(1, 128)}
                  </span>
                </span>
              ),
            });
          }
        }
      });
    },
    cancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: { path: "/upms/devCenter/tools/component-mgmt" },
        vm: this,
      });
    },
  },
};
</script>

<style lang="less" scoped>
.cp-add-page {
  .page-container .mega-design-business-table .mega-design-pro-table {
    padding-top: 0;
  }
}
</style>
