<template>
  <div style="padding: 10px">
    <div class="formbody">
      <el-form :inline="true" v-model="queryparameters" class="demo-form-inline">
        <el-col :span="6">
          <el-form-item label="设施台账">
            <el-select v-model="queryparameters.facilitiesId" class="m-1" placeholder="请选择">
              <el-option v-for="item in alldevices" :label="item.exId" :value="item.exId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="设施名称">
            <el-select v-model="queryparameters.facilitiesId" class="m-1" placeholder="请选择">
              <el-option v-for="item in alldevices" :label="item.ext1.tz_ss_name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="计划状态" v-if="currentstatus == 1">
            <el-select v-model="queryparameters.status" class="m-1" placeholder="请选择">
              <el-option v-for="item in maintain_status" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="养护类型">
            <el-select v-model="queryparameters.maintainType" class="m-2" placeholder="请选择">
              <el-option v-for="item in maintain_type" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="班组区域">
            <el-tree-select v-model="queryparameters.taskDeptRange" multiple :data="treedept" check-strictly="true" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="任务时间">
            <el-date-picker v-model="qdate" type="daterange" value-format="YYYY-MM-DD" range-separator="到"
              start-placeholder="开始时间" end-placeholder="结束时间" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="关键字">
            <el-input v-model="queryparameters.searchkey" placeholder="设施名称/道路"></el-input>
          </el-form-item>
        </el-col>

     <el-col :span="12">
        <div style="float: right">
          <el-form-item>
            <el-button type="primary" @click="resetall">重置</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getList">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="addmaintain">新增</el-button>
          </el-form-item>
        </div>
        </el-col>
      </el-form>

      <div>
        <el-table :data="tableData" class="eltable" style="width: 100%" @row-click="tblrowclick">
          <el-table-column prop="taskCode" label="台账编号">
            <template #default="scope">
              {{
                  alldevices.filter((i) => i.id === scope.row.facilitiesId)[0]?.ext1.tz_id ??
                  "-"
              }}
            </template>
          </el-table-column>
          <el-table-column prop="taskCode" label="设施名称">
            <template #default="scope">
              {{
                  alldevices.filter((i) => i.id === scope.row.facilitiesId)[0]?.ext1.tz_ss_name ??
                  "-"
              }}
            </template>
          </el-table-column>
          <el-table-column prop="taskCode" label="城区">
            <template #default="scope">
              {{
                  (sys_area ?? []).filter((i) => i.value === alldevices.filter((i) => i.id ===
                    scope.row.facilitiesId)[0]?.ext1.tz_area_new + "")[0]
                    ?.label ?? "-"
              }}
            </template>
          </el-table-column>
          <el-table-column label="养护类型">
            <template #default="scope">
              {{
                  maintain_type.filter(
                    (i) => i.value + "" === scope.row.maintainType + ""
                  )[0]?.label ?? "-"
              }}
            </template>
          </el-table-column>
          <el-table-column label="路段范围">
            <template #default="scope">
              {{
                  alldevices.filter((i) => i.id === scope.row.facilitiesId)[0]?.ext1.tz_ss_road_se ??
                  "-"
              }}
            </template>
          </el-table-column>
          <el-table-column prop="ext1.task.datestart" label="计划时间" />
          <el-table-column prop="ext1.task.dateend" label="完成时间" />
          <el-table-column label="管径(mm)">
            <template #default="scope">
              {{
                  scope.row.ext1.task.gd.map(i => i.yh_gj).join("、")
              }}
            </template>
          </el-table-column>
          <el-table-column label="管道清淤(米)">
            <template #default="scope">
              {{
                  evilFn((scope.row.ext1.task.gd).map(i => (i.yh_length && i.yh_length != '' ? parseFloat(i.yh_length) : 0)
                  ).join("+"))
              }}
            </template>
          </el-table-column>

          <el-table-column label="雨水口清掏（座）">
            <template #default="scope">
              {{
                  scope.row.ext1.task.ysk
              }}
            </template>
          </el-table-column>

          <el-table-column label="检查井清掏（座）">
            <template #default="scope">
              {{
                  scope.row.ext1.task.jcj
              }}
            </template>
          </el-table-column>



          <el-table-column label="计划状态">
            <template #default="scope">
              {{
                  maintain_status.filter((i) => i.value === scope.row.status + "")[0]
                    ?.label ?? "-"
              }}
            </template>
          </el-table-column>

          <el-table-column prop="maintainUnit" label="辖区班组">
            <template #default="scope">
              {{
                  (scope.row.ext1.facilities_unit == "" ? [] : scope.row.ext1.facilities_unit ?? [])
                    .map((i) => {
                      return (
                        alldept.find((p) => {
                          return p.deptId + "" === i + "";
                        })?.deptName ?? "-"
                      );
                    })
                    .join("、")
              }}
            </template>
          </el-table-column>
          <el-table-column label="养护单位">
            <template #default="scope">
              {{
                  scope.row.maintainUnit
              }}
            </template>
          </el-table-column>
          <el-table-column label="备注">
            <template #default="scope">
              {{
                  scope.row.maintainRemark
              }}
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作">
            <template #default="scope">
              <el-button text size="small" @click.stop="edittask(scope.row)">修改
              </el-button>
              <el-popconfirm title="确定删除?" @confirm="deltask(scope.row)">
                <template #reference>
                  <el-button text size="small" @click.stop="">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="ext1" label="责任人" width="180">
            <template #default="scope">
              {{ (scope.row.ext1 == null || scope.row.ext1 === "")? "暂无" : scope.row.ext1 }}
            </template>
          </el-table-column> -->
        </el-table>
        <div style="position: relative; padding-right: 20px; margin-top: -20px">
          <Pagination :total="pagedata.total ?? 0" v-show="pagedata.total > 0" v-model:page="queryparameters.pageNum"
            v-model:limit="queryparameters.pageSize" @pagination="getList"></Pagination>
        </div>
      </div>
    </div>

    <el-dialog v-model="showadd" v-loading="loading" title="新增养护计划" width="70%" append-to-body draggable>
      <div>
        <el-form :model="maintaininfo" ref="form">
          <div style="font-weight: bold; font-size: 15px; margin-bottom: 10px">
            任务基础信息
          </div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="关联设施" label-width="150px">
                <el-select v-model="maintaininfo.facilitiesId" filterable placeholder="请选择设备">
                  <el-option v-for="item in alldevices" :label="item.ext1.tz_id" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="养护类型" required label-width="150px" prop="maintainType">
                <el-select v-model="maintaininfo.maintainType" filterable placeholder="请选择类型">
                  <el-option v-for="item in maintain_type" :label="item.label" :value="parseInt(item.value)">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="设施名称" label-width="150px">
                <el-input v-model="maintaininfo.ext1.facilities_name" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所在道路" label-width="150px">
                <el-input v-model="maintaininfo.ext1.facilities_road" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="运维长度" label-width="100px">
                <el-input v-model="maintaininfo.ext1.facilities_length" type="number" placeholder="请输入"><template
                    #append>(米)</template></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="管径范围" label-width="100px">
                <el-input v-model="maintaininfo.ext1.facilities_gjfw" type="number" placeholder="请输入"><template
                    #append>(mm)</template></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="养护起点" required label-width="100px" prop="ext1.facilities_start">
                <el-input v-model="maintaininfo.ext1.facilities_start" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="辖区班组" label-width="100px">
                <el-tree-select v-model="maintaininfo.ext1.facilities_unit" multiple :data="treedept"
                  check-strictly="true" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="养护终点" required label-width="100px" prop="ext1.facilities_end">
                <el-input v-model="maintaininfo.ext1.facilities_end" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="计划备注" label-width="150px">
                <el-input v-model="maintaininfo.maintainDes" type="textarea" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="养护单位" label-width="150px">
                <el-input v-model="maintaininfo.maintainUnit" type="textarea" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <div style="font-weight: bold; font-size: 15px; margin-bottom: 10px">
            养护计划量及任务派发
          </div>
          <el-row>
            <el-col :span="8">
              <el-form-item label="检查井" label-width="100px">
                <el-input v-model="maintaininfo.ext1.task.jcj" type="number" placeholder="请输入"><template
                    #append>(座)</template></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="雨水口" label-width="100px">
                <el-input v-model="maintaininfo.ext1.task.ysk" type="number" placeholder="请输入"><template
                    #append>(座)</template></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="排河口" label-width="100px">
                <el-input v-model="maintaininfo.ext1.task.phk" type="number" placeholder="请输入"><template
                    #append>(座)</template></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="4">
              <div style="
                  font-weight: bold;
                  font-size: 15px;
                  text-align: right;
                  padding-right: 30px;
                  padding-top: 3px;
                ">
                雨水口养护详情
              </div>
            </el-col>
            <el-col :span="4" style="padding-right: 10px">
              <el-form-item label="单箅" label-width="40px">
                <el-input v-model="maintaininfo.ext1.task.bz_dan" type="number" placeholder="请输入"><template
                    #append>(个)</template></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" style="padding-right: 10px">
              <el-form-item label="双箅" label-width="40px">
                <el-input v-model="maintaininfo.ext1.task.bz_shuang" type="number" placeholder="请输入"><template
                    #append>(个)</template></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" style="padding-right: 10px">
              <el-form-item label="三箅" label-width="40px">
                <el-input v-model="maintaininfo.ext1.task.bz_san" type="number" placeholder="请输入"><template
                    #append>(个)</template></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" style="padding-right: 10px">
              <el-form-item label="四箅" label-width="40px">
                <el-input v-model="maintaininfo.ext1.task.bz_si" type="number" placeholder="请输入"><template
                    #append>(个)</template></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" style="padding-right: 10px">
              <el-form-item label="多箅" label-width="40px">
                <el-input v-model="maintaininfo.ext1.task.bz_duo" type="number" placeholder="请输入"><template
                    #append>(个)</template></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="4">
              <div style="
                  font-weight: bold;
                  font-size: 15px;
                  text-align: right;
                  padding-right: 30px;
                  padding-top: 3px;
                ">
                管道养护详情
              </div>
            </el-col>
            <el-col :span="20">
              <el-row>
                <el-col :span="24">
                  <el-row v-for="(item, index) in maintaininfo.ext1.task.gd">
                    <el-col :span="8" style="padding-right: 10px">
                      <el-form-item label="管道养护" label-width="80px">
                        <el-input v-model="item.yh_length" type="number" placeholder="请输入"><template
                            #append>(米)</template></el-input>
                      </el-form-item>
                    </el-col>

                    <el-col :span="8" style="padding-right: 10px">
                      <el-form-item label="管径" label-width="80px">
                        <el-input v-model="item.yh_gj" type="number" placeholder="请输入"><template #append>(mm)</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8" style="padding-right: 40px; position: relative">
                      <el-form-item label="备注" label-width="40px">
                        <el-input v-model="item.yh_remark" type="text" placeholder="请输入"></el-input>
                      </el-form-item>
                      <el-button style="position: absolute; right: 0; top: 3px" size="small" @click="gzloperat(index)"
                        type="primary" :icon="
                          index == maintaininfo.ext1.task.gd.length - 1 ? Plus : Minus
                        "></el-button>
                    </el-col>
                  </el-row>
                </el-col>

                <el-col :span="24">
                  <div style="font-weight: bold; font-size: 15px">
                    合计：{{
                        evilFn(
                          maintaininfo.ext1.task.gd
                            .map((i) => {
                              var p = 0;
                              try {
                                p = parseFloat(i.yh_length);
                              } catch (e) {
                                p = 0;
                              }
                              return p == "" || isNaN(p) ? 0 : p;
                            })
                            .join("+")
                        )
                    }}
                    米
                  </div>
                </el-col>
              </el-row>
            </el-col>
          </el-row>

          <el-row style="margin-top: 10px">
            <el-col :span="12" style="text-align: right">
              <el-form-item :label="`计划开始时间`">
                <el-date-picker v-model="maintaininfo.ext1.task.datestart" value-format="YYYY-MM" type="month"
                  placeholder="请选择" />
              </el-form-item>
            </el-col>
            <el-col :span="12" style="text-align: right">
              <el-form-item :label="`计划结束时间`">
                <el-date-picker v-model="maintaininfo.ext1.task.dateend" value-format="YYYY-MM" type="month"
                  placeholder="请选择" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showadd = false">取消</el-button>
          <el-button type="primary" @click="onadd">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { defineComponent, ref, reactive, onMounted, computed, watch } from "vue";
import { useDict } from "@/utils/dict";
import router from "../../../router";
// 分页组件
import Pagination from "@/components/Pagination";
import { listFacilities } from "@/api/system/facilities";
import { listMaintain, addMaintain } from "@/api/system/maintain";
import { cloneDeep } from "lodash";
import { listDept, getDept } from "@/api/system/dept";
import { treeselect as deptTreeselect } from "@/api/system/dept";
import { ElMessage } from "element-plus";
import { onBeforeRouteLeave, useRoute } from "vue-router";
import { delMaintain, getMaintain, updateMaintain } from "../../../api/system/maintain";
import {
  Delete,
  Edit,
  Search,
  Share,
  Upload,
  Plus,
  Minus,
} from "@element-plus/icons-vue";
import { isNumber } from "@vueuse/shared";

const { maintain_status, maintain_type } = useDict("maintain_status", "maintain_type");
const queryparameters = ref({
  status: "",
  maintainType: "",
  facilitiesId: "",
  taskDeptRange: [],
  searchkey: "",
  pageNum: 1,
  pageSize: 10,
});
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 showadd = ref(false);
const loading = ref(false);
const tableData = ref([]);
const pagedata = ref({});
const route = useRoute();
const currentstatus = computed(() => route.params.status);
const alldevices = ref([]);
const maintaininfo = ref();
const alldept = ref([]);
const qdate = ref([]);
const treedept = ref([]);


const resetall = () => {
  queryparameters.value = {
    status: "",
    maintainType: "",
    facilitiesId: "",
    taskDeptRange: [],
    searchkey: "",
    pageNum: 1,
    pageSize: 10,
  };
}

const initadd = () => {
  maintaininfo.value = {
    ext1: {
      facilities_name: "",
      facilities_road: "",
      facilities_length: "",
      facilities_gjfw: "",
      facilities_start: "",
      facilities_end: "",
      facilities_unit: "",
      task: {
        jcj: "",
        ysk: "",
        phk: "",
        bz_dan: "",
        bz_shuang: "",
        bz_san: "",
        bz_si: "",
        bz_duo: "",
        gd: [
          {
            yh_length: "",
            yh_gj: "",
            yh_remark: "",
          },
        ],
        datestart: "",
        dateend: "",
      },
    },
    facilitiesId: null,
    maintainRemark: "",
    maintainType: "",
    id: null,
    status: 1,
  };
  proxy.resetForm("form");
};

const addmaintain = () => {
  initadd();

  showadd.value = true;
};
const getyears = () => {
  var years = [];
  for (var i = 0; i <= 100; i++) {
    years.push((2019 + i).toString());
  }
  return years;
};
const getmonth = () => {
  var months = [];
  for (var i = 0; i < 12; i++) {
    if (i < 9) {
      months.push("0" + (1 + i).toString());
    } else {
      months.push((1 + i).toString());
    }
  }
  return months;
};

const tblrowclick = (row) => {
  // console.log(row)
  router.push(`/maintain/detail/${row.id}`);
};

const onadd = () => {
  // Element.loading();
  loading.value = true;
  if (maintaininfo.value.id == null) {
    var ddf = cloneDeep(maintaininfo.value);
    ddf.ext1 = JSON.stringify(ddf.ext1);
    addMaintain(ddf).then((res) => {
      loading.value = false;
      showadd.value = false;
      getList();
    });
  } else {
    var ddf = cloneDeep(maintaininfo.value);
    ddf.ext1 = JSON.stringify(ddf.ext1);
    updateMaintain(ddf).then((res) => {
      loading.value = false;
      showadd.value = false;
      getList();
    });
  }
};

const getList = () => {
  if (currentstatus.value != 1) {
    if (currentstatus.value == 2) {
      queryparameters.value.status = 1;
    } else {
      queryparameters.value.status = currentstatus.value;
    }
  } else {
    queryparameters.value.status = "";
  }
  var cq = cloneDeep(queryparameters.value);
  var query = proxy.addDateRange(cq, qdate.value);
  if (query.status == "0") {
    delete query.status;
  }
  if (query.searchkey != undefined && query.searchkey !== "") {
    query.params["searchkey"] = query.searchkey;
  }
  if (query.taskDeptRange != undefined) {
    query.taskDeptRange = query.taskDeptRange.join(",");
  }

  listMaintain(query).then((response) => {
    tableData.value = response.rows.map((i) => {
      i.ext1 = JSON.parse(i.ext1);
      return i;
    });
    pagedata.value = response;
  });
};

const edittask = (row) => {
  initadd();
  const id = row.id || ids.value;
  getMaintain(id).then((res) => {
    maintaininfo.value = res.data;
    maintaininfo.value.ext1 = JSON.parse(maintaininfo.value.ext1);
    showadd.value = true;
    // title.value = "修改设施";
  });
};
const deltask = (row) => {
  delMaintain(row.id).then((res) => {
    ElMessage.success("删除成功");
    getList();
  });
};
const gzloperat = (index) => {
  if (maintaininfo.value.ext1.task.gd.length - 1 == index) {
    //add
    maintaininfo.value.ext1.task.gd.push({
      yh_length: "",
      yh_gj: "",
      yh_remark: "",
    });
  } else {
    //sub
    maintaininfo.value.ext1.task.gd.splice(index, 1);
  }
};

const evilFn = (fn) => {
  console.log(fn);
  let Fn = Function; // 一个变量指向Function，防止有些前端编译工具报错
  return new Fn(`return ${fn}`)();
};

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

onMounted(() => { });

{
  listFacilities().then((res) => {
    alldevices.value = res.rows.map((i) => {
      i.ext1 = JSON.parse(i.ext1);
      return i;
    });
  });
  initadd();
  getList();

  listDept().then((response) => {
    alldept.value = cloneDeep(response.data);
  });
  deptTreeselect().then((res) => {
    treedept.value = [setdatakey(res.data[0].children.filter(i => i.id == 202))[0]];
  });

  watch(
    () => maintaininfo.value.facilitiesId,
    () => {
      if (maintaininfo.value.facilitiesId != null) {
        var fd = alldevices.value.filter(
          (i) => i.id + "" == maintaininfo.value.facilitiesId + ""
        )[0];
        maintaininfo.value.ext1["facilities_name"] = fd.ext1.tz_ss_name;
        maintaininfo.value.ext1["facilities_road"] = fd.ext1.tz_ss_road;
        maintaininfo.value.ext1["facilities_length"] = fd.ext1.tz_ss_data_length;
        maintaininfo.value.ext1["facilities_gjfw"] = fd.ext1.tz_ss_dn;
        maintaininfo.value.ext1["facilities_start"] = fd.ext1.tz_ss_road_start;
        maintaininfo.value.ext1["facilities_end"] = fd.ext1.tz_ss_road_end;
        maintaininfo.value.ext1["facilities_unit"] = fd.ext1.tz_ss_unit;
        maintaininfo.value.ext1["task"]["jcj"] = fd.ext1.tz_ss_data_jing;
        maintaininfo.value.ext1["task"]["ysk"] = fd.ext1.tz_ss_data_ysk;
        maintaininfo.value.ext1["task"]["phk"] = fd.ext1.tz_pfk;
        maintaininfo.value.ext1["task"]["bz_dan"] = fd.ext1.tz_bz_dan;
        maintaininfo.value.ext1["task"]["bz_shuang"] = fd.ext1.tz_bz_shuang;
        maintaininfo.value.ext1["task"]["bz_san"] = fd.ext1.tz_bz_san;
        maintaininfo.value.ext1["task"]["bz_si"] = fd.ext1.tz_bz_si;
        maintaininfo.value.ext1["task"]["bz_duo"] = fd.ext1.tz_bz_duo;
      }
    }
  );
}

onBeforeRouteLeave((to, from, next) => {
  to.meta.activeMenu = from.path;
  console.log(to);
  next()
})


</script>

<style lang="scss" scoped>
.formbody {
  background: #fff;
  width: 100%;
  border-radius: 5px;
  min-height: 80vh;
  padding: 15px 10px;

  .eltable {
    border: 1px solid #e5e9f2;
    border-radius: 5px;
  }
}

.el-select {
  width: 100%;
}
</style>

<style>
.el-table__row:hover {
  cursor: pointer;
}
</style>
