<!--
 * @Date: 2021-11-19 11:34:20
 * @LastEditTime: 2022-03-02 09:41:02
 * @LastEditors: Please set LastEditors
 * @Description: 目标数据-基本信息
-->
<template>
  <div class="dataStoreInfo">
    <!--基本信息-->
    <div class="airportInfoDetails-head">
      <Search title="编辑源数据信息" :isSearch="false">
        <button class="childBtnAn" @click="storagemod">保存</button>
      </Search>
      <div class="airportInfoDetails-head-content dialog-public-background">
        <el-form
          :inline="true"
          :rules="rules"
          :model="ruleForm"
          ref="ruleForm"
          class="demo-ruleForm"
          label-width="140px"
        >
          <el-form-item label="源数据名称" prop="dataName">
            <el-input
              size="small"
              maxlength="128"
              placeholder="请输入源数据名称"
              v-model="ruleForm.dataName"
            ></el-input>
          </el-form-item>
          <el-form-item label="数据格式" prop="dataType">
            <el-select
              size="small"
              style="width: 100%"
              v-model="ruleForm.dataType"
              placeholder="请选择数据类型"
            >
              <el-option label="JSON" value="1"></el-option>
              <el-option label="XML" value="2"></el-option>
              <el-option label=" REGULA" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目标数据描述">
              <el-input
                maxlength="128"
                placeholder="请输入描述"
                type="textarea"
                :rows="1"
                v-model="ruleForm.dataDescribe"
                style="width: 575px"
              ></el-input>
            </el-form-item>
          <el-row>
            <el-col :span="10.5">
            <el-form-item label="取值方法">
              <el-input
                maxlength="128"
                placeholder="请输入取值方法"
                type="textarea"
                :rows="1"
                v-model="ruleForm.computingMethod"
                style="width: 575px"
              ></el-input>
            </el-form-item>
            </el-col>
            <el-col :span="10.5">

            <el-form-item label="检测方法">
              <el-input
                maxlength="128"
                placeholder="请输入检测方法"
                type="textarea"
                :rows="1"
                v-model="ruleForm.validationExpression"
                style="width: 575px"
              ></el-input>
            </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <!--数据项信息-->
    <div class="airportInfoDetails-content">
      <Search
        style="padding-left: 24px"
        :isChild="true"
        title="数据项信息"
        @clearSearchData="clearSearchData"
        @getSearchData="getSearchData"
      >
        <button @click="addStore" class="childBtnAdd">新增</button>
      </Search>
      <div class="table-info">
        <el-table
          :data="posArr"
          row-key="ItemID"
          :row-class-name="tabRowClassName"
          height="56vh"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          class="table"
          style="width: 100%"
          :header-cell-style="{ 'text-align': 'left' }"
          :cell-style="{ 'text-align': 'left' }"
        >
          <el-table-column prop="ItemName" label="数据项名称"></el-table-column>
          <!-- <el-table-column prop="itemCode" label="数据项标识"></el-table-column> -->
          <el-table-column
            prop="dataTypeText"
            label="数据类型"
          ></el-table-column>
          <el-table-column
            prop="ItemDescribe"
            label="数据项描述"
          ></el-table-column>
          <el-table-column
            prop="computingMethod"
            label="取值方法"
          ></el-table-column>
          <el-table-column
            prop="computingExpression"
            label="取值表达式"
          ></el-table-column>
          <el-table-column
            prop="outputIdentifier"
            label="输出标识符"
          ></el-table-column>
          <el-table-column
            prop="isMustText"
            label="是否必填"
          ></el-table-column>
          <el-table-column
            prop="isKeyText"
            label="是否唯一"
          ></el-table-column>
          <el-table-column
            prop="isSpliteText"
            label="多条拆分"
          ></el-table-column>
          <el-table-column label="操作">
            <div
              slot-scope="scope"
              style="
                width: 100%;
                height: 100%;
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <el-button
                class="fut"
                size="small"
                @click="handleAdd(scope.$index, scope.row)"
                >新增</el-button
              >
              <el-button
                class="fut"
                size="small"
                @click="handleEdit(scope.$index, scope.row)"
                >编辑</el-button
              >
              <el-button
                class="futdel"
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
                >删除</el-button
              >
            </div>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!--删除弹框-->
    <Dialog :flag="flag">
      <div class="airportInfoDialog">
        <div class="del-title">删除存储数据项</div>
        <div class="content er">
          <div class="log"></div>
          是否确认删除{{ rmObj.name }}？
        </div>
        <div class="foot right t30" style="background: #ffffff">
          <el-button size="small" @click="remove" class="r25 r26" type="danger"
            >删除</el-button
          >
          <el-button size="medium" class="r26" @click="flag = false"
            >取消</el-button
          >
        </div>
      </div>
    </Dialog>
    <!--新增/编辑存储数据项弹框-->
    <Dialog width="748px" customClass="dataStoreInfoDialog" :flag="addFlag">
      <div class="dialog-public-background">
        <div class="flx">
          {{ msgType === 1 ? "新增" : "编辑" }}数据项信息
        </div>
        <div class="contenter">
          <el-form
            :model="dataForm"
            :rules="dataRules"
            ref="dataForm"
            label-width="130px"
            class="demo-dataForm"
          >
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item class="flex1" label="所属数据项" prop="parentID">
                  <el-cascader
                    size="small"
                    style="width: 100%"
                    placeholder="请选择所属数据项"
                    v-model="dataForm.parentIDs"
                    :options="posArr"
                    ref="cascader"
                    :props="{ label: 'ItemName', value: 'ItemID',checkStrictly: true  }"
                    @change="handleChange"
                    >
                  </el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item class="flex1" label="数据项名称" prop="ItemName">
                  <el-input
                    maxlength="128"
                    size="small"
                    placeholder="请输入数据项名称"
                    v-model="dataForm.ItemName"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item class="flex1" label="数据类型" prop="dataType">
                  <el-select
                    size="small"
                    style="width: 100%"
                    v-model="dataForm.dataType"
                    placeholder="请选择数据类型"
                  >
                    <el-option
                      v-for="item in optiondata"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  class="flex1"
                  label="输出标识符"
                  prop="outputIdentifier"
                >
                  <el-input
                    maxlength="128"
                    size="small"
                    placeholder="请输入输出标识符"
                    v-model="dataForm.outputIdentifier"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  class="flex1"
                  label="取值方法"
                  prop="computingMethod"
                >
                  <el-input
                    maxlength="128"
                    size="small"
                    placeholder="请输入取值方法"
                    v-model="dataForm.computingMethod"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="取值表达式">
                  <el-input
                    v-model="dataForm.computingExpression"
                    size="medium"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入取值表达式"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="数据项描述">
                  <el-input
                    v-model="dataForm.ItemDescribe"
                    size="medium"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入数据项描述"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item class="flexer" label="允许空值">
                  <el-radio v-model="dataForm.isMust" label="1">是</el-radio>
                  <el-radio v-model="dataForm.isMust" label="0">否</el-radio>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item class="flexer" label="唯一项标志">
                  <el-radio v-model="dataForm.isKey" label="1">是</el-radio>
                  <el-radio v-model="dataForm.isKey" label="0">否</el-radio>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item class="flexer" label="多条拆分">
                  <el-radio v-model="dataForm.isSplite" label="1">是</el-radio>
                  <el-radio v-model="dataForm.isSplite" label="0">否</el-radio>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="foot center" style="padding-right: 35px">
          <el-button
            size="small"
            type="primary"
            @click="addSubmit('dataForm')"
            class="r25 r26"
            >提交</el-button
          >
          <el-button size="small" class="r26" @click="resetForm('dataForm')"
            >取消</el-button
          >
        </div>
      </div>
    </Dialog>
  </div>
</template>

<script>
import Search from "@/layout/components/Search/index.vue";
import Dialog from "@/layout/components/Dialog/index.vue";
import { Query, GeneralDataReception } from "@/api/dataIntegration";
import { translateDataToTreeAll, findarrays } from "@/utils/validate";
export default {
  name: "dataStoreInfo",
  components: { Search, Dialog },
  data() {
    return {
      ruleForm: {
        //基本信息表单
        dataName: "",
        dataType: "",
        dataDescribe: "",
        computingMethod:"",
        validationExpression:""
      },
      rules: {
        //基本信息验证
        dataName: [
          { required: true, message: "请输入目标数据名", trigger: "blur" },
        ],
        dataType: [
          { required: true, message: "请选择数据格式", trigger: "change" },
        ],
      },
      posArr: [], //存储数据项数据
      posArrCopy: [], //临时存放数据
      rmObj: {}, //选中的表格信息
      rmIndex: null, //选中的表格序号
      flag: false, //删除弹框
      msgType: 1, //新增or编辑
      dataForm: {},
      dataRules: {
        //数据项表单验证
        ItemName: [
          { required: true, message: "请输入数据项名称", trigger: "blur" },
        ],
        code: [
          { required: true, message: "请输入数据来源表达式", trigger: "blur" },
        ],
        dataType: [{ required: true, message: "请选数据类型", trigger: "change" }],
      },
      addFlag: false, //数据项弹框,
      dataStoreid: "", //修改id，
      analyList: [], //遍历后的确定数据
      dataitem: [], //所属数据项
      optiondata: [
        //数据类型
        {
          name: "字符",
          id: 1,
        },
        {
          name: "数字",
          id: 2,
        },
        {
          name: "日期",
          id: 3,
        },
        {
          name: "时间",
          id: 4,
        },
      ],
      sourceList: [], //取值来源
      tableData: [],
      deleID: "", //删除id
    };
  },
  created() {
    const { id } = this.$route.query;
    this.dataStoreid = id;
    this.storagedetails();
    this.getDataList();
  },
  methods: {
    tabRowClassName({ row, rowIndex }) {
      if (row.index) {
        let index = row.index + 1;
        if (index % 2 == 0) {
          return "warning-row";
        } else {
          return "warning-rows";
        }
      }
    },
    //数据项信息
    // async Dataitem() {
    //   let params = {
    //     sourceId: this.sourceider,
    //   };
    //   const result = await anaListmod(params);
    //   if (result.code == 0) {
    //     this.sourceList = result.returnData;
    //     this.tableData = result.returnData;
    //   }
    // },
    //详情查询
    async storagedetails() {
      let params = {
        id: 18,
        dataContent: [this.dataStoreid],
      };
      const result = await Query(params);
      if (result.code == 0) {
        result.returnData.forEach((element) => {
          element.dataType = element.dataType + "";
        });
        this.ruleForm = result.returnData[0];
      } else {
        this.$message.error(res.message ?? "失败");
      }
    },

    //保存主数据
    async storagemod() {
      this.ruleForm["operate"] = "2";
      try {
        const res = await GeneralDataReception({
          serviceId: "4",
          dataContent: JSON.stringify(this.ruleForm),
        });
        if (res.code === "0") {
          this.$message.success(res.message ?? "成功");
        } else {
          this.$message.error(res.message ?? "失败");
        }
      } catch (error) {
        console.log("错误", error);
      }
    },
    //获取数据项列表
    async getDataList() {
      let params = {
        id: 16,
        dataContent: [this.dataStoreid],
      };
      const result = await Query(params);
      if (result.code == 0) {
        console.log(result);
        result.returnData.forEach(item =>{
          if(item.dataType==1){
            item['dataTypeText'] = "字符串"
          }
          else if(item.dataType==2){
            item['dataTypeText'] = "数字"
          }
          else if(item.dataType==3){
            item['dataTypeText'] = "时间"
          }
          else if(item.dataType==4){
            item['dataTypeText'] = "日期"
          }
          else{
            item['dataTypeText'] = "其他"
          }
          if(item.isKey==1){
            item['isKeyText'] = "是"
          }
          else{
            item['isKeyText'] = "否"
          }
          if(item.isMust==1){
            item['isMustText'] = "是"
          }
          else{
            item['isMustText'] = "否"
          }
          if(item.isSplite==1){
            item['isSpliteText'] = "是"
          }
          else{
            item['isSpliteText'] = "否"
          }
        })
        this.posArr = translateDataToTreeAll(
          result.returnData,
          "parentID",
          "ItemID"
        );
        this.posArr.forEach((res, index) => {
          res.index = index + 1;
          if(res.children.length<1){
            delete res.children
          }
        });
        this.posArrCopy = JSON.parse(JSON.stringify(this.posArr));
      } else {
        this.$message.error(res.message ?? "失败");
      }
    },
    //搜索
    getSearchData(val) {
      let that = this;
      that.storagedetails().then(function (data) {
        if (val) {
          that.posArr = that.rebuildData(val,that.posArr);
        } else {
          that.storagedetails();
        }
      });
    },
    //根据name字段模糊匹配树状结构数据，最后将处理好的数据返回出来
    rebuildData (value, arr){
      if (!arr) {
        return []
      }
      const newarr = [];
      arr.forEach(element => {
      // indexOf用来判读当前节点name字段是否包含所搜索的字符串value
      // 返回值：包含则返回索引值，反之返回-1
        if (element.ItemName.indexOf(value) > -1) {
          const ab = this.rebuildData(value, element.children);
          const obj = {
            ...element,
            children: ab
          }
          newarr.push(obj);
        } else {
        // 判断当前节点知否有子节点，并且子节点中有数据，有数据继续递归查找
          if (element.children && element.children.length > 0) {
            const ab = this.rebuildData(value, element.children);
            const obj = {
              ...element,
              children: ab
            };
            if (ab && ab.length > 0) {
              newarr.push(obj);
            }
          }
        }
      });
      return newarr
    },
    //清空搜索
    clearSearchData() {
      this.posArr = this.posArrCopy;
    },
    //删除信息
    handleDelete(index, row) {
      this.rmObj = row;
      this.rmIndex = index;
      this.flag = true;
      this.deleID = row.ItemID;
    },
    //删除
    async remove() {
      this.rmObj["operate"] = "3";
      try {
        const res = await GeneralDataReception({
          serviceId: "5",
          dataContent:  JSON.stringify(this.rmObj),
        });
        if (res.code === "0") {
          this.removeDialogVisible = false;
          this.$message.success("删除成功");
          this.getDataList()
        } else {
          this.$message.error(res.message ?? "失败");
        }
      } catch (error) {
        console.log("错误", error);
      }
      this.flag = false;
    },
    //新增数据项
    addStore() {
      this.msgType = 1;
      this.addFlag = true;
    },
    //点击列表新增按钮
    handleAdd(index,row){
      this.msgType = 1;
      this.addFlag = true;
      this.dataForm.parentID = row.ItemID;
      this.dataForm.parentIDs = [row.ItemID];
    },
    //点击列表编辑按钮
    handleEdit(index,row){
      this.msgType = 2;
      this.addFlag = true;
      this.dataForm = row;
      this.dataForm.parentIDs = [row.parentID];
      this.dataForm.isKey = this.dataForm.isKey+""
      this.dataForm.isMust = this.dataForm.isMust+""
      this.dataForm.isSplite = this.dataForm.isSplite+""
    },
    handleChange(data){
      this.dataForm.parentID = data[data.length-1]
    },
    //数据项-提交
    async addSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.dataForm.ItemID){
            this.dataForm["operate"] = "2";
          }
          else{
            this.dataForm["operate"] = "1";
          }
          this.dataForm["sourceDataID"] = this.dataStoreid;
          this.saveData();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //数据项保存
    async saveData(){
      try {
            const res =  await GeneralDataReception({
              serviceId: "5",
              dataContent: JSON.stringify(this.dataForm),
            });
            if (res.code === "0") {
              this.$message.success(res.message ?? "成功");
              this.getDataList();
              this.resetForm("dataForm");
            } else {
              this.$message.error(res.message ?? "失败");
            }
          } catch (error) {
            console.log("错误", error);
          }

    },
    //数据项-取消
    resetForm(formName) {
      this.addFlag = false;
      this.dataForm = {};
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style lang="scss" scoped>
.dataStoreInfo {
  ::v-deep .warning-row {
    background: #f0f3f7;
  }
  ::v-deep .warning-rows {
    background: #ffffff;
  }
  .log {
    width: 26px;
    height: 26px;
    background: #eb2f3b;
    border-radius: 50%;
    margin-right: 15px;
    background: url("../../../../assets/index/ic_close_hint.png") no-repeat;
    background-size: 100% 100%;
  }
  .fut {
    width: 48px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #ffffff;
    border: 1px solid #9ebbf7;
    box-shadow: 0px 3px 3px 0px rgba(0, 0, 0, 0.06);
    border-radius: 4px;
    font-size: 12px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #2d67e3;
  }
  .futdel {
    width: 48px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #eb2f3b;
    box-shadow: 0px 3px 3px 0px rgba(0, 0, 0, 0.06);
    border-radius: 4px;
    font-size: 12px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #ffffff;
  }
  .contenter {
    padding: 0 24px 0 24px;
  }
  .flexer {
    margin-left: 0;
  }
  // ::v-deep .cell {
  //   display: flex;
  // }
  .er {
    display: flex;
    align-items: center;
  }
  .airportInfoDetails-head {
    padding: 32px 40px 44px 24px;
    background: #ffffff;
    box-shadow: 8px 6px 7px 0px rgba(0, 0, 0, 0.06);
    border-radius: 4px;
    .airportInfoDetails-head-content {
      margin-top: 48px;
      .el-input {
        min-width: 188px;
      }
      .el-form--inline .el-form-item {
        margin-bottom: 0;
        margin-right: 48px;
      }
    }
  }
  .airportInfoDetails-content {
    // height: 56vh;
    overflow-x: hidden;
    overflow-y: hidden;
    padding: 0 0 0 0;
    background: #dfe3ea;
    // box-shadow: 0px 6px 7px 0px rgba(0, 0, 0, 0.06);
    border-radius: 4px;
    margin-top: 10px;
    .table-info {
      margin-top: 8px;
      ::v-deep .table {
        .el-table__header {
          .has-gutter {
            color: #101116;
            .is-leaf {
              height: 40px;
              background: #ffffff;
              &:first-child {
                border-top-left-radius: 4px;
              }
            }
            .gutter {
              background: #ffffff;
              border-top-right-radius: 4px;
            }
          }
        }
        td.el-table__cell,
        th.el-table__cell.is-leaf {
          border-bottom: none;
        }
        .el-table__cell {
          padding: 16px 0;
          // background: #f5f7fa;
        }
        .el-table__row--level-1 {
          td {
            background: #dfe4ec;
          }
        }
        tr {
          transition: all 0.3s;
          &:hover {
            td {
              background-color: #cbd7ee;
            }
          }
        }
        &::before {
          width: 0;
        }
      }
    }
  }
  ::v-deep .dataStoreInfoDialog {
    .demo-dataForm {
      .noleft {
        .el-form-item__content {
          margin-left: 0 !important;
          margin-right: 0 !important;
          width: 300px;
          .el-input__suffix {
            right: 23px;
          }
        }
      }
    }
  }
  ::v-deep .el-input__suffix {
    right: 15px;
  }
}
</style>
