<template>
  <div>
    <el-dialog
      :title="title"
      width="70%"
      :visible.sync="open"
      @close="cancelTags"
    >
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="add"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="update"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            >删除</el-button
          >
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-table
            :height="'62vh'"
            border
            v-loading="loading"
            :data="handle"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
              label="类型"
              align="center"
              prop="type"
              :formatter="typeFormat"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="字段/点位"
              align="center"
              prop="point"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="共享类型"
              align="center"
              prop="shareType"
              :formatter="shareTypeFormat"
              v-if="column"
              :show-overflow-tooltip="true"
            />
            <el-table-column label="是否为判断" align="center">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.judge" disabled></el-switch>
              </template>
            </el-table-column>
            <el-table-column
              label="获取原始值"
              align="center"
              prop="pointValue"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="组态改变值"
              align="center"
              prop="changeValue"
              :show-overflow-tooltip="true"
            />
          </el-table>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitHandle">确 定</el-button>
        <el-button @click="submitHandle">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="'添加配置'"
      width="65%"
      :visible.sync="load"
      @close="cancel"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        :inline="true"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="组态类型" prop="type">
              <el-select
                v-model="form.type"
                filterable
                placeholder="请选择组态类型"
              >
                <el-option
                  v-for="dict in tagAttribute"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!form.customChart || form.type != 'data'">
            <el-form-item label="数据字段/点位" prop="point">
              <el-input
                v-model="form.point"
                placeholder="请输入数据字段/点位"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="form.type != 'data'">
          <el-col :span="12" v-show="column">
            <el-form-item label="共享类型" prop="shareType">
              <el-select
                v-model="form.shareType"
                filterable
                placeholder="请选择共享类型"
              >
                <el-option
                  v-for="dict in shareTypeList"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否为判断" prop="judge">
              <el-radio-group v-model="form.judge" size="small">
                <el-radio :label="true" border>开启</el-radio>
                <el-radio :label="false" border>关闭</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="form.judge">
            <el-form-item label="获取原始值" prop="pointValue">
              <el-input
                v-model="form.pointValue"
                placeholder="请输入获取原始值"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="form.judge">
            <!-- prop="changeValue" -->
            <el-form-item label="组态改变值" prop="changeValue">
              <el-input
                v-if="form.type != 'icon' && form.type != 'image'"
                v-model="form.changeValue"
                placeholder="请输入组态改变值"
              />
              <el-select
                v-if="form.type === 'icon'"
                multiple
                v-model="selectIcons"
                @change="iconChange"
                collapse-tags
                filterable
                style="margin-left: 20px"
                placeholder="请输入组态改变值"
              >
                <el-option-group
                  v-for="item in options"
                  :key="item.group"
                  :label="item.group"
                >
                  <el-option
                    v-for="item1 in item.children"
                    :key="item1.icon"
                    :label="item1.data.icon + '%' + item1.data.iconFamily"
                    :value="item1.data.icon + '%' + item1.data.iconFamily"
                  >
                    <i
                      :class="`iconfont ${item1.icon}`"
                      style="font-size: 25px"
                    ></i>
                  </el-option>
                </el-option-group>
              </el-select>
              <el-select
                v-if="form.type === 'image'"
                multiple
                v-model="selectImage"
                @change="imageChange"
                collapse-tags
                filterable
                style="margin-left: 20px"
                placeholder="请输入组态改变值"
              >
                <el-option
                  v-for="item of imageList"
                  :key="item.id"
                  :label="item.id"
                  :value="baseapi + item.url"
                >
                  <span>
                    {{ item.id }}
                  </span>
                  <el-image
                    style="width: 25px; height: 25px; float: right"
                    :src="baseapi + item.url"
                    :fit="fit"
                  ></el-image>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="form.type === 'data'">
          <el-col :span="12">
            <el-form-item label="图表名称" prop="title">
              <el-input
                v-model="form.title"
                placeholder="请输入echarts Title"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="自定义图表" prop="customChart">
              <!-- <el-switch
                v-model="form.customChart"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="switchChange"
              >
              </el-switch> -->
              <el-radio-group v-model="form.customChart" size="small">
                <el-radio :label="true" border>开启</el-radio>
                <el-radio :label="false" border>关闭</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-show="form.customChart">
            <el-row>
              <el-col :span="24">
                <el-button
                  size="mini"
                  @click="handleAdd()"
                  type="primary"
                  style="margin-bottom: 5px"
                  >添加</el-button
                >
                <el-table ref="mytable" :data="table_data" style="width: 100%">
                  <el-table-column
                    align="center"
                    v-for="(item, index, key) in table_columns"
                    :item="item"
                    :key="key"
                    :index="index"
                    :label="item.label"
                  >
                    <template slot-scope="scope">
                      <el-input
                        v-if="scope.row.edit && item.input === 'text'"
                        size="small"
                        v-model="scope.row[item.prop]"
                        :placeholder="'请输入' + item.label"
                      ></el-input>
                      <el-select
                        v-if="scope.row.edit && item.input === 'select'"
                        v-model="scope.row[item.prop]"
                        filterable
                        :placeholder="'请选择' + item.label"
                      >
                        <el-option :value="''" label="请选择"> </el-option>
                        <el-option
                          v-for="dict in dictEcharts(item.selectName)"
                          :key="dict.dictValue"
                          :label="dict.dictLabel"
                          :value="dict.dictValue"
                        >
                        </el-option>
                      </el-select>
                      <span v-if="!scope.row.edit">{{
                        dictEchartsFormat(item.selectName, scope.row[item.prop])
                      }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                      <!-- 全局控制的编辑 -->
                      <div
                        v-if="is_edit && scope.row.add == undefined"
                        style="display: inline-block"
                      >
                        <!-- 编辑 -->
                        <el-button
                          size="mini"
                          v-if="!scope.row.edit"
                          @click="handleEdit(scope.$index, scope.row)"
                          type="primary"
                          style="margin-right: 5px"
                          >Edit</el-button
                        >
                        <!-- 保存 -->
                        <el-button
                          size="mini"
                          type="success"
                          :plain="true"
                          v-if="scope.row.edit"
                          @click="handleSave(scope.$index, scope.row)"
                          style="margin-right: 5px"
                          >Save</el-button
                        >
                      </div>
                      <!-- 添加控制 -->
                      <div
                        v-if="scope.row.add != undefined && scope.row.add"
                        style="display: inline-block"
                      >
                        <!-- 保存 -->
                        <el-button
                          size="mini"
                          type="success"
                          :plain="true"
                          v-if="scope.row.edit"
                          @click="handleSave(scope.$index, scope.row)"
                          >Save</el-button
                        >
                      </div>
                      <!-- 全局控制删除 -->
                      <el-button
                        size="mini"
                        v-if="is_delete && scope.row.add == undefined"
                        :plain="true"
                        type="danger"
                        @click="handleDeleteIt(scope.$index, scope.row)"
                        >Delete</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
let type = [{ required: true, message: "请选择组态类型", trigger: "change" }];
let point = [{ required: true, message: "请填写字段/点位", trigger: "blur" }];
let shareType = [
  { required: true, message: "请选择共享类型", trigger: "change" },
];
let judge = [
  { required: true, message: "请选择是否为判断", trigger: "change" },
];
//type: "boolean",
let customChart = [
  {
    type: "boolean",
    required: true,
    message: "请选择自定义图表",
    trigger: "blur",
  },
];
let pointValue = [
  {
    required: true,
    message: "请填写原始值",
    trigger: "blur",
  },
];
let changeValue = [
  {
    required: true,
    message: "请填写改变值",
    trigger: "blur",
  },
];
let title = [
  {
    type: "string",
    required: true,
    message: "请填写图表名称",
    trigger: "blur",
  },
];
import { getDatas } from "@/utils/topology/registerIconssetting.js";
import {list} from "@/api/topology.js"
export default {
  data() {
    return {
      imageList: [],
      baseapi: process.env.VUE_APP_BASE_API,
      title: "",
      row: {},
      column: false,
      open: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      options: [],
      selectIcons: [],
      selectImage: [],
      form: {
        type: "",
        point: "",
        shareType: "",
        judge: false,
        customChart: true,
        pointValue: "",
        changeValue: "",
        title: "",
        echartsArray: [],
      },
      rules: {},
      loading: false,
      handle: [],
      //tagType类型
      tagType: [],
      load: false,
      tagAttribute: [],
      shareTypeList: [],
      //以下为测试

      new_date_json: {}, //数据结构
      is_edit: true, //是否可编辑
      is_delete: true, //是否可删除
      //表头信息
      table_columns: [
        {
          prop: "axis",
          label: "echarts轴",
          input: "select",
          selectName: "echarts_axis",
        },
        {
          prop: "name",
          label: "名称",
          input: "text",
        },
        {
          prop: "point",
          label: "数据字段/点位",
          input: "text",
        },
        {
          prop: "seriesType",
          label: "echarts类型",
          input: "select",
          selectName: "echarts_series_type",
        },
      ],
      //表格数据
      table_data: [],
      echartsAxisList: [],
      echartsSeriesTypeList: [],
    };
  },
  watch: {
    //动态校验
    "form.type": {
      handler(n, o) {
        this.rules = {};
        this.rules.type = type;
        if (n === "") {
          return;
        }
        if (n != "data") {
          this.rules.point = point;
          this.form.customChart = false;
          this.rules.judge = judge;
          if (this.column) {
            this.rules.shareType = shareType;
          }
        } else {
          this.rules.point = "";
          this.rules.title = title;
          this.rules.customChart = customChart;
        }
      },
      immediate: true,
      deep: true,
    },
    "form.customChart": {
      handler(n, o) {
        console.log(n);
        if (n === "") {
          return;
        }
        if (!n) {
          this.rules.point = point;
        }
      },
      immediate: true,
      deep: true,
    },
    "form.judge": {
      handler(n, o) {
        if (n === "") {
          return;
        }
        if (this.form.type != "data" && n) {
          this.rules.pointValue = pointValue;
          this.rules.changeValue = changeValue;
        } else {
          delete this.rules.pointValue;
          delete this.rules.changeValue;
        }
      },
      immediate: true,
      deep: true,
    },
  },
  created() {
    this.options = getDatas();
  },
  methods: {
    getList() {
      list().then((res) => {
        if (res.code === 200) {
          this.imageList = res.data;
        }
      });
    },
    imageChange(val) {
      this.form.changeValue = val.join(",");
    },
    iconChange(val) {
      this.form.changeValue = val.join(",");
    },
    switchChange(val) {
      console.log(val);
    },
    handleDelete() {
      for (let i = this.ids.length - 1; i >= 0; i--) {
        this.handle.splice(this.handle.indexOf(this.ids[i]), 1);
      }
      this.ids = [];
      this.$message.success("删除成功");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => {
        return item;
      });
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    getTagAttribute() {
      this.getDicts("tag_attribute").then((response) => {
        this.tagAttribute = response.data;
      });
    },
    getShareTypeList() {
      this.getDicts("share_type").then((response) => {
        this.shareTypeList = response.data;
      });
    },
    getEchartsAxisList() {
      this.getDicts("echarts_axis").then((response) => {
        this.echartsAxisList = response.data;
      });
    },
    getEchartsSeriesTypeList() {
      this.getDicts("echarts_series_type").then((response) => {
        this.echartsSeriesTypeList = response.data;
      });
    },
    init(row, data) {
      this.open = true;
      this.title = "配置" + row.tag;
      this.row = Object.assign({}, row);
      this.column = data.dataAcquisitionMode === "4" ? true : false;
      this.handle = this.row.handle;
      this.getList();
      this.getTagAttribute();
      this.getShareTypeList();
      this.getEchartsAxisList();
      this.getEchartsSeriesTypeList();
    },
    typeFormat(row, column) {
      return this.selectDictLabel(this.tagAttribute, row.type);
    },
    shareTypeFormat(row, column) {
      return this.selectDictLabel(this.shareTypeList, row.shareType);
    },
    dictEchartsFormat(type, val) {
      if (type === "echarts_axis") {
        return this.selectDictLabel(this.echartsAxisList, val);
      }
      if (type === "echarts_series_type") {
        return this.selectDictLabel(this.echartsSeriesTypeList, val);
      }
      return val;
    },
    dictEcharts(type) {
      if (type === "echarts_axis") {
        return this.echartsAxisList;
      }
      if (type === "echarts_series_type") {
        return this.echartsSeriesTypeList;
      }
      return [];
    },

    add() {
      this.load = true;
    },
    update() {
      this.load = true;
      this.$nextTick(() => {
        this.form = Object.assign({}, this.ids[0]);
        if (!this.form.echartsArray) {
          this.form.echartsArray = [];
        }
        if (this.form.type === "icon") {
          this.selectIcons = this.form.changeValue.split(",");
        }
        if (this.form.type === "image") {
          this.selectImage = this.form.changeValue.split(",");
        }
        this.initEditAttribute();
      });
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let params = Object.assign({}, this.form);
          if (this.form.changeValue) {
            if (this.form.changeValue instanceof Array) {
              params.changeValue = this.form.changeValue.join(",");
            }
          }

          if (params.type === "data") {
            if (!params.customChart) {
              if (this.table_data.length < 1) {
                this.$message.warning("请添加图表数据");
                return;
              }
            }
          }
          params.echartsArray = [...this.table_data];
          if (this.handle.indexOf(this.ids[0]) > -1) {
            this.handle.splice(this.handle.indexOf(this.ids[0]), 1, params);
            this.ids = [];
            this.$message.success("修改成功");
          } else {
            this.$message.success("添加成功");
            this.handle.push(params);
          }
          this.cancel();
        }
      });
    },
    reset() {
      this.table_data = [];
      // this.resetForm("form");
      this.$refs["form"].resetFields();
    },
    cancel() {
      this.load = false;
      this.reset();
    },
    cancelTags() {
      this.open = false;
      this.handle = [];
      this.row = {};
      this.column = false;
    },
    submitHandle() {
      this.cancelTags();
    },

    // 以下为测试
    //编辑
    handleEdit(index, row) {
      row.edit = true;
    },
    //删除
    handleDeleteIt(index, row) {
      this.table_data.splice(index, 1);
      this.$message({
        message: "删除成功！",
        type: "success",
      });
    },
    //保存
    handleSave(index, row) {
      row.edit = false;
      delete this.table_data[index].add;
      this.$message({
        message: "保存成功！",
        type: "success",
      });
    },
    handleAdd() {
      var addDataJson = {};

      for (var key in this.new_date_json) {
        if (key === "edit") {
          delete addDataJson[key];
        } else if (key === "add") {
          delete addDataJson[key];
        } else {
          addDataJson[key] = "";
        }
      }
      addDataJson.edit = true;
      addDataJson.add = true;
      this.table_data.push(addDataJson);
    },
    //初始化编辑属性
    initEditAttribute() {
      var self = this;
      var edit = self.edit;
      let [...dataArray] = this.form.echartsArray;
      if (dataArray.length > 0) {
        //添加编辑事件
        for (var index in dataArray) {
          dataArray[index]["edit"] = false;
          this.table_data.push(dataArray[index]);
        }

        if (Object.keys(this.new_date_json).length === 0) {
          //新增时，初始化数据结构
          this.initAddDataJson(dataArray[0]);
        }
      }
    },
    initAddDataJson(dataArray) {
      //新增时，初始化数据结构
      var dataJson = dataArray;
      var newDateJson = {};
      for (var key in dataJson) {
        if (key === "edit") {
          newDateJson[key] = "true";
        } else {
          newDateJson[key] = "";
        }
      }
      newDateJson["add"] = true;
      this.new_date_json = newDateJson;
    },
  },
};
</script>
<style>
</style>