<template>
  <div class="style-wrap">
    <el-button
      type="primary"
      class="inline-large-button mb10"
      icon="el-icon-plus"
      size="mini"
      @click="addDataDialog"
    >
      添加样式
    </el-button>
    <!-- 样式表格 -->
    <el-table :data="styleTableData" style="width: 100%">
      <el-table-column label="序号" type="index" width="50"> </el-table-column>
      <el-table-column prop="styleName" label="样式名" width="100">
      </el-table-column>
      <el-table-column prop="styleDescription" label="描述" width="100">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-dropdown>
            <el-button type="warning" plain size="small">
              处理<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="editHandler(scope.row, scope.$index)"
                  >修改
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="delHandler(scope.$index)"
                  >删除
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="编辑样式" :visible.sync="dialogShow" width="50%">
      <el-form
        ref="styleFormDataRef"
        :model="styleFormData"
        label-width="100px"
        :rules="styleFormRules"
      >
        <el-form-item label="样式名" prop="styleName">
          <el-input v-model="styleFormData.styleName"></el-input>
        </el-form-item>
        <el-form-item label="样式描述" prop="styleDescription">
          <el-input
            type="textarea"
            v-model="styleFormData.styleDescription"
          ></el-input>
        </el-form-item>
        <el-form-item label="样式类型" prop="styleType">
          <el-radio-group v-model="styleFormData.styleType" size="small">
            <el-radio-button :label="0">行样式</el-radio-button>
            <el-radio-button :label="1">字段样式</el-radio-button>
            <el-radio-button :label="2">字典样式</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <div v-show="styleFormData.styleType == 0">
          <el-form-item label="背景颜色" prop="rowBgColor">
            <input
              type="color"
              :value="styleFormData.rowBgColor"
              @input="selectColors($event, 'rowBgColor')"
            />
          </el-form-item>
        </div>
        <div v-show="styleFormData.styleType == 1">
          <el-form-item label="样式生效字段" prop="styleTable">
            <el-col :span="10">
              <el-select
                v-model="styleFormData.styleTable"
                value-key=""
                placeholder="请选择表"
                filterable
              >
                <el-option
                  v-for="item in tableList"
                  :key="item.tableName"
                  :label="item.tableComment"
                  :value="item.tableName"
                >
                  <span style="float: left">{{ item.tableComment }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{
                    item.tableName
                  }}</span>
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="10">
              <el-select
                v-model="styleFormData.styleField"
                value-key=""
                placeholder="请选择字段"
                filterable
              >
                <el-option
                  v-for="item in styleFieldList"
                  :key="item.fieldName"
                  :label="item.fieldDescription"
                  :value="item.fieldName"
                >
                  <span style="float: left">{{ item.fieldDescription }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{
                    item.fieldName
                  }}</span>
                </el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label="文本样式">
            <el-radio-group v-model="styleFormData.fieldStyleType" size="small">
              <el-radio-button :label="0">普通文本</el-radio-button>
              <el-radio-button :label="1">标签</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <template v-if="styleFormData.fieldStyleType == 0">
            <el-form-item label="字体颜色">
              <input
                type="color"
                :value="styleFormData.fontColor"
                @input="selectColors($event, 'fontColor')"
              />
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item label="标签样式">
              <el-switch
                v-model="styleFormData.isTagFullBg"
                active-text="背景填充"
                inactive-text="仅文字"
              >
              </el-switch>
            </el-form-item>
            <el-form-item label="标签类型">
              <!-- <input
                type="color"
                :value="styleFormData.tagColor"
                @input="selectColors($event, 'tagColor')"
              /> -->
              <el-select v-model="styleFormData.tagType">
                <el-option
                  v-for="(item, index) in tagTypeList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>

              <el-tag
                class="ml10"
                size="normal"
                :type="styleFormData.tagType"
                :effect="styleFormData.isTagFullBg ? 'dark' : 'light'"
                >标签一</el-tag
              >
            </el-form-item>
          </template>
        </div>
        <div v-show="styleFormData.styleType == 2">
          <el-form-item label="字典生效字段" size="normal" prop="styleTable">
            <el-col :span="10">
              <el-select
                v-model="styleFormData.styleTable"
                value-key=""
                placeholder="请选择表"
                clearable
                filterable
              >
                <el-option
                  v-for="item in tableList"
                  :key="item.tableName"
                  :label="item.tableComment"
                  :value="item.tableName"
                >
                  <span style="float: left">{{ item.tableComment }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{
                    item.tableName
                  }}</span>
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="10">
              <el-select
                v-model="styleFormData.styleField"
                value-key=""
                placeholder="请选择字段"
                clearable
                filterable
              >
                <el-option
                  v-for="item in styleFieldList"
                  :key="item.fieldName"
                  :label="item.fieldDescription"
                  :value="item.fieldName"
                >
                  <span style="float: left">{{ item.fieldDescription }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{
                    item.fieldName
                  }}</span>
                </el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label="字典" size="normal">
            <el-select
              v-model="styleFormData.styleCondtion"
              placeholder="请选择字典"
              filterable
            >
              <el-option
                v-for="item in dictsList"
                :key="item.dictType"
                :label="item.dictName"
                :value="item.dictType"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div v-show="styleFormData.styleType != 2" class="condition-table-wrap">
          <span class="table-title">条件编辑</span>
          <el-table :data="conditionTableData" style="width: 100%">
            <el-table-column label="序号" type="index" width="50">
            </el-table-column>
            <el-table-column prop="tableName" label="表名" width="150">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.tableName"
                  @change="conditionTableChange(scope.row)"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in tableList"
                    :key="item.tableName"
                    :label="item.tableComment"
                    :value="item.tableName"
                  >
                    <span style="float: left">{{ item.tableComment }}</span>
                    <span
                      style="float: right; color: #8492a6; font-size: 13px"
                      >{{ item.tableName }}</span
                    >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="fieldName" label="字段名" width="150">
              <template slot-scope="scope">
                <el-select v-model="scope.row.fieldName" placeholder="请选择">
                  <el-option
                    v-for="item in scope.row.fieldList"
                    :key="item.fieldName"
                    :label="item.fieldDescription"
                    :value="item.fieldName"
                  >
                    <span style="float: left">{{ item.fieldDescription }}</span>
                    <span
                      style="float: right; color: #8492a6; font-size: 13px"
                      >{{ item.fieldName }}</span
                    >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="condition" label="条件" width="100">
              <template slot-scope="scope">
                <el-select v-model="scope.row.condition" placeholder="请选择">
                  <el-option
                    v-for="item in conditionList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="flagValue" label="参照值" width="100">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.flagValue"
                  @input="
                    scope.row.flagValue = scope.row.flagValue.replace(
                      /^(0+)|[^\d]+/g,
                      ''
                    )
                  "
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteConditionItem(scope.$index)"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button
            type="primary"
            class="inline-large-button mb10"
            icon="el-icon-plus"
            size="mini"
            style="width: 100%"
            @click="addConditionHandler"
          >
            添加条件
          </el-button>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogShow = false">取 消</el-button>
        <el-button type="primary" @click="saveStyleFormHandler"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listType } from "@/api/system/tenant/type";
export default {
  name: "StyleFormPanel",
  props: {
    tableFieldList: {
      default: [],
      type: Array,
    },
    dragTableStyleList: {
      default: [],
      type: Array,
    },
  },
  components: {},
  data() {
    return {
      dialogShow: false,
      // 表格及字段数据
      tableList: [],
      isShowFieldList: [],
      allFieldList: [],
      editIndex: -1,
      // 表格样式数据
      styleTableData: [],
      styleFormData: {
        styleName: "",
        styleDescription: "",
        styleType: 0, //0:行样式  1:字段样式 2:字典样式
        styleTable: "", //样式生效的表
        styleField: "", //样式生效的字段
        tableName: "",
        styleCode: "",
        styleCondtion: "",
        rowBgColor: "", //行背景色
        fieldStyleType: 0, //字段样式类型 0:普通文本  1:标签
        fontColor: "", //字体颜色
        isTagFullBg: false, //tag背景色是否填满
        tagType: "",
        conditionTableStr: "",
      },
      styleFormRules: {
        styleName: [
          { required: true, message: "请输入样式名", trigger: "blur" },
        ],
        styleTable: [
          { validator: this.styleFieldValidator, trigger: "change" },
        ],
      },
      conditionTableData: [
        // {
        //   tableName: "",
        //   fieldName: "",
        //   condition: 1, //1:> 2:< 3:= 4:>= 5:<=
        //   flagValue: 0,
        //   fieldList: [],
        // },
      ],
      conditionList: [
        {
          value: 1,
          label: ">",
        },
        {
          value: 2,
          label: "<",
        },
        {
          value: 3,
          label: "=",
        },
        {
          value: 4,
          label: ">=",
        },
        {
          value: 5,
          label: "<=",
        },
      ],
      tagTypeList: [
        {
          value: "",
          label: "默认",
        },
        {
          value: "success",
          label: "成功",
        },
        {
          value: "info",
          label: "普通",
        },
        {
          value: "warning",
          label: "警告",
        },
        {
          value: "danger",
          label: "危险",
        },
      ],
      // 字典列表
      dictsList: [],
    };
  },
  computed: {
    styleFieldList() {
      return this.isShowFieldList.filter(
        (item) => item.tableName == this.styleFormData.styleTable
      );
    },
  },
  watch: {
    tableFieldList: {
      handler(nval) {
        if (!nval || !nval.length) return;
        this.allFieldList = nval;
        this.isShowFieldList = nval.filter((item) => item.isShow);
        let tempList = nval.map((item) => {
          return {
            tableName: item.tableName,
            tableComment: item.tableComment,
          };
        });
        this.tableList = [];
        tempList.forEach((item) => {
          let isHas = this.tableList.find(
            (it) => it.tableName == item.tableName
          );
          if (!isHas) {
            this.tableList.push(item);
          }
        });
      },
      immediate: true,
      deep: true,
    },
    dragTableStyleList: {
      handler(nval) {
        let res = nval.map((item) => {
          let tampItem = JSON.parse(JSON.stringify(item));
          let styleCode = JSON.parse(tampItem.styleCode);
          let { rowBgColor, fieldStyleType, fontColor, isTagFullBg, tagType } =
            styleCode;
          let fieldData = tampItem.styleField?.split(".");
          Object.assign(tampItem, {
            rowBgColor,
            fieldStyleType,
            fontColor,
            isTagFullBg,
            tagType,
            conditionTableStr: tampItem.styleCondtion,
            styleTable: fieldData ? fieldData[0] : "",
            styleField: fieldData ? fieldData[1] : "",
          });
          return tampItem;
        });
        this.styleTableData = res;
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    // 添加一条样式数据回调
    addDataDialog(index, row) {
      this.resetStyleFormData();
      this.dialogShow = true;
    },

    // 重置样式表单
    resetStyleFormData() {
      Object.assign(this.styleFormData, {
        styleName: "",
        styleDescription: "",
        styleType: 0,
        tableName: "",
        styleCode: "",
        styleCondtion: "",
        rowBgColor: "",
        fieldStyleType: 0,
        fontColor: "",
        isTagFullBg: false,
        tagType: "",
        styleTable: "",
        styleField: "",
      });
      this.conditionTableData = [];
    },

    //样式表单保存回调
    saveStyleFormHandler() {
      this.$refs.styleFormDataRef.validate((valid) => {
        if (valid) {
          // 校验样式生效条件的表格数据
          let validateRes = this.validateCondition();
          if (!validateRes.flag) {
            this.$message.error(validateRes.msg);
            return;
          }
          let tempConditionTableData = this.conditionTableData.map((item) => ({
            tableName: item.tableName,
            fieldName: item.fieldName,
            condition: item.condition,
            flagValue: item.flagValue,
          }));
          this.styleFormData.conditionTableStr = JSON.stringify(
            tempConditionTableData
          );
          let tempFormData = JSON.parse(JSON.stringify(this.styleFormData));
          console.log(tempFormData, this.editIndex);
          if (this.editIndex != -1) {
            //修改
            this.$set(this.styleTableData, this.editIndex, tempFormData);
            // this.styleTableData[this.editIndex] = tempFormData;
            this.editIndex = -1;
          } else {
            //新增
            this.styleTableData.push(tempFormData);
          }
          console.log(this.styleTableData);
          this.dialogShow = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //添加样式判断条件回调
    addConditionHandler() {
      this.conditionTableData.push({
        tableName: "",
        fieldName: "",
        condition: 1, //1:> 2:< 3:= 4:>= 5:<=
        flagValue: 0,
        fieldList: [],
      });
    },

    // 颜色改变回调
    selectColors(event, tempField) {
      console.log(tempField);
      this.styleFormData[tempField] = event.target.value;
    },

    // 条件表改变回调
    conditionTableChange(row) {
      if (!row.tableName) return;
      row.fieldList = this.allFieldList.filter(
        (item) => item.tableName == row.tableName
      );
    },

    // 条件表删除回调
    deleteConditionItem(index) {
      this.conditionTableData.splice(index, 1);
    },

    // 编辑样式回调
    editHandler(row, index) {
      this.editIndex = index;
      this.styleFormData = JSON.parse(JSON.stringify(row));
      console.log(row.conditionTableStr);
      if (row.styleType != 2) {
        this.conditionTableData = JSON.parse(row.conditionTableStr);
        this.conditionTableData.forEach((item) => {
          this.conditionTableChange(item);
        });
      }

      this.dialogShow = true;
    },

    // 删除样式回调
    delHandler(index) {
      this.styleTableData.splice(index, 1);
    },

    // 获取保存数据
    getSaveData() {
      let res = this.styleTableData.map((item) => {
        let styleCode = {
          rowBgColor: item.rowBgColor,
          fieldStyleType: item.fieldStyleType,
          fontColor: item.fontColor,
          isTagFullBg: item.isTagFullBg,
          tagType: item.tagType,
        };
        return {
          styleName: item.styleName,
          styleDescription: item.styleDescription,
          styleCode: JSON.stringify(styleCode),
          styleCondtion:
            item.styleType == 2 ? item.styleCondtion : item.conditionTableStr,
          styleField: item.styleTable + "." + item.styleField,
          styleType: item.styleType,
        };
      });
      return res;
    },

    // 获取样式条件中的表名和字段
    getStyleTableField() {
      let res = [];
      this.styleTableData
        .filter((item) => item.styleType != 2)
        .map((item) => {
          let tableList = JSON.parse(item.conditionTableStr);
          tableList.forEach((val) => {
            res.push(val.tableName + "." + val.fieldName);
          });
        });
      return res;
    },

    // 样式生效字段的表格验证
    styleFieldValidator(rule, value, callBack) {
      if (this.styleFormData.styleType == 0) return callBack();
      let { styleTable, styleField } = this.styleFormData;
      if (!styleTable) return callBack(new Error("请选择表格"));
      if (!styleField) return callBack(new Error("请选择字段"));
      callBack();
    },

    // 校验样式生效条件
    validateCondition() {
      let { styleType } = this.styleFormData;
      if (styleType == 2) return { flag: true };
      let res = {
        flag: true,
      };
      try {
        this.conditionTableData.forEach((item) => {
          if (!item.tableName || !item.fieldName) {
            res.flag = false;
            res.msg = "请完善表格数据(表格名/字段名)";
            throw new Error("validate error");
          }
        });
      } catch (error) {
        if (error != "validate error") console.log(error);
      }
      return res;
    },
  },
  async mounted() {
    let res = await listType(this.addDateRange({ isEnablePaging: false }, []));
    this.dictsList = res.rows;
  },
};
</script>

<style scoped lang="scss">
.style-wrap {
  .condition-table-wrap {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    .table-title {
      margin-bottom: 10px;
      font-size: 16px;
      font-weight: 600;
    }
  }
}
</style>
