<template>
  <div class="option-edit-wrap">
    <el-button
      type="info"
      size="small"
      icon="el-icon-edit"
      @click="editHandler(0)"
      v-if="selectItem.type == 'select'"
    >
    </el-button>
    <div class="btn-list" v-else>
      <el-button
        type="primary"
        size="small"
        icon="el-icon-plus"
        @click="addHandler"
        circle
      >
      </el-button>
      <el-button
        v-for="(btnData, index) in btnList"
        :key="index"
        type="info"
        size="small"
        icon="el-icon-edit"
        @click="editHandler(index)"
        >第{{ index + 1 }}级选项
      </el-button>
      <el-button
        circle
        type="danger"
        size="small"
        icon="el-icon-minus"
        @click="minusHandler"
      >
      </el-button>
    </div>
    <!-- 按钮 -->
    <el-dialog
      title="设置下拉选项数据"
      :visible.sync="isShow"
      width="50%"
      :before-close="cancleHandler"
    >
      <el-form
        ref="formDataRef"
        :model="formData"
        :rules="rules"
        label-width="140px"
      >
        <el-row type="flex" style="flex-wrap: wrap">
          <!-- <el-col :span="12">
            <el-form-item label="选项数据名" prop="dynamicName">
              <el-input
                v-model="formData.dynamicName"
                placeholder="请输入动态数据名"
                size="normal"
              ></el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="表名" prop="tableName">
              <el-select
                class="mr10"
                v-model="formData.tableName"
                placeholder="请选择表名"
                clearable
                filterable
                @change="
                  (value) => {
                    getFieldOptions(value);
                  }
                "
              >
                <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-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="描述字段(label)" prop="optLabelData">
              <el-select
                v-model="formData.optLabelData"
                placeholder="请选择字段"
                clearable
                filterable
              >
                <el-option
                  v-for="item in 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>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="值字段(value)" prop="optValueData">
              <el-select
                v-model="formData.optValueData"
                placeholder="请选择字段"
                clearable
                filterable
              >
                <el-option
                  v-for="item in 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>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div class="filter-table-wrap">
              <span class="title">添加数据过滤条件</span>
              <el-table :data="filterTableData" 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="
                        (value) => {
                          getFieldOptions(value, 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"
                      filterable
                      clearable
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in 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="flagValue" label="参照值" width="100">
                  <template slot-scope="scope">
                    <el-button
                      type="info"
                      size="small"
                      icon="el-icon-edit"
                      @click="editFlagHandler(scope.row, scope.$index)"
                    >
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="deleteFilterItem(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="addFilterHandler"
              >
                添加条件
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span>
          <el-button @click="cancleHandler">取消</el-button>
          <el-button type="primary" @click="conformHandler">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="编辑参照值" :visible.sync="flagShow" width="30%">
      <!-- :rules="rules" -->
      <el-form
        :model="flagFormData"
        ref="flagFormDataRef"
        label-width="100px"
        :rules="flagRules"
        :inline="false"
        size="normal"
      >
        <el-form-item label="参照类型">
          <el-select
            v-model="flagFormData.flagType"
            placeholder="请选择参照类型"
            filterable
          >
            <el-option
              v-for="item in flagTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="flagValue"
          v-show="flagFormData.flagType == 0"
          label="自定义值"
        >
          <el-input v-model="flagFormData.flagValue"></el-input>
        </el-form-item>
        <el-form-item
          prop="tableField"
          v-show="flagFormData.flagType == 1"
          label="关联表格字段"
        >
          <el-select
            class="mr10"
            v-model="flagFormData.tableField.tableName"
            placeholder="请选择表名"
            clearable
            filterable
            @change="
              (value) => {
                getFieldOptions(value, flagFormData.tableField);
              }
            "
          >
            <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-select
            v-model="flagFormData.tableField.fieldName"
            placeholder="请选择字段"
            clearable
            filterable
          >
            <el-option
              v-for="item in flagFormData.tableField.fieldOptions"
              :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-form-item>
        <el-form-item
          v-show="flagFormData.flagType == 2"
          label="固定值"
          size="normal"
        >
          <el-select
            v-model="flagFormData.flagValue"
            placeholder="请选择固定值"
            filterable
          >
            <el-option
              v-for="item in constFlagList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span>
          <el-button @click="flagShow = false">取消</el-button>
          <el-button type="primary" @click="flagConfirm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getFormName, getListName } from "@/api/dragform/form.js";
import { mapState } from "vuex";
import getOptionsSqlString from "@/utils/sqlString";
export default {
  name: "OptionsEdit",
  props: ["options", "selectItem", "dynamicKey"],
  components: {},
  data() {
    return {
      relateOptionShow: false,
      isShow: false,
      flagShow: false,
      flagEditIndex: "",
      formData: {
        dynamicName: "", //英文字符串
        tableName: "",
        optLabelData: "",
        optValueData: "",
      },
      filterTableData: [
        {
          fieldName: "",
          flagValue: "",
          fieldOptions: [],
          flagFormData: {
            flagType: 0,
            tableField: {
              tableName: "",
              fieldName: "",
              fieldOptions: [],
            },
            flagValue: "",
          },
        },
      ],

      flagFormData: {
        flagType: 0,
        tableField: {
          tableName: "",
          fieldName: "",
          fieldOptions: [],
        },
        flagValue: "",
      },
      flagTypeList: [
        {
          value: 0,
          label: "自定义",
        },
        // {
        //   value: 1,
        //   label: "关联其他字段",
        // },
        {
          value: 2,
          label: "固定值",
        },
      ],
      tableList: [],
      fieldList: [],
      rules: {
        tableName: [
          { required: true, message: "请选择表格名称", trigger: "change" },
        ],
        optLabelData: [
          { required: true, message: "请选择描述字段", trigger: "change" },
        ],
        optValueData: [
          { required: true, message: "请选择值字段", trigger: "change" },
        ],
      },
      flagRules: {
        flagType: [
          { required: true, message: "请选择参照值类型", trigger: "change" },
        ],
      },
      constFlagList: [
        {
          value: "#{USERID}",
          label: "当前用户相关数据",
        },
      ],
      //树形数据
      btnList: [
        // {
        //   sql: "",
        //   echoData: "",
        // },
      ],
      editIndex: "", //当前编辑层级
    };
  },
  watch: {
    myDynamicKey: {
      handler(nval) {
        this.formData.dynamicName = nval;
        console.log(this.formData.dynamicName);
      },
      deep: true,
    },
    mySelectItem: {
      handler(nval) {
        // if (
        //   nval.options.sqlData &&
        //   nval.options.sqlData.dynamicName == nval.options.dynamicKey
        // ) {
        //   this.btnList = nval.options.sqlData.echoDatas.map((item) => {
        //     return {
        //       sql: "",
        //       echoData: item,
        //     };
        //   });
        // }
      },
      deep: true,
      immediate: true,
    },
    myOptions: {
      handler(nval) {
        console.log("options", nval);
        this.btnList = [];
        this.reset();
        if (nval.sqlData && nval.sqlData.dynamicName == nval.dynamicKey) {
          this.btnList = nval.sqlData.echoDatas.map((item) => {
            return {
              sql: "",
              echoData: item,
            };
          });
        }
        console.log(this.btnList);
      },
      deep: true,
      immediate: true,
    },
    // 'formData.tableName': {
    //   handler(nval) {
    //     if(nval){}
    //   }
    // }
  },
  computed: {
    ...mapState({
      databaseName: (state) => state.user.dataSource.databaseName,
      databaseType: (state) => state.user.dataSource.databaseType,
    }),
    domType() {
      return this.selectItem.type; //select  treeSelect  cascader
    },
    myDynamicKey() {
      return this.dynamicKey;
    },
    mySelectItem() {
      return this.selectItem;
    },
    myOptions() {
      return this.options;
    },
  },
  methods: {
    // 添加一级回调
    addHandler() {
      this.btnList.push({
        sql: "",
        echoData: "",
      });
    },
    minusHandler() {
      this.btnList.pop();
    },
    reset() {
      Object.assign(this.formData, {
        dynamicName: "", //英文字符串
        tableName: "",
        optLabelData: "",
        optValueData: "",
      });
      this.filterTableData = [];
      Object.assign(this.flagFormData, {
        flagType: 0,
        tableField: {
          tableName: "",
          fieldName: "",
          fieldOptions: [],
        },
        flagValue: "",
      });
    },

    // 重置条件表单数据
    resetFlagFormData() {
      Object.assign(this.flagFormData, {
        flagType: 0,
        tableField: {
          tableName: "",
          fieldName: "",
          fieldOptions: [],
        },
        flagValue: "",
      });
    },
    // 开始编辑回调
    async editHandler(editIndex) {
      await this.getAllTable();
      // if (this.domType == "select") {
      //   this.isShow = true;
      // } else {
      //   this.relateOptionShow = true;
      // }
      this.editIndex = editIndex;
      let currentItem = this.btnList[editIndex];
      console.log(currentItem, "currentItem");
      if (currentItem?.echoData) {
        let { formData, filterTableData, flagFormData } = JSON.parse(
          currentItem.echoData
        );
        this.filterTableData = filterTableData;
        this.formData = formData;

        // this.flagFormData = flagFormData;
      } else {
        this.btnList[editIndex] = {
          sql: "",
          echoData: "",
        };
      }
      this.formData.dynamicName = this.myOptions.dynamicKey;
      if (this.formData.tableName) {
        this.getFieldOptions(this.formData.tableName);
      }
      this.isShow = true;
    },
    // 弹窗取消回调
    cancleHandler() {
      this.reset();
      this.isShow = false;
    },
    // 弹窗确认回调
    conformHandler() {
      let sql = getOptionsSqlString(this.formData, this.filterTableData);
      // let sqlData = {};
      // sqlData[this.formData.dynamicName] = sql;
      let echoData = {
        formData: {},
        filterTableData: [],
        // flagFormData: {},
      };
      Object.assign(echoData.formData, this.formData);
      Object.assign(echoData.filterTableData, this.filterTableData);
      // Object.assign(echoData.flagFormData, this.flagFormData);
      echoData.filterTableData.forEach((item) => {
        delete item.flagFormData.tableField.fieldOptions;
      });
      this.btnList[this.editIndex].sql = sql;
      this.btnList[this.editIndex].echoData = JSON.stringify(echoData);
      let sqlData = {};
      sqlData.dynamicName = this.formData.dynamicName;
      sqlData.sqls = this.btnList.map((item) => item.sql);
      sqlData.echoDatas = this.btnList.map((item) => item.echoData);
      this.$emit("setDynamicKey", sqlData);
      this.reset();

      this.isShow = false;
    },
    // 获取所有表格
    async getAllTable() {
      let data = {
        databaseName: this.databaseName,
        databaseType: this.databaseType,
      };
      let res = await getFormName(data);

      this.tableList = res.data;
    },
    async getFieldOptions(value, tempData) {
      let data = {
        databaseName: this.databaseName,
        databaseType: this.databaseType,
        tableName: value,
      };
      try {
        let res = await getListName(data);
        if (tempData) {
          tempData.fieldOptions = res;
        } else {
          this.fieldList = res;
        }
      } catch (error) {
        this.$message.error("网络异常,请稍后再试");
      }
    },
    // 删除一条筛选条件
    deleteFilterItem(index) {
      this.filterTableData.splice(index, 1);
    },
    // 新增一条筛选条件
    addFilterHandler() {
      this.filterTableData.push({
        // tableName: "",
        fieldName: "",
        flagValue: "",
        fieldOptions: [],
        flagFormData: {
          flagType: 0,
          tableField: {
            tableName: "",
            fieldName: "",
            fieldOptions: [],
          },
          flagValue: "",
        },
      });
    },
    // 编辑参照回调
    editFlagHandler(row, index) {
      this.flagEditIndex = index;
      this.flagFormData = JSON.parse(JSON.stringify(row.flagFormData));
      this.flagShow = true;
    },
    // 确认参照回调
    flagConfirm() {
      this.filterTableData[this.flagEditIndex].flagFormData = JSON.parse(
        JSON.stringify(this.flagFormData)
      );
      this.flagShow = false;
    },
  },
  async mounted() {
    console.log(this.options, this.selectItem);
    // if (this.selectItem.options.sqlData) {
    //   this.btnList = this.selectItem.options.sqlData.echoDatas.map((item) => {
    //     return {
    //       sql: "",
    //       echoData: item,
    //     };
    //   });
    //   console.log(this.btnList);
    // }
  },
};
</script>

<style scoped lang="scss">
.filter-table-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.btn-list {
  display: flex;
  flex-wrap: wrap;
}
</style>
