<template>
  <div class="option-items-pane">
    <el-form-item label="选项值类型">
      <el-radio-group v-model="optionModel.optionItemValueType" @change="changeValueType">
        <el-radio :label="0">文本</el-radio>
        <el-radio :label="1">数值</el-radio>
        <el-radio :label="2">布尔值</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="默认值">
      <template
        v-if="
          selectedWidget.type === 'checkbox' ||
          (selectedWidget.type === 'select' && selectedWidget.options.multiple)
        "
      >
        <a
          href="javascript:void(0);"
          class="a-link link-oneLind"
          @click="openTableDataEdit()"
        >
          <span>{{ getDefaultValue() }}</span>
          <i class="el-icon-edit"></i>
        </a>
      </template>
      <template v-else>
        <el-input
          v-model="optionModel.defaultValue"
          size="mini"
          style="width: 100px"
          v-if="!optionModel.optionItemValueType"
        ></el-input>
        <base-input-number
          v-model="optionModel.defaultValue"
          size="mini"
          style="width: 100%"
          v-if="optionModel.optionItemValueType == 1"
        />
        <el-select
          v-model="optionModel.defaultValue"
          style="width: 100%"
          v-if="optionModel.optionItemValueType === 2"
          clearable
          @clear="optionModel.defaultValue = null"
        >
          <el-option :value="true" label="true"></el-option>
          <el-option :value="false" label="false"></el-option>
        </el-select>
      </template>
    </el-form-item>
    <el-form-item :label="i18nt('显示字段')">
      <el-input
        type="text"
        v-model="optionModel.labelKey"
        placeholder="默认label"
        :disabled="optionModel.commonAttributeEnabled || !optionModel.formScriptEnabled"
      ></el-input>
    </el-form-item>
    <el-form-item :label="i18nt('关联字段')">
      <el-input
        type="text"
        v-model="optionModel.valueKey"
        placeholder="默认value"
        :disabled="optionModel.commonAttributeEnabled || !optionModel.formScriptEnabled"
      ></el-input>
    </el-form-item>
    <template
      v-if="!optionModel.commonAttributeEnabled && !optionModel.formScriptEnabled"
    >
      <el-radio-group
        v-if="
          selectedWidget.type === 'radio' ||
          (selectedWidget.type === 'select' && !selectedWidget.options.multiple)
        "
        v-model="optionModel.defaultValue"
        @change="emitDefaultValueChange"
      >
        <draggable
          tag="ul"
          class="draggable-box"
          :list="optionModel.optionItems"
          v-bind="{ group: 'optionsGroup', ghostClass: 'ghost', handle: '.drag-option' }"
        >
          <li v-for="(option, idx) in optionModel.optionItems" :key="idx">
            <el-radio :label="option.value">
              <el-input
                v-model="option.value"
                size="mini"
                style="width: 100px"
                v-if="!optionModel.optionItemValueType"
              ></el-input>
              <base-input-number
                v-model="option.value"
                size="mini"
                style="width: 100px"
                v-if="optionModel.optionItemValueType == 1"
              />
              <!--            <el-input v-model="option.value" size="mini" style="width: 100px" v-if="optionModel.optionItemValueType===2" disabled></el-input>-->
              <el-select
                v-model="option.value"
                style="width: 100px"
                v-if="optionModel.optionItemValueType === 2"
              >
                <el-option :value="true" label="true"></el-option>
                <el-option :value="false" label="false"></el-option>
              </el-select>
              <el-input
                v-model="option.label"
                size="mini"
                style="width: 100px"
              ></el-input>
              <i class="el-icon-s-operation drag-option"></i>
              <el-button
                circle
                plain
                size="mini"
                type="danger"
                @click="deleteOption(option, idx)"
                icon="el-icon-minus"
                class="col-delete-button"
              ></el-button>
            </el-radio>
          </li>
        </draggable>
      </el-radio-group>
      <el-checkbox-group
        v-else-if="
          selectedWidget.type === 'checkbox' ||
          (selectedWidget.type === 'select' && selectedWidget.options.multiple)
        "
        v-model="optionModel.defaultValue"
        @change="emitDefaultValueChange"
      >
        <draggable
          tag="ul"
          class="draggable-box"
          :list="optionModel.optionItems"
          v-bind="{ group: 'optionsGroup', ghostClass: 'ghost', handle: '.drag-option' }"
        >
          <li v-for="(option, idx) in optionModel.optionItems" :key="idx">
            <el-checkbox :label="option.value">
              <el-input
                v-model="option.value"
                size="mini"
                style="width: 100px"
                v-if="!optionModel.optionItemValueType"
              ></el-input>
              <base-input-number
                v-model="option.value"
                size="mini"
                style="width: 100px"
                v-if="optionModel.optionItemValueType == 1"
              />
              <el-input
                v-model="option.value"
                size="mini"
                style="width: 100px"
                v-if="optionModel.optionItemValueType === 2"
                disabled
              ></el-input>
              <el-input
                v-model="option.label"
                size="mini"
                style="width: 100px"
              ></el-input>
              <i class="el-icon-s-operation drag-option"></i>
              <el-button
                circle
                plain
                size="mini"
                type="danger"
                @click="deleteOption(option, idx)"
                icon="el-icon-minus"
                class="col-delete-button"
              ></el-button>
            </el-checkbox>
          </li>
        </draggable>
      </el-checkbox-group>
      <el-cascader
        v-else-if="selectedWidget.type === 'cascader'"
        v-model="optionModel.defaultValue"
        :options="optionModel.optionItems"
        @change="emitDefaultValueChange"
        :placeholder="i18nt('render.hint.selectPlaceholder')"
        style="width: 100%"
      ></el-cascader>
      <div v-if="selectedWidget.type === 'cascader'">
        <el-button type="text" @click="importCascaderOptions">{{
          i18nt("designer.setting.importOptions")
        }}</el-button>
        <el-button type="text" @click="resetDefault">{{
          i18nt("designer.setting.resetDefault")
        }}</el-button>
      </div>

      <div
        v-if="
          selectedWidget.type === 'radio' ||
          selectedWidget.type === 'checkbox' ||
          selectedWidget.type === 'select'
        "
      >
        <el-button type="text" @click="addOption">{{
          i18nt("designer.setting.addOption")
        }}</el-button>
        <el-button
          type="text"
          @click="importOptions"
          v-if="optionModel.optionItemValueType !== 2"
          >{{ i18nt("designer.setting.importOptions") }}</el-button
        >
        <el-button type="text" @click="resetDefault">{{
          i18nt("designer.setting.resetDefault")
        }}</el-button>
      </div>
    </template>

    <el-dialog
      :title="i18nt('designer.setting.importOptions')"
      :visible.sync="showImportDialogFlag"
      v-if="showImportDialogFlag"
      :show-close="true"
      class="small-padding-dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :append-to-body="true"
      :modal-append-to-body="true"
    >
      <el-form-item
        ><el-input type="textarea" rows="10" v-model="optionLines"></el-input
      ></el-form-item>
      <div slot="footer" class="dialog-footer">
        <el-button size="large" type="primary" @click="saveOptions">{{
          i18nt("designer.hint.confirm")
        }}</el-button>
        <el-button size="large" type="" @click="showImportDialogFlag = false">{{
          i18nt("designer.hint.cancel")
        }}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="i18nt('designer.setting.importOptions')"
      :visible.sync="showImportCascaderDialogFlag"
      v-if="showImportCascaderDialogFlag"
      :show-close="true"
      class="small-padding-dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :append-to-body="true"
      :modal-append-to-body="true"
    >
      <code-editor v-model="cascaderOptions" mode="json" :readonly="false"></code-editor>
      <div slot="footer" class="dialog-footer">
        <el-button size="large" type="primary" @click="saveCascaderOptions">{{
          i18nt("designer.hint.confirm")
        }}</el-button>
        <el-button size="large" type="" @click="showImportCascaderDialogFlag = false">{{
          i18nt("designer.hint.cancel")
        }}</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-if="dataDialogVisible"
      custom-class="dialog-style list-dialog"
      :title="i18nt('默认值编辑')"
      :visible.sync="dataDialogVisible"
      :show-close="!0"
      append-to-body=""
      :close-on-click-modal="!1"
      :close-on-press-escape="!1"
      :destroy-on-close="!0"
      width="75%"
      v-dialog-drag
    >
      <template slot="footer">
        <div class="dialog-footer">
          <el-button
            type=""
            @click="dataDialogVisible = !1"
            class="button-sty"
            icon="el-icon-close"
          >
            {{ i18nt("designer.hint.cancel") }}
          </el-button>
          <el-button
            type="primary"
            @click="saveTableData"
            class="button-sty"
            icon="el-icon-check"
          >
            {{ i18nt("designer.hint.confirm") }}
          </el-button>
        </div>
      </template>
      <code-editor mode="json" :readonly="!1" v-model="tableDataOptions"></code-editor>
    </el-dialog>
  </div>
</template>

<script>
import Draggable from "vuedraggable";
import i18n from "../../../../components/xform/utils/i18n";

export default {
  name: "OptionItemsSetting",
  componentName: "PropertyEditor",
  mixins: [i18n],
  components: {
    Draggable,
  },
  props: {
    designer: Object,
    selectedWidget: Object,
  },
  data() {
    return {
      showImportDialogFlag: false,
      optionLines: "",

      cascaderOptions: "",
      showImportCascaderDialogFlag: false,

      //separator: '||',
      separator: ",",
      dataDialogVisible: false,
      tableDataOptions: [],
    };
  },
  computed: {
    optionModel() {
      return this.selectedWidget.options;
    },
  },
  watch: {
    "selectedWidget.options": {
      deep: true,
      handler(val) {
        //console.log('888888', 'Options change!')
      },
    },
  },
  created() {
    if (!this.optionModel.hasOwnProperty("optionItemValueType")) {
      this.optionModel.optionItemValueType = 0;
    }
    if (this.optionModel.optionItemValueType == 1) {
      if (
        this.optionModel.defaultValue === null ||
        this.optionModel.defaultValue === ""
      ) {
        this.optionModel.defaultValue = undefined;
      }
    }
  },
  methods: {
    emitDefaultValueChange() {
      if (!!this.designer && !!this.designer.formWidget) {
        let fieldWidget = this.designer.formWidget.getWidgetRef(
          this.selectedWidget.options.name
        );
        if (!!fieldWidget && !!fieldWidget.refreshDefaultValue) {
          fieldWidget.refreshDefaultValue();
        }
      }
    },

    deleteOption(option, index) {
      this.optionModel.optionItems.splice(index, 1);
    },

    addOption() {
      let optionItemValueType = this.optionModel.optionItemValueType;
      let newValue = this.optionModel.optionItems.length + 1;
      if (!optionItemValueType) {
        newValue = newValue + "";
      } else if (optionItemValueType == 2) {
        newValue = true;
      }
      this.optionModel.optionItems.push({
        value: newValue,
        label: "new option",
      });
    },

    importOptions() {
      this.optionLines = "";
      if (this.optionModel.optionItems.length > 0) {
        this.optionModel.optionItems.forEach((opt) => {
          if (opt.value === opt.label) {
            this.optionLines += opt.value + "\n";
          } else {
            this.optionLines += opt.value + this.separator + opt.label + "\n";
          }
        });
      }

      this.showImportDialogFlag = true;
    },

    saveOptions() {
      let lineArray = this.optionLines.split("\n");
      //console.log('test', lineArray)
      if (lineArray.length > 0) {
        let isNumericOptionItemValue = this.optionModel.optionItemValueType === 1;
        this.optionModel.optionItems = [];
        lineArray.forEach((optLine) => {
          if (!!optLine && !!optLine.trim()) {
            if (optLine.indexOf(this.separator) !== -1) {
              let valueStr = optLine.split(this.separator)[0];
              let value = isNumericOptionItemValue ? Number(valueStr) : valueStr;
              this.optionModel.optionItems.push({
                value: value,
                label: optLine.split(this.separator)[1],
              });
            } else {
              let value = isNumericOptionItemValue ? Number(optLine) : optLine;
              this.optionModel.optionItems.push({
                value: value,
                label: optLine,
              });
            }
          }
        });
      } else {
        this.optionModel.optionItems = [];
      }

      this.showImportDialogFlag = false;
    },

    resetDefault() {
      if (
        this.selectedWidget.type === "checkbox" ||
        (this.selectedWidget.type === "select" && this.selectedWidget.options.multiple)
      ) {
        this.optionModel.defaultValue = [];
      } else {
        this.optionModel.defaultValue = undefined;
      }

      this.emitDefaultValueChange();
    },

    importCascaderOptions() {
      this.cascaderOptions = JSON.stringify(this.optionModel.optionItems, null, "  ");
      this.showImportCascaderDialogFlag = true;
    },

    saveCascaderOptions() {
      try {
        let newOptions = JSON.parse(this.cascaderOptions);
        this.optionModel.optionItems = newOptions;
        //TODO: 是否需要重置选项默认值？？

        this.showImportCascaderDialogFlag = false;
      } catch (ex) {
        this.$message.error(this.i18nt("designer.hint.invalidOptionsData") + ex.message);
      }
    },
    changeValueType(val) {
      let optionItems = this.optionModel.optionItems;
      // this.optionModel.defaultValue = undefined;
      this.resetDefault();
      this.optionModel.optionItems.length = 0;
      if (val == 2) {
        optionItems.push({
          label: "是",
          value: true,
        });
        optionItems.push({
          label: "否",
          value: false,
        });
      } else {
        this.addOption();
      }
      this.$forceUpdate();
      this.emitDefaultValueChange();
    },

    openTableDataEdit: function () {
      (this.dataDialogVisible = !0),
        (this.tableDataOptions = JSON.stringify(
          this.optionModel.defaultValue,
          null,
          "  "
        ));
    },
    saveTableData: function () {
      try {
        (this.optionModel.defaultValue = JSON.parse(this.tableDataOptions)),
          (this.dataDialogVisible = !1);
      } catch (e) {
        this.$message.error(this.i18nt("designer.hint.invalidOptionsData") + e.message);
      }
    },
    getDefaultValue() {
      let result = this.optionModel.defaultValue;
      if (result) {
        if (Array.isArray(result)) {
          result = result.join(",");
        }
      }
      return result;
    },
  },
};
</script>

<style lang="scss" scoped>
.option-items-pane ul {
  padding-inline-start: 6px;
  padding-left: 6px; /* 重置IE11默认样式 */
}

li.ghost {
  background: #fff;
  border: 2px dotted $--color-primary;
}

.drag-option {
  cursor: move;
}

.small-padding-dialog ::v-deep .el-dialog__body {
  padding: 10px 15px;
}

.dialog-footer .el-button {
  width: 100px;
}
</style>
