<template>
  <div>
    <el-breadcrumb separator="/" style="margin-bottom: 20px">
      <el-breadcrumb-item
        v-for="(item, index) in routeList"
        :key="item + index"
        :to="{ path: item.path }"
      >
        {{ item.routeName }}
      </el-breadcrumb-item>
    </el-breadcrumb>
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="组织名称" prop="organizationName">
        <el-input
          v-model="queryParams.data.organizationName"
          placeholder="请输入组织名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        >
          <el-button
            type="primary"
            slot="append"
            icon="el-icon-search"
            size="small"
            @click="handleQuery"
          ></el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="所属区划" prop="adcd">
        <!-- <el-input
          v-model="queryParams.data.adcd"
          placeholder="请输入所属区划"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        /> -->
        <el-cascader
          v-model="queryParams.data.adcd"
          :props="areasOptionProps"
          placeholder="请选择所属区划"
          clearable
          size="small"
          style="width: 100%"
          @change="handleQuery"
        >
        </el-cascader>
      </el-form-item>
      <!-- <el-form-item
        label="负责人职务"
        prop="chargePersonDuites"
        label-width="84px"
      >
        <el-input
          v-model="queryParams.data.chargePersonDuites"
          placeholder="请输入负责人职务"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <!-- <el-button
          type="cyan"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        > -->
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['df:fxzz:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['df:fxzz:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['df:fxzz:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="fxzzList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" fixed />
      <el-table-column
        label="序号"
        type="index"
        width="50"
        align="center"
        fixed
      />
      <el-table-column
        label="堤防名称"
        align="center"
        prop="dikeName"
        min-width="120"
      />
      <!-- <el-table-column
        label="堤防名称"
        align="center"
        prop="dikeCode"
        :formatter="dikeCodeFormat"
        min-width="120"
      /> -->
      <el-table-column
        label="组织名称"
        align="center"
        prop="organizationName"
        min-width="120"
      />
      <el-table-column
        label="所属区划"
        align="center"
        prop="adcd"
        :formatter="$formatAdcd"
        min-width="120"
      />
      <el-table-column
        label="负责人名称"
        align="center"
        prop="chargePersonName"
        min-width="120"
      />
      <el-table-column
        label="负责人电话"
        align="center"
        prop="chargePersonPhone"
        min-width="120"
      />
      <el-table-column
        label="负责人职务"
        align="center"
        prop="chargePersonDuites"
        min-width="120"
      />
      <el-table-column
        label="负责人类型"
        align="center"
        prop="chargePersonType"
        :formatter="typeFormat"
        min-width="120"
      />
      <!-- <el-table-column
        label="成员"
        align="center"
        prop="member"
        min-width="120"
      /> -->

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="180"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['df:fxzz:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['df:fxzz:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改防汛组织对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1200px"
      append-to-body
      :close-on-click-modal="false"
      @close="close"
    >
      <div class="listTitle">
        <span>防汛组织信息</span>
        <!-- <span class="addBtn" @click="handleAdd('0')">
        <i class="el-icon-plus"></i>
        添加
      </span> -->
      </div>
      <el-row :gutter="15">
        <el-form ref="form" :model="form" :rules="rules" label-width="96px">
          <el-form-item label="堤防名称" prop="dikeCode">
            <linkDike :form="form" v-if="open" />
            <!-- <el-select
              v-model="form.dikeCode"
              placeholder="请选择堤防名称"
              style="width: 100%"
              v-scroll="selectSearch"
              filterable
              clearable
              remote
              reserve-keyword
              :remote-method="remoteMethod"
              :loading="selectLoading"
            >
              <el-option
                v-for="dict in dikeNameOptions"
                :key="dict.id"
                :label="dict.dikeName"
                :value="dict.dikeCode"
                @click.native="chooseDike(dict)"
              ></el-option>
            </el-select> -->
          </el-form-item>
          <el-col :span="12">
            <el-form-item label="组织名称" prop="organizationName">
              <el-input
                v-model="form.organizationName"
                placeholder="请输入组织名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属区划" prop="adcd">
              <!-- <el-input v-model="form.adcd" placeholder="请输入所属区划" /> -->
              <el-cascader
                :options="areasOptions"
                v-model="form.adcd"
                :props="areasOptionProps"
                placeholder="请选择所属区划"
                clearable
                size="small"
                style="width: 100%"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人名称" prop="chargePersonName">
              <el-input
                v-model="form.chargePersonName"
                placeholder="请输入负责人名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人电话" prop="chargePersonPhone">
              <el-input
                v-model="form.chargePersonPhone"
                placeholder="请输入负责人电话"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人职务" prop="chargePersonDuites">
              <el-input
                v-model="form.chargePersonDuites"
                placeholder="请输入负责人职务"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人类型" prop="chargePersonType">
              <el-select
                v-model="form.chargePersonType"
                placeholder="请选择负责人类型"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in typeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>

      <div class="listTitle">
        <span>防汛组织成员</span>
        <!-- <span class="addBtn" @click="handleAdd('0')">
        <i class="el-icon-plus"></i>
        添加
      </span> -->
      </div>
      <div class="member" ref="member">
        <template v-for="(item, index) in counter">
          <msFxzzMember
            :ref="'msFxzzMember' + index"
            :key="item + index"
            :index="index"
            :isFirst="index == 0 ? isFirst : false"
            :status="isEdit"
            :editItem="item"
            :addForm="addForm"
            @delForm="delForm"
          />
        </template>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listFxzz,
  getFxzz,
  delFxzz,
  addFxzz,
  updateFxzz,
  exportFxzz,
} from "@/api/yg/dike/fxzz";
import {
  listFxzzcy,
  getFxzzcy,
  delFxzzcy,
  addFxzzcy,
  updateFxzzcy,
  updataAllFxzzcy,
  exportFxzzcy,
} from "@/api/yg/dike/fxzzcy";
import { listJbxx, getJbxx } from "@/api/yg/dike/jbxx";
import { getAreasData } from "@/api/areas/index";
import msFxzzMember from "./components/msFxzzMember.vue";
import linkDike from "@/components/linkNameSelect/linkDike.vue";
import { cascaderLazyLoad } from "@/utils/elUtils";

export default {
  name: "Fxzz",
  components: {
    msFxzzMember,
    linkDike,
  },
  data() {
    return {
      // 面包屑，路由信息
      routeList: [
        {
          path: "/dike/safetyManage/floodControlManagement/tissue",
          routeName: "防汛组织管理",
        },
      ],
      areasOptionProps: {
        emitPath: false,
        checkStrictly: true, //选择任意一级
        expandTrigger: "hover",
        lazy: true,
        lazyLoad: cascaderLazyLoad,
      },
      areasOptions: [],
      // 遮罩层
      loading: true,
      selectLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 防汛组织表格数据
      fxzzList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型字典
      typeOptions: [],
      // 堤防项目
      dikeNameOptions: [],
      // 堤防查询参数
      dikeNameQueryParams: {
        pageNum: 1,
        pageSize: 10,
        ids: null,
        data: {
          dikeName: null,
        },
        // 排序方式
        params: {
          // 按哪个字段排序
          orderBy: "create_time",
          // desc降序，升序asc
          sortBy: "desc",
        },
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ids: null,
        data: {
          organizationName: null,
          adcd: null,
          chargePersonName: null,
          chargePersonPhone: null,
          chargePersonDuites: null,
          chargePersonType: null,
          member: null,
          createUid: null,
          updateUid: null,
          proCode: null,
          proNo: null,
          owerDept: null,
          relation: null,
        },
        // 排序方式
        params: {
          // 按哪个字段排序
          orderBy: "create_time",
          // desc降序，升序asc
          sortBy: "desc",
        },
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        dikeCode: [
          { required: true, message: "请选择堤防名称", trigger: "blur" },
        ],
        organizationName: [
          { required: true, message: "请输入组织名称", trigger: "blur" },
        ],
        chargePersonPhone: [
          {
            pattern:
              /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: "手机号格式不正确",
            trigger: "blur",
          },
        ],
      },
      counter: [{}],
      delIdList: [],
      isFirst: true,
      isEdit: false,
    };
  },
  created() {
    this.getList();
    listJbxx(this.dikeNameQueryParams).then((res) => {
      // console.log(111, res);
      this.dikeNameOptions = res.records;
    });
    this.getTreeData();
    this.getDicts("person_dept").then((response) => {
      this.typeOptions = response.data;
    });
  },
  methods: {
    remoteMethod(query) {
      if (query !== "") {
        this.selectLoading = true;
        // console.log(444, query);
        this.dikeNameQueryParams.data.dikeName = query;
        listJbxx(this.dikeNameQueryParams).then((res) => {
          this.dikeNameOptions = res.records;
          this.selectLoading = false;
        });
      }
    },
    selectSearch() {
      this.dikeNameQueryParams.pageNum += 1;
      listJbxx(this.dikeNameQueryParams).then((res) => {
        // console.log(111, res);
        this.dikeNameOptions = [...this.dikeNameOptions, ...res.records];
        // console.log(111, this.dikeNameOptions);
      });
    },
    chooseDike(item) {
      this.form.dikeName = item.dikeName;
    },
    addForm(index) {
      // console.log(44444, this.$refs.noticePart.$refs["noticeForm0"]);
      // 重新赋值每种标牌首项
      if (this.counter.length == 1) {
        console.log(this.$refs, this.$refs.msFxzzMember0[0]);
        this.counter[0] = this.$refs.msFxzzMember0[0].form;
      }

      // 先增加节点
      this.counter.push({});
      // 再改变其存储的值
      this.$nextTick(() => {
        this.counter[this.counter.length - 1] =
          this.$refs["msFxzzMember" + (index + 1)][0].form;
        console.log(
          66666,
          this.counter,
          this.$refs["msFxzzMember" + (index + 1)][0].form
        );
      });
    },
    getTreeData() {
      getAreasData().then((items) => {
        // console.log("getAreasData", items.data);
        let res = [];
        let getChildren = (res, pid) => {
          for (const i of items.data) {
            if (i.parentid === pid) {
              const newItem = {
                label: i.name,
                value: i.id,
              };
              if (i.layer != 3) newItem.children = [];
              res.push(newItem);
              getChildren(newItem.children, newItem.value);
            }
          }
        };
        getChildren(res, items.data[0].parentid);
        console.log(66666666666, res);
        this.areasOptions = res;
        // return res;
      });
    },
    // 类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.chargePersonType);
    },
    dikeCodeFormat(row) {
      const dikeCode = row.dikeCode;
      // const name = await new Promise(function (resolve, reject) {
      //   getJbxx(id).then((res) => {
      //     // console.log(111, res);
      //     resolve(res.data.dikeName);
      //   });
      // });
      let data = this.dikeNameOptions.find((res) => res.dikeCode == dikeCode);
      if (data) return data.dikeName;
    },
    /** 查询防汛组织列表 */
    getList() {
      this.loading = true;
      // this.queryParams.data.dikeCode = this.$route.query.baseDataId;
      listFxzz(this.queryParams).then((response) => {
        this.fxzzList = response.records;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.delIdList = [];
      this.counter = [{}];
      this.form = {
        id: null,
        organizationName: null,
        adcd: null,
        chargePersonName: null,
        chargePersonPhone: null,
        chargePersonDuites: null,
        chargePersonType: null,
        member: null,
        createUid: null,
        updateUid: null,
        createTime: null,
        updateTime: null,
        proCode: null,
        proNo: null,
        owerDept: null,
        remark: null,
        relation: null,
      };
      this.resetForm("form");
    },
    // 查询表单重置
    resetQueryForm() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        data: {
          id: null,
          organizationName: null,
          adcd: null,
          chargePersonName: null,
          chargePersonPhone: null,
          chargePersonDuites: null,
          chargePersonType: null,
          member: null,
          createUid: null,
          updateUid: null,
          createTime: null,
          updateTime: null,
          proCode: null,
          proNo: null,
          owerDept: null,
          remark: null,
          relation: null,
        },
        params: {
          // 按哪个字段排序
          orderBy: "create_time",
          // desc降序，升序asc
          sortBy: "desc",
        },
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetQueryForm();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isEdit = false;
      this.open = true;
      this.title = "添加防汛组织";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isEdit = true;
      const id = row.id || this.ids;
      const organizationId = row.id || this.ids[0];
      console.log(444, id);
      getFxzz(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改防汛组织";
      });
      listFxzzcy({ data: { organizationId: organizationId } }).then((res) => {
        console.log(6666, res);
        this.counter = res.records;
      });
    },
    close() {
      this.$refs.msFxzzMember0[0].validClear();
    },
    /** 提交按钮 */
    submitForm() {
      // 且运算
      let isAllTrue = true;
      this.counter.forEach((item, index) => {
        this.$refs["msFxzzMember" + index][0].validateForm();
        isAllTrue = isAllTrue && this.$refs["msFxzzMember" + index][0].valid;
      });
      console.log("全部表单是否通过校验", isAllTrue);
      this.$refs["form"].validate((valid) => {
        if (valid && isAllTrue) {
          const C0 =
            this.counter.length > 1
              ? this.counter
              : this.$refs["msFxzzMember0"][0].form.name
              ? [this.$refs["msFxzzMember0"][0].form]
              : [];
          if (this.isEdit) {
            updateFxzz(this.form).then((response) => {
              if (response.code === 200) {
                C0.forEach((item, index) => {
                  if (!item.organizationId) {
                    C0[index].organizationId = this.form.id;
                  }
                });
                updataAllFxzzcy(C0).then((res) => {
                  if (res.code === 200) {
                    this.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                  }
                });
              }
            });
            if (this.delIdList.length > 0) delFxzzcy(this.delIdList);
          } else {
            this.form.cy = C0;
            // this.form.dikeCode = this.$route.query.baseDataId;
            addFxzz(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      if (ids) {
        this.$confirm("是否删除选中的数据？", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return delFxzz(ids);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          })
          .catch(function () {});
      } else {
        this.$message.warning("请选择要删除的数据！！");
      }
    },
    // 弹出框每一个小表单的减号 删除
    delForm(itemId, index) {
      console.log(111, itemId, index);
      this.counter.splice(index, 1);
      if (itemId) this.delIdList.push(itemId);
      console.log(222, this.delIdList);
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/css/dialog.scss";

.listTitle {
  font-size: 14px;
  padding-left: 10px;
  padding-right: 30px;
  margin: 20px 0;
  border-left: 2px solid #36b29e;
  display: flex;
  justify-content: space-between;
  span:nth-child(1) {
    font-weight: bold;
  }
  .addBtn {
    color: #36b29e;
    cursor: pointer;
  }
  .addBtn:hover {
    color: #31a08e;
  }
}
.listTitle:nth-child(1) {
  margin-top: 0;
}
</style>
