<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="台账编号" prop="params.ext1.tz_id">
        <el-input
          v-model="queryParams.params.ext1.tz_id"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设施名称" prop="params.ext1.tz_ss_name">
        <el-input
          v-model="queryParams.params.ext1.tz_ss_name"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关键字" prop="params.keyword">
        <el-input
          v-model="queryParams.params.keyword"
          placeholder="所属流域/管径范围"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="城区" prop="params.ext1.tz_area_new">
        <el-select
          v-model="queryParams.params.ext1.tz_area_new"
          class="m-2"
          placeholder="请选择"
          clearable
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="item in sys_area"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="管辖班组" prop="params.ext1.tz_ss_unit">
        <el-select v-model="queryParams.params.ext1.tz_ss_unit" class="m-2" placeholder="请选择" clearable
          @keyup.enter.native="handleQuery">
          <el-option v-for="dept in alldept.filter(i => i.deptName.indexOf('生产') != -1 || i.deptName.indexOf('运营') != -1)" :label="dept.deptName" :value="dept.deptId"></el-option>
        </el-select>
        <!-- <el-tree-select
          v-model="queryParams.params.ext1.tz_ss_unit"
          :data="alldept.filter(i => i.deptName.indexOf('生产') != -1 || i.deptName.indexOf('运营') != -1 )"
          check-strictly="true"
          @keyup.enter.native="handleQuery"
        /> -->
      </el-form-item>
      <el-form-item label="排水体制" prop="params.ext1.tz_ss_pstz">
        <el-select
          v-model="queryParams.params.ext1.tz_ss_pstz"
          class="m-2"
          placeholder="请选择"
          clearable
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="item in facilities_pstz"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>

      </el-form-item>


      <!-- <el-form-item>
        <el-button type="primary" icon="search" size="mini" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="refresh" type="primary" 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="search" size="mini" @click="handleQuery"
            >搜索</el-button
          >
        </el-col>

         <el-col :span="1.5">
           <el-button icon="refresh" type="primary" size="mini" @click="resetQuery">重置</el-button>
        </el-col>

      <el-col :span="1.5">
                  <el-button
                    type="primary"
                      @click.stop="exportexcel3()"
                      >导出
                    </el-button>
            </el-col>

                <el-col :span="1.5">
                  <el-upload :limit="1"  v-model:file-list="fileList"  :auto-upload="false"   :on-change="inportexcel3">
                  <el-button
                   type="success"

                      >导入
                    </el-button>
                    </el-upload>
              </el-col>

      <el-col :span="1.5">
        <el-button type="danger" icon="Delete" size="mini" :disabled="multiple" @click.stop="handleDelete"
          v-hasPermi="['system:facilities:remove']">删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          icon="Plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:facilities:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="false"
          type="success"
          icon="Edit"
          size="mini"
          :disabled="single"
          @click.stop="handleUpdate"
          v-hasPermi="['system:facilities:edit']"
          >修改</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button v-if="false"
          type="warning"
          icon="Download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:facilities:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar v-if="false" :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="facilitiesList"
      @row-click="itemclick"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" fixed="left" width="55" align="center" />
      <!-- <el-table-column label="序号" align="center" prop="id" /> -->
      <el-table-column label="台账编号" fixed="left" align="center" prop="ext1.tz_id" />
      <el-table-column label="设施名称" fixed="left" width="200" align="center" prop="ext1.tz_ss_name" />
      <el-table-column label="行政区"  align="center" prop="ext1.tz_area_new">
        <template #default="scope">
          {{
            (sys_area ?? []).filter((i) => i.value === scope.row.ext1.tz_area_new + "")[0]
              ?.label ?? "-"
          }}
        </template>
      </el-table-column>


      <el-table-column label="排水体制" align="center" prop="ext1.tz_ss_pstz">
        <template #default="scope">
          {{
            (facilities_pstz ?? []).filter((i) => i.value === scope.row.ext1.tz_ss_pstz + "")[0]
              ?.label ?? "-"
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="运维长度(米)"
        align="center"
        prop="ext1.tz_ss_data_length"
      />
      <el-table-column label="设施起止点" width="300" align="center" prop="ext1.tz_ss_road_se" />
      <el-table-column label="管径范围(mm)" align="center" prop="ext1.tz_ss_dn" />
      <el-table-column label="辖区班组" width="300" align="center" prop="ext1.tz_ss_unit">
        <template #default="scope">
          {{
            (scope.row.ext1.tz_ss_unit == "" ? [] : scope.row.ext1.tz_ss_unit ?? [])
              .map((i) => {
                return (
                  alldept.find((p) => {
                    return p.deptId + "" === i + "";
                  })?.deptName ?? "-"
                );
              })
              .join("、")
          }}
        </template>
      </el-table-column>
      <el-table-column label="检查井(座)" align="center" prop="ext1.tz_ss_data_jing" />
      <el-table-column label="雨水口(座)" align="center" prop="ext1.tz_ss_data_ysk" />
      <el-table-column label="排河口(座)" align="center" prop="ext1.tz_pfk" />
      <el-table-column label="流域名称" align="center" width="200" prop="ext1.tz_gwly" />
      <el-table-column label="备注" align="center" width="200" prop="ext1.tz_ss_more" />


      <el-table-column label="操作" align="center" fixed="right" width="200" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="mini"
             type="primary"
            @click.stop="handleUpdate(scope.row)"
            v-hasPermi="['system:facilities:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click.stop="handleDelete(scope.row)"
            v-hasPermi="['system:facilities:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination

      :total="total"
       v-model:page="queryParams.params.pageNum"
      v-model:limit="queryParams.params.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设施对话框 -->
    <el-dialog :title="title" v-model="open" width="80vw" append-to-body>
      <el-form ref="form" :model="fform" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="`台账编号：`" required prop="ext1.tz_id"
              ><el-input
                v-model="fform.ext1.tz_id"
                :placeholder="`请输入编号`"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="`行政区：`" prop="ext1.tz_area_new">
              <el-select
                v-model="fform.ext1.tz_area_new"
                class="m-1"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in sys_area"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="`设施名称：`" required prop="ext1.tz_ss_name"
              ><el-input v-model="fform.ext1.tz_ss_name" :placeholder="`请输入`">
              </el-input
            ></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="`移交来源：`" prop="ext1.tz_ss_info"
              ><el-input v-model="fform.ext1.tz_ss_info" :placeholder="`请输入`">
              </el-input
            ></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="`设施起止点：`" required prop="ext1.tz_ss_road_se"
              ><el-input v-model="fform.ext1.tz_ss_road_se" :placeholder="`请输入`">
              </el-input
            ></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="`移交时间：`" prop="ext1.tz_ss_time">
              <el-date-picker
                v-model="fform.ext1.tz_ss_time"
                value-format="YYYY-MM-DD"
                type="date"
                placeholder="请选择"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="`运维长度：`" required prop="ext1.tz_ss_data_length"
              ><el-input v-model="fform.ext1.tz_ss_data_length" type="number" :placeholder="`请输入`">
                <template #append>(米)</template>
              </el-input></el-form-item
            >
          </el-col>
          <el-col :span="12">
            <el-form-item :label="`移交单位：`" prop="ext1.tz_ss_from"
              ><el-input v-model="fform.ext1.tz_ss_from" :placeholder="`请输入`">
              </el-input
            ></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="`管径范围：`" prop="ext1.tz_ss_dn"
              ><el-input v-model="fform.ext1.tz_ss_dn" @change="() => { fform.ext1.tz_ss_dn = check(fform.ext1.tz_ss_dn)}"  :placeholder="`请输入`">
                <template #append>(mm)</template>
              </el-input></el-form-item
            >
          </el-col>

          <el-col :span="12">
            <el-form-item :label="`接收时间：`" prop="ext1.tz_jssj">
              <el-date-picker
                v-model="fform.ext1.tz_jssj"
                value-format="YYYY-MM-DD"
                type="date"
                placeholder="请选择"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="`所属流域：`" prop="ext1.tz_ssly"
              ><el-input v-model="fform.ext1.tz_ssly" :placeholder="`请输入`">
              </el-input
            ></el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="`辖区班组：`" prop="ext1.tz_ss_unit">
              <el-tree-select
                v-model="fform.ext1.tz_ss_unit"
                multiple
                :data="treedept"
                check-strictly="true"
            /></el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="`排水体制：`" prop="ext1.tz_ss_pstz">
              <el-select v-model="fform.ext1.tz_ss_pstz" class="m-1" placeholder="请选择">
                <el-option
                  v-for="item in facilities_pstz"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item :label="`检查井：`" prop="ext1.tz_ss_data_jing"
              ><el-input v-model="fform.ext1.tz_ss_data_jing" type="number" :placeholder="`请输入`">
                <template #append>(座)</template>
              </el-input></el-form-item
            >
          </el-col>
          <el-col :span="6">
            <el-form-item :label="`雨口井：`" prop="ext1.tz_ss_data_ysk"
              ><el-input v-model="fform.ext1.tz_ss_data_ysk" type="number" :placeholder="`请输入`">
                <template #append>(座)</template>
              </el-input></el-form-item
            >
          </el-col>
          <el-col :span="6">
            <el-form-item :label="`排河口：`" prop="ext1.tz_pfk"
              ><el-input v-model="fform.ext1.tz_pfk" type="number" :placeholder="`请输入`">
                <template #append>(座)</template>
              </el-input></el-form-item
            >
          </el-col>
          <el-col :span="4" style="text-align: right">
            <span style="font-weight: bold; line-height: 30px; padding-right: 20px">
              雨水口检测详情</span
            >
          </el-col>
          <el-col :span="4">
            <el-form-item :label="`单箅:`" prop="ext1.tz_bz_dan" label-width="60px"
              ><el-input v-model="fform.ext1.tz_bz_dan" type="number" :placeholder="`请输入`">
                <template #append>(个)</template>
              </el-input></el-form-item
            >
          </el-col>
          <el-col :span="4">
            <el-form-item :label="`双箅:`" prop="ext1.tz_bz_shuang" label-width="60px"
              ><el-input v-model="fform.ext1.tz_bz_shuang" type="number" :placeholder="`请输入`">
                <template #append>(个)</template>
              </el-input></el-form-item
            >
          </el-col>
          <el-col :span="4">
            <el-form-item :label="`三箅:`" prop="ext1.tz_bz_san" label-width="60px"
              ><el-input v-model="fform.ext1.tz_bz_san"  type="number" :placeholder="`请输入`">
                <template #append>(个)</template>
              </el-input></el-form-item
            >
          </el-col>
          <el-col :span="4">
            <el-form-item :label="`四箅:`" prop="ext1.tz_bz_si" label-width="60px"
              ><el-input v-model="fform.ext1.tz_bz_si" type="number" :placeholder="`请输入`">
                <template #append>(个)</template>
              </el-input></el-form-item
            >
          </el-col>
          <el-col :span="4">
            <el-form-item :label="`多箅:`" prop="ext1.tz_bz_duo" label-width="60px"
              ><el-input v-model="fform.ext1.tz_bz_duo" type="number" :placeholder="`请输入`">
                <template #append>(个)</template>
              </el-input></el-form-item
            >
          </el-col>

          <!-- <el-col :span="12" v-for="itemkey in Object.keys(facilities_obj)">
            <el-form-item
              :label="`${getfacilitiesdesname(itemkey).des}：`"
              prop="areaDes"
            >
              <el-input
                v-if="getfacilitiesdesname(itemkey).type == 'text'"
                v-model="fform.ext1[itemkey + '']"
                :placeholder="`请输入${getfacilitiesdesname(itemkey).des}`"
              />
              <el-input
                type="textarea"
                v-if="getfacilitiesdesname(itemkey).type == 'textarea'"
                v-model="fform.ext1[itemkey + '']"
                :placeholder="`请输入${getfacilitiesdesname(itemkey).des}`"
              />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: right">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  listFacilities,
  listFacilities1,
  getFacilities,
  delFacilities,
  addFacilities,
  updateFacilities,
  uploadFacilities
} from "@/api/system/facilities";
import ImageUpload from "@/components/ImageUpload";
import { useDict } from "@/utils/dict";
import { Search } from "@element-plus/icons-vue";
import { cloneDeep } from "lodash";
import { listDept, getDept } from "@/api/system/dept";
import { treeselect as deptTreeselect } from "@/api/system/dept";
import { getfacilitiesdesname } from "@/utils/ruoyi";
import { defineComponent, ref, onMounted, watch } from "vue";
import router from "../../../router";
const {
  task_status,
  task_type,
  task_event_type,
  task_event_category,
  sys_area,
  facilities_pstz,
} = useDict(
  "task_status",
  "task_type",
  "task_event_type",
  "task_event_category",
  "sys_area",
  "facilities_pstz"
);
const { proxy } = getCurrentInstance();

// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 设施表格数据
const facilitiesList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 查询参数
const facilities_obj = ref({
  tz_id: "",
  tz_dhx: "",
  tz_dlj: "",
  tz_jlj: "",
  tz_jsk: "",
  tz_pfk: "",
  tz_gjsj: "",
  tz_gwly: "",
  tz_jgsj: "",
  tz_road: "",
  tz_yssj: "",
  tz_bz_si: "",
  tz_ss_cz: "",
  tz_ss_dn: "",
  tz_xlymc: "",
  tz_bz_dan: "",
  tz_bz_duo: "",
  tz_bz_san: "",
  tz_ss_from: "",
  tz_ss_info: "",
  tz_ss_more: "",
  tz_ss_name: "",
  tz_ss_pstz: "",
  tz_ss_road: "",
  tz_ss_time: "",
  tz_jssj: "",
  tz_ssly: "",
  tz_pkbh: "",
  pics:"",
  tz_ss_type: "",
  tz_ss_unit: "",
  tz_zm_type: "",
  tz_area_new: "",
  tz_area_old: "",
  tz_bz_total: "",
  tz_ss_river: "",
  tz_bz_shuang: "",
  tz_xfgj_dxgj: "",
  tz_xfgj_xxgq: "",
  tz_xfgj_zxgj: "",
  tz_ss_road_se: "",
  tz_xfgj_tdxgj: "",
  tz_ss_data_ysk: "",
  tz_ss_road_end: "",
  tz_zm_material: "",
  tz_ss_data_jing: "",
  tz_ss_road_start: "",
  tz_ss_data_length: "",
  tz_ss_data_main_length: "",
  tz_ss_data_minor_length: "",
});

const alldept = ref([]);

const fileList = ref([])


listDept().then((response) => {
  alldept.value = cloneDeep(response.data);
});

function setdatakey(dept) {
  if (dept.children) {
    dept.children = dept.children.map((i) => {
      return setdatakey(i);
    });
  }
  dept["value"] = dept.id;
  return dept;
}

const treedept = ref([
  {
    value: "1",
    label: "ss",
  },
  {
    value: "2",
    label: "ss1",
  },
]);
deptTreeselect().then((res) => {
  treedept.value = [setdatakey(res.data[0])];
});

const validatedhx = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入编号"));
    return;
  }
  var p = {
    params: {
      ext1: {
        tz_id: value,
      },
    },
  };
  listFacilities1(p).then((response) => {
    if (response.total > 0 && response.rows[0].id != fform.value.id) {
      callback(new Error("编号已存在"));
    }
    callback();
  });
};

const data = reactive({
  fform: { ext1: cloneDeep(facilities_obj.value) },
  queryParams: {
    params: {
      pageNum: 1,
      pageSize: 10,
      keyword: "",
      ext1: {
        tz_id: "",
        tz_ss_name: "",
        tz_area_new: "",
        tz_ss_unit: "",
        tz_ss_pstz: "",
      },
    },
  },
  rules: {
    "ext1.tz_id": [{ validator: validatedhx, trigger: "blur" }],
    "ext1.tz_ss_name": [{ required: true, message: "请输入名称", trigger: "blur" }],
    "ext1.tz_ss_road_se": [{ required: true, message: "请输入起止点", trigger: "blur" }],
    "ext1.tz_ss_data_length": [
      { required: true, message: "请输入长度", trigger: "blur" },
    ],
  },
});
const { queryParams, fform, rules } = toRefs(data);

onMounted(() => {
  getList();
});

const getList = () => {
  // debugger
  loading.value = true;

  listFacilities1(queryParams.value).then((response) => {
    facilitiesList.value = response.rows.map((i) => {
      i.ext1 = JSON.parse(i.ext1);
      return i;
    });
    total.value = response.total;
    loading.value = false;
  });
};


const exportexcel3 = () => {
  // loading.value = true;
  var q = cloneDeep(queryParams.value);
  var c = JSON.stringify(cloneDeep(q.params));
  delete q.params;
  // console.log(q.params)
  q["params"] = {"q":c};

   proxy.download(
    "system/facilities/export3",
    {
      ...q,
    },
    `南宁北排管网公司设施台账.xlsx`
  );


}

const inportexcel3 = (files, uploadFiles) => {
  // console.log(files)
  //  console.log(uploadFiles)
  uploadFacilities(files.raw).then(() => {
     proxy.$modal.msgSuccess("上传成功");
    getList();
  })

}


// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
};
// 表单重置
const reset = () => {
  fform.value = {
    id: null,
    areaDes: null,
    areaAdDes: null,
    exId: null,
    name: null,
    roadName: null,
    nature: null,
    addrFrom: null,
    addrEnd: null,
    exId1: null,
    ext1: cloneDeep(facilities_obj.value),
  };
  proxy.resetForm("form");
  handleQuery()
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  proxy.resetForm("queryForm");
  handleQuery();
};
// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};
/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = "添加设施";
};
/** 修改按钮操作 */
const handleUpdate = (row) => {
  reset();
  const id = row.id || ids.value;
  getFacilities(id).then((response) => {
    fform.value = response.data;
    fform.value.ext1 = JSON.parse(fform.value.ext1);
    open.value = true;
    title.value = "修改设施";
  });
};
/** 提交按钮 */
const submitForm = () => {
  proxy.$refs["form"]
    .validate((valid) => {
      console.log(valid);
      if (valid) {
        if (fform.value.id != null) {
          var ddf = cloneDeep(fform.value);
          ddf.ext1 = JSON.stringify(ddf.ext1);
          updateFacilities(ddf).then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          var ddf = cloneDeep(fform.value);
          ddf.ext1 = JSON.stringify(ddf.ext1);
          addFacilities(ddf).then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    });

};
/** 删除按钮操作 */
const handleDelete = (row) => {
  debugger
  const ids1 = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除设施编号为"' + ids1 + '"的数据项？')
    .then(function () {
      return delFacilities(ids1);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};
/** 导出按钮操作 */
const handleExport = () => {
  proxy.download(
    "system/facilities/export",
    {
      ...queryParams.value,
    },
    `facilities_${new Date().getTime()}.xlsx`
  );
};
const itemclick = (row, index) => {
  router.push("/system/facilities/detail/" + row.id);
};


const check = (str) =>{
  var temp = ""; for (var i = 0; i < str.length; i++)
    if (str.charCodeAt(i) > 0 && str.charCodeAt(i) < 255)
      temp += str.charAt(i)
  return temp
}
</script>
