<template>
  <div>
    <xy-dialog
      :width="72"
      ref="dialog"
      :is-show.sync="isShow"
      type="form"
      :title="type === 'add' ? '新增数据管理' : '编辑数据管理'"
      :form="form"
      :rules="rules"
      @submit="submit"
    >
      <template v-slot:type>
        <div class="xy-table-item">
          <div class="xy-table-item-label">名称 ：</div>
          <div class="xy-table-item-content">
            <el-input
              v-model="form.type"
              clearable
              placeholder="请输入名称"
              style="width: 300px"
            ></el-input>
          </div>
        </div>
      </template>
      <template v-slot:key>
        <div class="xy-table-item">
          <div class="xy-table-item-label">键 ：</div>
          <div class="xy-table-item-content">
            <el-input
              v-model="form.key"
              clearable
              placeholder="请输入键"
              style="width: 300px"
            ></el-input>
          </div>
        </div>
      </template>
      <template v-slot:value>
        <div class="xy-table-item">
          <div class="xy-table-item-label">值 ：</div>
          <div class="xy-table-item-content" style="width: 600px">
            <el-input
              type="textarea"
              :autosize="{
                minRows: 2
              }"
              v-model="form.value"
              clearable
              placeholder="请输入值"
            ></el-input>


            <div style="margin: 10px auto;">
              <el-button type="primary" icon="el-icon-upload2" @click="JSON2str">转换</el-button>
              <el-button type="primary" icon="el-icon-download" @click="str2JSON">转换</el-button>
            </div>

            <div>
              <template v-if="transformJSON instanceof Array">
                <xy-table :height="300" :list="transformJSON" :table-item="JSONHeader" :is-page="false">
                  <template #btns>
                    <el-table-column>
                      <template #default="{ row, $index }">
                        <Button size="small" type="primary" @click="transformJSON.splice($index,1)">删除</Button>
                      </template>
                    </el-table-column>
                  </template>
                </xy-table>
              </template>
              <template v-if="typeof transformJSON === 'object' && !transformJSON instanceof Array">
                <div v-for="(value, key) in transformJSON">
                  <el-input size="small" :value="key"></el-input>
                  <el-input size="small" style="margin-left: 6px;" :value="value"></el-input>
                </div>
              </template>
            </div>
          </div>
        </div>
      </template>
      <template v-slot:sort>
        <div class="xy-table-item">
          <div class="xy-table-item-label">排序 ：</div>
          <div class="xy-table-item-content">
            <el-input-number
              v-model="form.sort"
              clearable
              placeholder="请输入排序"
              style="width: 300px"
              :controls="false"
            ></el-input-number>
          </div>
        </div>
      </template>
<!--      <template #extraFormBottom>-->
<!--        <div class="xy-table-item">-->
<!--          <div class="xy-table-item-label">文件 ：</div>-->
<!--          <div class="xy-table-item-content">-->
<!--            <el-upload-->
<!--              style="width: 300px"-->
<!--              ref="upload"-->
<!--              multiple-->
<!--              :on-success="-->
<!--                (response, file, fileList) =>-->
<!--                  successHandle(response, file, fileList, 'file')-->
<!--              "-->
<!--              :before-upload="uploadBefore"-->
<!--              accept=".rar,.zip,.doc,.docx,.pdf,.jpg,.png,.gif,.mp4,.xls,.xlsx"-->
<!--              :action="action"-->
<!--              :file-list="file"-->
<!--              :auto-upload="false"-->
<!--              :on-remove="-->
<!--                (file, fileList) => removeHande(file, fileList, 'file')-->
<!--              "-->
<!--            >-->
<!--              <el-button slot="trigger" size="small" type="primary"-->
<!--                >选取文件</el-button-->
<!--              >-->
<!--              <el-button-->
<!--                style="margin-left: 10px"-->
<!--                size="small"-->
<!--                type="success"-->
<!--                @click="$refs['upload'].submit()"-->
<!--                >开始上传</el-button-->
<!--              >-->
<!--              <div slot="tip" class="el-upload__tip">-->
<!--                支持文件格式：.rar .zip .doc .docx .pdf .jpg .png .gif .mp4 .xls-->
<!--                .xlsx-->
<!--                <br />单个文件不能超过20M-->
<!--              </div>-->
<!--            </el-upload>-->
<!--          </div>-->
<!--        </div>-->
<!--      </template>-->
    </xy-dialog>
  </div>
</template>

<script>
import { detail, save } from "@/api/bigScreen";
export default {
  props: {},
  data() {
    return {
      isShow: false,
      id: "",
      type: "",
      action: process.env.VUE_APP_UPLOAD_API,
      file: [],

      form: {
        type: "",
        key: "",
        value: "",
        sort: "",
      },
      rules: {},

      transformJSON: null,
    };
  },
  methods: {
    show() {
      this.isShow = true;
    },
    hidden() {
      this.isShow = false;
    },
    init() {
      for (let key in this.form) {
        if (this.form[key] instanceof Array) {
          this.form[key] = [];
        } else {
          this.form[key] = "";
        }
      }
      this.$refs["dialog"].clearValidate();
    },
    setId(id) {
      if (typeof id == "number") {
        this.id = id;
      } else {
        console.error("error typeof id: " + typeof id);
      }
    },
    getId() {
      return this.id;
    },
    setType(type = "add") {
      let types = ["add", "editor"];
      if (types.includes(type)) {
        this.type = type;
      } else {
        console.warn("Unknown type: " + type);
      }
    },
    setForm(key = [], value = []) {
      if (key instanceof Array) {
        key.forEach((key, index) => {
          this.form[key] = value[index] ?? "";
        });
      }
      if (typeof key === "string") {
        this.form[key] = value;
      }
      if (!key) {
        this.init();
      }
    },

    //上传
    successHandle(response, file, fileList, key) {
      this[key] = fileList;
    },
    removeHande(file, fileList, key) {
      this[key] = fileList;
    },
    uploadBefore(file) {
      console.log(file);
      // if (file.size / 1000 > 20 * 1024) {
      //   this.$message({
      //     type: "warning",
      //     message: "上传图片大小超过20MB！",
      //   });
      //   return false;
      // }
    },

    async getDetail() {
      const res = await detail(this.id);
      this.$integrateData(this.form, res);
    },

    submit() {
      if (this.type === "add") {
        if (this.form.hasOwnProperty("id")) {
          delete this.form.id;
        }
      }
      if (this.type === "editor") {
        Object.defineProperty(this.form, "id", {
          value: this.id,
          enumerable: true,
          configurable: true,
          writable: true,
        });
      }
      save(this.form).then((res) => {
        this.$message({
          type: "success",
          message:
            this.type === "add" ? "新增数据管理" : "编辑数据管理" + "成功",
        });
        this.isShow = false;
        this.$emit("refresh");
      });
    },

    str2JSON () {
      try {
        this.transformJSON = JSON.parse(this.form.value)
        console.log(this.transformJSON)
      } catch (err) {
        this.$message.error(err)
      }
    },
    JSON2str () {
      this.form.value = JSON.stringify(this.transformJSON)
    }
  },
  computed: {
    JSONHeader () {
      if (this.transformJSON instanceof Array && this.transformJSON[0] && typeof this.transformJSON[0] === 'object') {
        return Object.keys(this.transformJSON[0]).map(i => ({
          prop: i,
          label: i,
          customFn: row => (
            <el-input vModel={row[i]} size="small"></el-input>
          )
        }))
      } else {
        return []
      }
    }
  },
  watch: {
    isShow(val) {
      if (val) {
        if (this.type === "editor") {
          this.getDetail();
        }
      } else {
        this.transformJSON = null;
        this.id = "";
        this.type = "";
        this.init();
        this.$refs["dialog"].clearValidate();
        delete this.form.id;
      }
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-input__inner {
  text-align: left;
}
.xy-table-item-content {}
</style>
