<template>
  <div>
    <el-dialog
      :title="title"
      :destroy-on-close="true"
      :visible.sync="Visible"
      width="30%"
      @close="handleClose"
      :close-on-click-modal="false"
      top="10vh"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        size="small"
        label-width="100px"
      >
        <el-form-item label="区域" prop="areaName">
          <InputTree
            :treeData="initTree"
            v-model="form.areaName"
            @change="changeArea"
          ></InputTree>
        </el-form-item>
        <el-form-item label="系统标签" prop="tag">
          <div class="flex gap-2">
            <el-tag
              v-for="(v, i) in form.tag"
              :key="i"
              closable
              :disable-transitions="false"
              @close="handleCloseTag(v)"
            >
              {{ v }}
            </el-tag>
            <el-input
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            >
            </el-input>
            <el-button v-else size="small" @click="showInput">+</el-button>
          </div>
        </el-form-item>
        <el-form-item label="背景图片" prop="bigPath">
          <YUpload
            accept=".png,.gif,.jpeg,.jpg"
            list-type="picture-card"
            v-model="form.bigPath"
          ></YUpload>
        </el-form-item>
        <el-form-item label="对接日期" prop="accessTime">
          <el-date-picker
            v-model="form.accessTime"
            type="date"
            value-format="timestamp"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="form.sort"
            controls-position="right"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="描述" prop="content">
          <el-input
            resize="none"
            :autosize="{ minRows: 3, maxRows: 3 }"
            type="textarea"
            placeholder="请输入描述"
            v-model="form.content"
          ></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            resize="none"
            :autosize="{ minRows: 3, maxRows: 3 }"
            type="textarea"
            placeholder="请输入备注"
            v-model="form.remark"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleRest">重 置</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          @click="handleOk"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { saveAccess } from "@/api/system";
import InputTree from "./InputTree.vue";
export default {
  components: {
    InputTree,
  },
  props: {
    title: {
      type: String,
      required: true,
      default: "",
    },
    show: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  data() {
    return {
      api: process.env.VUE_APP_API_BASE_URL,
      loading: false,
      inputVisible: false,
      inputValue: "",
      form: {
        areaName: "",
        areaCode: "",
        areaId: "",
        siteId: "",
        siteCode: "",
        siteName: "",
        latitude: "",
        longitude: "",
        type: "",
        bigPath: "",
        tag: [],
        sort: 99,
        remark: "",
        icon: "",
        accessTime: "", // 接入时间
        content: "", // 内容
        accessSystemList: [],
      },
      rules: {
        areaName: [
          { required: true, message: "请选择区域", trigger: "change" },
        ],
        bigPath: [
          { required: true, message: "请上传背景图片", trigger: "change" },
        ],
      },
    };
  },
  computed: {
    ...mapState("user", ["areaTree"]),
    Visible: {
      get() {
        return this.show;
      },
      set(val) {
        this.$emit("update:show", val);
      },
    },
    initTree() {
      return this.addAreaNameField(this.areaTree);
    },
  },
  methods: {
    // 确定
    handleOk() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          let res = await saveAccess({
            ...this.form,
            tag: this.form.tag.join(","),
          });
          let { code, msg } = res.data;
          if (code === 1) {
            this.$message.success(msg);
            this.$emit("success");
            this.handleClose();
          }
          this.loading = false;
        }
      });
    },
    // 新增
    onAdd() {
      Object.assign(this.form, this.$options.data().form);
      this.form.id && this.$delete(this.form, "id");
    },
    // 编辑
    onEdit(row) {
      setTimeout(() => {
        this.form = row;
        if (this.form.tag) {
          this.form.tag = this.form.tag.split(",");
        } else {
          this.form.tag = [];
        }
      }, 10);
    },
    // 重置
    handleRest() {
      this.fileList = [];
      this.$resetForm("form");
    },
    // 关闭
    handleClose() {
      this.fileList = [];
      this.$resetForm("form");
      this.Visible = false;
    },
    changeArea(row) {
      let {
        areaName,
        areaCode,
        id,
        label,
        siteCode,
        latitude,
        longitude,
        type,
      } = row;

      this.form.areaId = "";
      this.form.siteId = "";
      this.form.siteName = "";

      if (type === "area") {
        this.form.areaId = id;
      } else if (type === "site") {
        this.form.siteId = id;
        this.form.siteName = label;
      }

      this.form.areaName = areaName;
      this.form.areaCode = areaCode;
      this.form.latitude = latitude;
      this.form.longitude = longitude;
      this.form.siteCode = siteCode;
      this.form.type = type;
    },

    addAreaNameField(data) {
      let arr = data;
      arr.forEach((item) => {
        if (!item.areaName) {
          item.areaName = item.label;
        }
        if (item.children && item.children.length > 0) {
          this.addAreaNameField(item.children);
        }
      });
      return arr;
    },

    handleCloseTag(tag) {
      this.form.tag.splice(this.form.tag.indexOf(tag), 1);
    },

    showInput() {
      if (this.form.tag.length >= 2) {
        this.$message.warning("暂时只能添加两个系统标签");
        return;
      }
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        if (this.form.tag.includes(inputValue)) {
          this.$message.warning("已存在相同标签");
          return;
        }
        this.form.tag.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
  },
};
</script>

<style lang="less" scoped>
:deep(.el-select) {
  width: 100%;
}
:deep(.el-cascader) {
  width: 100%;
}
</style>
