<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">
          <el-upload
            name="file"
            accept="image/jpeg,image/png"
            :file-list="fileList"
            :action="api + '/bill/file/commonupload'"
            list-type="picture-card"
            :on-remove="handleRemoveImg"
            :on-success="handleExampleImgSuccess"
            :on-preview="handlePreview"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0"></el-input-number>
        </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" @click="handleOk"
          >确 定</el-button
        >
      </span>
      <!-- 图片查看 -->
      <el-image-viewer
        v-if="preview"
        :appendToBody="false"
        :on-close="
          () => {
            (preview = false), (filepaths = []);
          }
        "
        :url-list="filepaths"
      />
    </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: "",
    },
    addVisible: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  data() {
    return {
      api: process.env.VUE_APP_API_BASE_URL,
      fileList: [],
      preview: false,
      filepaths: [],
      inputVisible: false,
      inputValue: "",
      form: {
        areaName: "",
        areaCode: "",
        areaId: "",
        siteId: "",
        siteCode: "",
        siteName: "",
        latitude: "",
        longitude: "",
        type: "",
        bigPath: "",
        tag: [],
        sort: 99,
        remark: "",
        icon: "",
        accessSystemList: [],
      },
      rules: {
        areaName: [
          { required: true, message: "请选择区域", trigger: "change" },
        ],
        bigPath: [{ required: true, message: "请选择区域", trigger: "change" }],
      },
    };
  },
  computed: {
    ...mapState("user", ["areaTree"]),
    Visible: {
      get() {
        return this.addVisible;
      },
      set(val) {
        this.$emit("update:addVisible", val);
      },
    },
    initTree() {
      return this.addAreaNameField(this.areaTree);
    },
  },
  methods: {
    // 确定
    handleOk() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          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("addSuccess");
            this.handleClose();
          }
        }
      });
    },
    // 新增
    onAdd() {
      Object.assign(this.form, this.$options.data().form);
      this.form.id && this.$delete(this.form, "id");
    },
    // 编辑
    onEdit(row) {
      setTimeout(() => {
        if (row.tag) {
          row.tag = row.tag.split(",");
        }
        if (row.bigPath) {
          this.fileList = [
            {
              name: row.bigPath,
              url: row.bigPath,
            },
          ];
        }
        this.form = row;
      }, 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;
    },
    handleExampleImgSuccess(response, file, fileList) {
      if (response.code && response.code == 1) {
        let list = fileList.slice(-1);
        this.fileList = list.map((v) => {
          if (v.response) {
            v.url = v.response.url;
          }
          return v;
        });
        this.form.bigPath = response.url;
      } else {
        let msg = response.msg || "上传失败";
        this.$message.error(msg);
      }
    },
    // 删除示例图片
    handleRemoveImg() {
      this.form.bigPath = "";
      this.fileList = [];
    },
    // 预览
    handlePreview(file) {
      this.filepaths = [file.url];
      this.preview = true;
    },
    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>
