<template>
  <el-container>
    <el-row class="header">
      <el-button type="primary" @click="addRules"
        >增加数据完整性检查项</el-button
      >
    </el-row>

    <div class="ruleContent" ref="ruleContent">
      <el-table
        ref="multipleTable"
        :data="checkDetail"
        border
        :max-height="tableMaxHeight"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="50" align="center">
        </el-table-column>
        <el-table-column
          prop="name"
          label="是否检查"
          width="160"
          align="center"
        >
          <template slot-scope="scope">
            <el-radio v-model="scope.row.isCheck" :label="1">是</el-radio>
            <el-radio v-model="scope.row.isCheck" :label="0">否</el-radio>
          </template>
        </el-table-column>
        <el-table-column
          prop="checkContent"
          label="检查项"
          width="180"
          align="center"
        >
          <template slot-scope="scope">
            <!-- <div class="morerow" v-if="scope.row.children != undefined">
              <el-row v-for="(item, index) in scope.row.children" :key="index">
                <span> {{ item.checkContent }} </span>
              </el-row>
            </div>
            <span v-else> {{ scope.row.checkContent }} </span> -->
            <span> {{ scope.row.checkContent }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="checkDescribe" label="描述" align="center">
          <template slot-scope="scope">
            <div class="morerow" v-if="scope.row.children != undefined">
              <el-row v-for="(item, index) in scope.row.children" :key="index">
                <span> {{ item.checkDescribe }} </span>
              </el-row>
            </div>
            <span v-else> {{ scope.row.checkDescribe }} </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="fieldName"
          label="字段名称"
          width="200"
          align="center"
        >
          <template slot-scope="scope">
            <div class="morerow" v-if="scope.row.children != undefined">
              <el-row v-for="(item, index) in scope.row.children" :key="index">
                <el-input v-model="item.fieldName"></el-input>
              </el-row>
            </div>
            <el-input v-else v-model="scope.row.fieldName"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="50" align="center">
          <template slot-scope="scope">
            <el-popover
              v-if="scope.row.type == 'dataIntegrality'"
              placement="top-end"
              width="160"
              trigger="hover"
              :ref="`popover-${scope.$index}`"
            >
              <p style="padding: 10px 0">确定要删除此检查项吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button
                  size="mini"
                  type="text"
                  @click="
                    scope._self.$refs[`popover-${scope.$index}`].doClose()
                  "
                >
                  取消
                </el-button>
                <el-button
                  type="primary"
                  size="mini"
                  @click="deleteRules(scope.$index, scope.row, scope)"
                >
                  确定
                </el-button>
              </div>
              <el-button
                slot="reference"
                icon="el-icon-delete iconfont"
                :style="{ color: '#999999' }"
                size="mini"
                :title="'删除'"
                circle
              ></el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-row>
      <el-upload
        class="uploadbtn"
        ref="upload"
        accept="csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        :action="''"
        :auto-upload="true"
        :show-file-list="false"
        :limit="1"
        :before-upload="uploadFile"
      >
        <el-button type="primary" class="add-item" @click="beforeUploadFile">
          上传文件
        </el-button>
      </el-upload>
    </el-row>
  </el-container>
</template>

<script>
import qualityApi from "@/api/qualityinspection";

export default {
  data() {
    return {
      tableMaxHeight: 450,
      defaultField: {
        isCheck: 1,
        checkContent: "数据完整性",
        checkDescribe:
          "检查所填字段数据是否完整（可填写多个字段，会动态扩展行数）",
        fieldName: "",
        delBtn: true,
        type: "dataIntegrality",
      },
      checkDefaultDetail: [
        {
          isCheck: 1,
          checkContent: "数据完整性",
          checkDescribe:
            "检查所填字段数据是否完整（可填写多个字段，会动态扩展行数）",
          fieldName: "",
          delBtn: true,
          type: "dataIntegrality",
        },
        {
          isCheck: 1,
          checkContent: "省级行政区划编码检查",
          checkDescribe: '验证是否是以"13"开头的纯数字的行政区划编码',
          fieldName: "",
          delBtn: false,
          type: "provinceCode",
        },
        {
          isCheck: 1,
          checkContent: "市级行政区划编码检查",
          checkDescribe: '验证是否是以"13"开头的纯数字且至少4位的行政区划编码',
          fieldName: "",
          type: "cityCode",
          delBtn: false,
        },
        {
          isCheck: 1,
          checkContent: "县级行政区划编码检查",
          checkDescribe: '验证是否是以"13"开头的纯数字且至少6位的行政区划编码',
          fieldName: "",
          type: "countyCode",
          delBtn: false,
        },
        {
          isCheck: 1,
          checkContent: "经纬度验证",
          checkDescribe: "经纬度是否在河北省境内",
          fieldName: "",
          type: "latlon",
          delBtn: false,
          children: [
            {
              checkDescribe: "验证所需经度字段名",
              fieldName: "",
              type: "lon",
              delBtn: false,
            },
            {
              checkDescribe: "验证所需纬度字段名",
              fieldName: "",
              type: "lat",
              delBtn: false,
            },
          ],
        },
        {
          isCheck: 1,
          checkContent: "行政区划+经纬度验证",
          checkDescribe:
            "检查经纬度点位是否在行政区划范围内部，例：经纬度为116.4,39.9的位置是否在石家庄范围内",
          fieldName: "",
          type: "areaLatlon",
          delBtn: false,
          children: [
            {
              checkDescribe: "验证所需行政区划编码字段名",
              fieldName: "",
              type: "areaCode",
              delBtn: false,
            },
            {
              checkDescribe: "验证所需经度字段名",
              fieldName: "",
              type: "lon",
              delBtn: false,
            },
            {
              checkDescribe: "验证所需纬度字段名",
              fieldName: "",
              type: "lat",
              delBtn: false,
            },
          ],
        },
      ],
      checkDetail: [],
    };
  },
  components: {},
  mounted() {
    let that = this;
    this.checkDetail = JSON.parse(JSON.stringify(this.checkDefaultDetail));
    setTimeout(() => {
      that.resizeWindowEvent();
    }, 100);
  },
  methods: {
    // 重置表格高度
    resizeWindowEvent() {
      let that = this;
      this.tableInterval = setInterval(() => {
        if (that.$refs["ruleContent"]) {
          that.tableMaxHeight = that.$refs["ruleContent"].clientHeight;
          clearInterval(that.tableInterval);
        }
      }, 100);
      window.onresize = () => {
        return (() => {
          if (that.$refs["ruleContent"])
            that.tableMaxHeight = that.$refs["ruleContent"].clientHeight;
        })();
      };
    },
    addRules() {
      let obj = JSON.parse(JSON.stringify(this.defaultField));
      this.checkDetail.unshift(obj);
      this.checkDetail = JSON.parse(JSON.stringify(this.checkDetail));
    },
    deleteRules(index, data, scope) {
      scope._self.$refs["popover-" + scope.$index].doClose();
      this.checkDetail.splice(index, 1);
    },
    beforeUploadFile(e) {
      let that = this;
      if (!jy()) e.stopPropagation();
      function jy() {
        for (let i = 0; i < that.checkDetail.length; i++) {
          let param = that.checkDetail[i];
          if (param.isCheck) {
            if (!param.children) {
              switch (param.type) {
                case "dataIntegrality":
                  if (
                    that.webMessage(param.fieldName.trim(), param.checkContent)
                  )
                    return false;
                  break;
                case "provinceCode":
                case "cityCode":
                case "countyCode":
                  if (
                    that.webMessage(param.fieldName.trim(), param.checkContent)
                  )
                    return false;
                  break;
                default:
                  break;
              }
            } else {
              switch (param.type) {
                case "latlon":
                  let judge1 = that.webMessage(
                    param.children[0].fieldName.trim(),
                    param.checkContent
                  );
                  if (judge1) return false;
                  let judge2 = that.webMessage(
                    param.children[1].fieldName.trim(),
                    param.checkContent
                  );
                  if (judge2) return false;
                  break;
                case "areaLatlon":
                  let judge3 = that.webMessage(
                    param.children[0].fieldName.trim(),
                    param.checkContent
                  );
                  if (judge3) return false;
                  let judge4 = that.webMessage(
                    param.children[1].fieldName.trim(),
                    param.checkContent
                  );
                  if (judge4) return false;
                  let judge5 = that.webMessage(
                    param.children[2].fieldName.trim(),
                    param.checkContent
                  );
                  if (judge5) return false;
                  break;
                default:
                  break;
              }
            }
          }
        }
        return true;
      }
    },
    uploadFile(file) {
      let that = this;
      let obj = new FormData();
      let completeArr = [];
      for (let i = 0; i < this.checkDetail.length; i++) {
        let param = this.checkDetail[i];
        if (param.isCheck) {
          if (!param.children) {
            switch (param.type) {
              case "dataIntegrality":
                completeArr.push(param.fieldName.trim());
                break;
              case "provinceCode":
              case "cityCode":
              case "countyCode":
                obj.append(param.type, param.fieldName.trim());
                break;
              default:
                break;
            }
          } else {
            switch (param.type) {
              case "latlon":
                obj.append(
                  param.type,
                  // {
                  //   check: true,
                  //   lonlat: [
                  //     param.children[0].fieldName,
                  //     param.children[1].fieldName,
                  //   ],
                  // }
                  [
                    param.children[0].fieldName.trim(),
                    param.children[1].fieldName.trim(),
                  ]
                );
                break;
              case "areaLatlon":
                obj.append(param.type, [
                  param.children[0].fieldName.trim(),
                  param.children[1].fieldName.trim(),
                  param.children[2].fieldName.trim(),
                ]);
                break;
              default:
                break;
            }
          }
        }
      }
      if (completeArr.length > 0) {
        obj.append("dataIntegrality", completeArr);
      }
      obj.append("file", file);
      const loading = this.$createLoading("数据质检中，请稍后！");
      qualityApi
        .uploadInspectionFile(obj)
        .then((result) => {
          loading.close();
          if (result.code == 200) {
            that
              .$confirm(result.content, "质检结果", {
                showConfirmButton: false,
                cancelButtonText: "关闭",
                type: "success",
              })
              .then(() => {})
              .catch(() => {});
          } else {
            that
              .$confirm(result.content, "质检结果", {
                showConfirmButton: false,
                cancelButtonText: "关闭",
                type: "error",
              })
              .then(() => {})
              .catch(() => {});
          }
        })
        .catch((err) => {
          loading.close();
          that.$message({
            type: "error",
            message: err,
          });
        });
      return false;
    },
    webMessage(fieldName, str) {
      if (fieldName == "") {
        this.$message({
          message: "请完善" + str,
          type: "warning",
        });
        return true;
      }
      return false;
    },
  },
};
</script>

<style lang="less" scoped>
.el-container {
  display: block;
  width: 100%;
  padding: 10px 20px;
  box-sizing: border-box;
  background: #ffffff;
  overflow: hidden;
  overflow-y: auto;
  .el-row {
    line-height: 40px;
    &::before {
      display: unset;
    }
  }
  .header {
    margin-bottom: 10px;
  }
  .ruleContent {
    height: calc(100% - 110px);
  }
  .el-table {
    /deep/ .el-table--border .el-table__cell:first-child .cell {
      padding-left: unset;
    }
    /deep/ .cell {
      padding-left: unset;
      padding-right: unset;
    }
    .el-input {
      margin: 0 10px;
      width: calc(100% - 20px);
    }
    .morerow {
      .el-row {
        padding-bottom: 10px;
        border-bottom: 1px solid #eeeeee;
        &:last-child {
          padding-top: 10px;
          padding-bottom: 0px;
          border-bottom: 0px;
        }
      }
    }
  }
  .uploadbtn {
    float: right;
    margin-top: 10px;
    margin-right: 20px;
  }
}
</style>