<template>
  <div class="my_form">
    <el-form
      ref="label_form"
      :inline="true"
      :model="formData"
      class="div_form"
      :rules="rules"
    >
    <!--  v-if="formType == 'info'&& addFormLabel" -->
      <el-form-item
        label="标签名称"
        label-width="100px"
        prop="tagName"
      >
        <el-autocomplete
          v-model="formData.tagName"
          value-key="tagName"
          :fetch-suggestions="querySearchAsync"
          @blur="handelChangeTagName"
          placeholder="请输入内容进行搜索"
          @select="handleSelect"
        ></el-autocomplete>
      </el-form-item>
      <!-- <el-form-item label="标签名称（新增）" label-width="100px" prop="tagName" v-else>
        <el-input
          v-model="formData.tagName"
          placeholder="请输入内容"
          @blur="handelChangeTagName"
          clearable
        ></el-input>
      </el-form-item> -->
    </el-form>
    <p style="margin-left: 15px"><b style="color: #f56c6c">*</b> 匹配数据</p>
    <el-table border :data="tableData" style="width: 100%" height="200">
      <el-table-column label="选择数据源" align="center" width="120">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.dataSource"
            placeholder="请选择"
            :disabled="formType == 'info'"
            @change="handleChangeSource(scope.row, scope.$index)"
            clearable
          >
            <el-option
              v-for="item in dataSourceOpction"
              :label="item.label"
              :value="item.value"
              :key="item.value"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="字段类别" align="center" width="120">
        <template slot-scope="scope" v-if="scope.row.dataSource == 'resi'">
          <el-select
            v-model="scope.row.itemGroupId"
            placeholder="请选择"
            :disabled="formType == 'info'"
            clearable
            @change="handleChangeFieldsType(scope.row, scope.$index)"
          >
            <el-option
              v-for="item in scope.row.itemGroupIdOpction"
              :label="item.label"
              :value="item.id"
              :key="item.id"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="字段名称" align="center" width="120">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.itemId"
            :disabled="formType == 'info'"
            placeholder="请选择"
            @change="handleChangeFieldsName(scope.row, scope.$index)"
            @clear="handleClearItemId(scope.row, scope.$index)"
            clearable
          >
            <el-option
              v-for="item in scope.row.itemIdOpction"
              :label="item.label"
              :value="
                scope.row.dataSource == 'resi' ? item.itemId : item.colKey
              "
              :key="scope.row.dataSource == 'resi' ? item.itemId : item.colKey"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="比较符" align="center" width="120">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.queryType"
            placeholder="请选择"
            :disabled="formType == 'info'"
            clearable
          >
            <el-option
              v-for="item in queryTypeOpction"
              :label="item.label"
              :value="item.value"
              :key="item.value"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="对应值" align="center">
        <template slot-scope="scope">
          <template v-for="item in scope.row.correspondingOpction">
            <el-select
              v-if="
                item.itemType == 'select' ||
                item.itemType == 'radio' ||
                item.itemType == 'checkbox'
              "
              v-model="scope.row.colVal"
              :disabled="formType == 'info'"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="items in item.options"
                :label="items.label"
                :value="items.value"
                :key="items.label"
              >
              </el-option>
            </el-select>
            <el-input
              v-else-if="
                item.itemType === 'input' || item.itemType === 'textarea'
              "
              v-model="scope.row.colVal"
              :disabled="formType == 'info'"
              placeholder="请输入"
              clearable
            >
            </el-input>
            <el-input-number
              v-else-if="item.itemType === 'inputNum'"
              class="item_width_2"
              v-model="scope.row.colVal"
              :disabled="formType == 'info'"
              :min="0"
              size="mini"
              label="请输入"
            ></el-input-number>
            <el-date-picker
              v-else-if="
                item.itemType === 'datepicker' || item.itemType === 'date'
              "
              v-model="scope.row.colVal"
              class="item_width_2"
              :disabled="formType == 'info'"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              value="yyyy-MM-dd HH:mm:ss"
              placeholder="开始时间"
            >
            </el-date-picker>
            <el-input
              v-else
              class="item_width_2"
              size="mini"
              :disabled="formType == 'info'"
              placeholder="请输入"
              v-model="personItem.colVal"
            >
            </el-input>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="条件关系" align="center" width="120">
        <template
          slot-scope="scope"
          v-if="scope.$index != tableData.length - 1"
        >
          <el-select
            v-model="scope.row.nextLogicalRel"
            placeholder="请选择"
            :disabled="formType == 'info'"
            clearable
          >
            <el-option
              v-for="item in nextLogicalRelOpction"
              :label="item.label"
              :value="item.value"
              :key="item.value"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        align="center"
        width="120"
        v-if="formType != 'info'"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            @click="handleClickAddRow"
            v-if="scope.$index == tableData.length - 1"
            size="small"
            icon="el-icon-plus"
            circle
          ></el-button>

          <el-button
            type="danger"
            @click="handleClickDelete(scope.$index)"
            v-if="
              scope.$index != tableData.length - 1 ||
              (tableData.length - 1 >= 1 && scope.$index != '0')
            "
            size="small"
            icon="el-icon-minus"
            circle
          >
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="div_btn">
      <el-button size="small" @click="handleCancle">取 消</el-button>
      <el-button size="small" type="primary" @click="handleComfirm"
        >确 定</el-button
      >
    </div>
  </div>
</template>

<script>
import { requestPost, requestGet } from "@/js/dai/request";
export default {
  data() {
    return {
      formData: {
        tagName: "",
      },
      formType: "",
      rules: {
        tagName: [
          { required: true, message: "请输入标签名称", trigger: "change" },
        ],
      },
      timeout: null,
      tagObj: {},
      searchList: [],
      tableData: [
        {
          dataSource: "", //数据源
          itemGroupId: "", //字段类别
          itemId: "", //字段名称
          queryType: "", //比较符
          colVal: "", //对应值
          nextLogicalRel: "", //条件关系,
          tableName: "", //数据库表名
          colKey: "",
          itemIdOpction: [],
          itemGroupIdOpction: [],
          correspondingOpction: [],
        },
      ],
      formType: "",
      dataSourceOpction: [
        { label: "人员信息", value: "resi" },
        { label: "房屋信息", value: "house" },
        { label: "统计信息", value: "stat" },
      ],
      queryTypeOpction: [{}],
      nextLogicalRelOpction: [
        { label: "并且", value: "and" },
        { label: "或者", value: "or" },
      ],
      addFormLabel:true
    };
  },
  created() {},
  async mounted() {
    await this.getLabelList();
  },
  methods: {
    async initForm(type, row) {
      this.formType = type;
     
      if (type == "info") {
        await this.getFormEdit(row.tagId);
      } else if (type == "edit") {
        await this.getFormEdit(row.tagId);
        this.formData.tagName = row.tagName;
      }
      this.tagId = row.tagId;
      this.tagObj = row;
      for (let i in this.tableData) {
       await this.handleChangeSource(this.tableData[i], [i], type);
       await this.handleChangeFieldsType(this.tableData[i], [i], type);
       await this.handleChangeFieldsName(this.tableData[i], [i], type);
      }
    },
    querySearchAsync(val, cb) {
      var searchList = this.searchList;
      var results = val
        ? searchList.filter(this.createStateFilter(val))
        : searchList;
      if (results.length == 0) {
        this.tableData = []
        this.handleClickAddRow();
        this.addFormLabel = false
        this.formType = "add";
      } else {
        this.formType = "info";
      }
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 3000 * Math.random());
    },
    handelChangeTagName(val){
      if(this.formData.tagName.length == 0 ){
        this.formType = 'info'
        this.tableData = []
        this.addFormLabel = true
      }
    },
    createStateFilter(val) {
      return (state) => {
        return state.tagName.toLowerCase().indexOf(val.toLowerCase()) === 0;
      };
    },
    async handleSelect(item) {
      console.log(item);
      await this.initForm(item.editable?'edit':'info', item);
    },
    async getLabelList() {
      const url = "/governance/resiSearchTag/listResiSearchTags";
      let params = {
        pageSize: 99,
      };
      let { data, msg, code } = await requestPost(url, params);
      if (code == 0) {
        this.searchList = data.list;
      } else {
        this.$message.error(msg);
      }
    },
    // 选择数据源
    async handleChangeSource(row, index, type) {
      if (row.dataSource == "resi") {
        let url = "/oper/customize/icformitemgroup/list";
        let params = {
          formCode: "resident_base_info",
        };
        let { data, code, msg } = await requestPost(url, params);
        if (code == 0) {
          this.$set(this.tableData[index], "itemGroupIdOpction", data);
          console.log(this.tableData[index].itemGroupIdOpction);
        } else {
          this.$message.error(msg);
        }
        this.hadeleClearForm(this.tableData[index], index);
        if (!type) {
          this.tableData[index].itemGroupId = "";
          this.tableData[index].itemId = "";
          this.tableData[index].colKey = "";
          this.tableData[index].colVal = "";
          this.tableData[index].nextLogicalRel = "";
          this.tableData[index].queryType = "";
          this.tableData[index].itemIdOpction = [];
        }
      } else if (row.dataSource == "house") {
        let url = "/governance/policy/item-list/house";
        let params = {};
        let { data, code, msg } = await requestPost(url, params);
        if (code == 0) {
          this.tableData[index].itemIdOpction = data;
        } else {
          this.$message.error(msg);
        }
        this.hadeleClearForm(this.tableData[index], index);
        if (!type) {
          this.tableData[index].itemGroupId = "";
          this.tableData[index].itemId = "";
          this.tableData[index].colKey = "";
          this.tableData[index].colVal = "";
          this.tableData[index].nextLogicalRel = "";
          this.tableData[index].queryType = "";
        }
      } else if (row.dataSource == "stat") {
        let url = "/governance/policy/item-list/stat";
        let params = {};
        let { data, code, msg } = await requestPost(url, params);
        if (code == 0) {
          this.tableData[index].itemIdOpction = data;
        } else {
          this.$message.error(msg);
        }
        this.hadeleClearForm(this.tableData[index], index);
        if (!type) {
          this.tableData[index].itemGroupId = "";
          this.tableData[index].itemId = "";
          this.tableData[index].colKey = "";
          this.tableData[index].colVal = "";
          this.tableData[index].nextLogicalRel = "";
          this.tableData[index].queryType = "";
        }
      } else {
        this.hadeleClearForm(this.tableData[index], index);
        this.tableData[index].itemGroupId = "";
        this.tableData[index].itemId = "";
        this.tableData[index].colKey = "";
        this.tableData[index].colVal = "";
        this.tableData[index].nextLogicalRel = "";
        this.tableData[index].queryType = "";
        this.tableData[index].itemIdOpction = [];
      }

      this.getCompareList();
    },

    // 字段类别修改
    async handleChangeFieldsType(row, index, type) {
      console.log(row, index, "字段类别row");
      if (row.dataSource != "resi") return;
      const url = "/oper/customize/icformitem/getItemListV2";
      let params = {
        groupId: row.itemGroupId,
      };
      this.hadeleClearForm(this.tableData[index], index);
      if (!type) {
        this.tableData[index].itemId = "";
        this.tableData[index].colKey = "";
        this.tableData[index].colVal = "";
        this.tableData[index].nextLogicalRel = "";
        this.tableData[index].queryType = "";
        this.tableData[index].itemIdOpction = [];
      }
      let { data, code, msg } = await requestPost(url, params);
      if (code == 0) {
        this.$set(this.tableData[index], "itemIdOpction", data);
        console.log(this.tableData[index].itemIdOpction, "see");
      } else {
        this.$message.error(msg);
      }
    },
    // 字段名称修改
    async handleChangeFieldsName(row, index, type) {
      console.log(row, "字段名称row");
      var arr = [];
      // 人的信息中colKey的字段是columnName要做一下判断
      if (row.dataSource == "house" || row.dataSource == "stat") {
        arr = row.itemIdOpction.filter((item) => item.colKey == row.itemId);
        this.tableData[index].tableName = arr[0].tableName;
        this.tableData[index].colKey = arr[0].colKey;
        if (!type) {
          this.tableData[index].colVal = "";
          this.tableData[index].nextLogicalRel = "";
          this.tableData[index].queryType = "";
        }
        // this.tableData[index].colVal = ''
        // this.tableData[index].queryType = ''
      } else if (row.dataSource == "resi" && row.itemId != "") {
        arr = row.itemIdOpction.filter((item) => item.itemId == row.itemId);
        this.tableData[index].tableName = arr[0].tableName;
        this.tableData[index].colKey = arr[0].columnName;
        if (!type) {
          this.tableData[index].colVal = "";
          this.tableData[index].nextLogicalRel = "";
          this.tableData[index].queryType = "";
        }
        // this.tableData[index].colVal = ''
        // this.tableData[index].queryType = ''
      }
      if (row.itemId == "") return;
      //  列表对应值的option有的是通过接口获取的就需要再通过optionSourceType判断下
      if (arr[0].optionSourceType == "remote") {
        let url = "";
        let params = {};
        if (row.dataSource == "house") {
          url = arr[0].optionSourceUrl;
          params = JSON.parse(arr[0].optionSourceParam);
        } else {
          url = arr[0].optionSourceValue;
        }

        const { data, code, msg } = await requestPost(url, params);
        if (code == 0) {
          arr[0].options = data;
          this.$set(this.tableData[index], "correspondingOpction", arr);
        } else {
          this.$message.error(msg);
        }
      } else {
        this.$set(this.tableData[index], "correspondingOpction", arr);
      }

      console.log(this.tableData);
    },
    async getCompareList() {
      const url = "/sys/dict/data/dictlist";
      let params = {
        dictType: "sql_query_type",
      };
      let { data, code, msg } = await requestPost(url, params);
      if (code == 0) {
        this.queryTypeOpction = data;
      } else if (code >= 8000) {
        this.$message.error(msg);
      }
    },
    // 选中标签其他清空
    hadeleClearForm(row, index) {
      let obj = {};
      obj = {
        dataSource: row.dataSource ? row.dataSource : "",
        itemId: row.itemId ? row.itemId : "",
        queryType: row.queryType ? row.queryType : "",
        colVal: row.colVal ? row.colVal : "",
        colKey: row.colKey ? row.colKey : "",
        nextLogicalRel: row.nextLogicalRel ? row.nextLogicalRel : "",
        tableName: row.tableName ? row.tableName : "",
        itemGroupId: row.itemGroupId ? row.itemGroupId : "",
        itemIdOpction: row.itemIdOpction ? row.itemIdOpction : [],
        itemGroupIdOpction: row.itemGroupIdOpction
          ? row.itemGroupIdOpction
          : [],
      };
      this.$set(this.tableData, index, obj);
    },
    async getFormEdit(id) {
      const url = `/governance/resiSearchTag/listResiSearchRulesByTagId?tagId=${id}`;
      let { code, msg, data } = await requestGet(url);
      if (code == 0) {
        console.log(data, "获取到的详情信息");
        this.tableData = data;
      } else if (code >= 8000) {
        this.$message.error(msg);
      }
    },
    async handleComfirm() {
      if (this.formType != "info") {
        this.$refs.label_form.validate((flag) => {
          if (flag) {
            let messageObj = {};
            messageObj = this.validateRule(this.tableData);
            if (messageObj) {
              this.$message.error(messageObj);
              return;
            }
            for (let i in this.tableData) {
              for (let j in this.tableData[i]) {
                if (
                  typeof this.tableData[i][j] != "string" &&
                  typeof this.tableData[i][j] != "number"
                ) {
                  this.$delete(this.tableData[i], j);
                }
              }
            }
            this.addSubmit();
          } else {
            return false;
          }
        });
      } else {
        this.$emit("dialogOk", this.tagObj);
        return this.tagId;
      }
    },
    async addSubmit() {
      var url = "";
      var params = {};
      if (this.formType == "edit") {
        url = "/governance/resiSearchTag/updateResiSearchTag";
        params = {
          tagName: this.formData.tagName,
          rules: this.tableData,
          tagId: this.tagId,
        };
      } else if (this.formType == "add") {
        url = "/governance/resiSearchTag/addResiSearchTag";
        params = {
          tagName: this.formData.tagName,
          rules: this.tableData,
        };
      }
      const { data, msg, code } = await requestPost(url, params);
      if (code == 0) {
        this.$message.success("操作成功");
        this.$emit("dialogOk", { tagId: data.id, tagName: data.tagName });
      } else if (code >= 8000) {
        this.$message.error(msg);
      }
    },
    handleCancle() {
      this.$emit("dialogCancle");
    },
    validateRule(tabList) {
      console.log(tabList);
      let message = "";
      tabList.forEach((item, index) => {
        if (
          (item.itemGroupId === "" && item.dataSource == "resi") ||
          item.itemId === "" ||
          item.queryType === "" ||
          item.colKey === ""
        ) {
          message = `匹配规则${
            item.dataSource == "resi"
              ? "人员"
              : item.dataSource == "house"
              ? "房屋"
              : item.dataSource == "stat"
              ? "统计"
              : ""
          }信息不完整，请填写完整 !`;
          return message;
        }
        if (index != this.tableData.length - 1 && item.nextLogicalRel === "") {
          message = `匹配规则${
            item.dataSource == "resi"
              ? "人员"
              : item.dataSource == "house"
              ? "房屋"
              : item.dataSource == "stat"
              ? "统计"
              : ""
          }信息不完整，请填写完整 !`;
          console.log(item);
          return message;
        }
        if (
          item.queryType !== "is_null" &&
          item.queryType !== "is_not_null" &&
          item.colVal === ""
        ) {
          message = `匹配规则${
            item.dataSource == "resi"
              ? "人员"
              : item.dataSource == "house"
              ? "房屋"
              : item.dataSource == "stat"
              ? "统计"
              : ""
          }信息不完整，请填写完整 !`;

          return message;
        }
      });
      return message;
    },
    handleClickAddRow() {
      if (this.tableData === undefined) this.tableData = [];
      let obj = {};
      obj.dataSource = "";
      obj.itemGroupId = "";
      obj.itemId = "";
      obj.queryType = "";
      obj.colVal = "";
      obj.nextLogicalRel = "";
      obj.itemIdOpction = [];
      this.tableData.push(obj);
    },
    // 删除一行
    handleClickDelete(index) {
      this.tableData.splice(index, 1);
    },
    handleClearItemId(row, index) {
      this.tableData[index].colVal = "";
      this.tableData[index].queryType = "";
    },
  },
  props: {},
  computed: {},
  watch: {},
};
</script>

<style lang="scss" scoped>
@import "@/assets/scss/modules/management/list-main.scss";

.imgBtn {
  width: 25px;
  height: 25px;
  margin-top: 3px;
  cursor: pointer;
}

.div_btn {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.my_form {
  padding: 10px 50px 0;
}
</style>
