<!-- 巡查计划管理-水闸 -->
<script>

import {
  delRunSzYhPlan,
  postRunSzYhPlanList,
  postRunSzYhPlanApproval,
  postRunSzYhPlanApprovalReturn
} from "@/api/sluice";

import TopBackTitle from "@/components/TopBackTitle/index.vue";
import PlanDetail from "./components/PlanDetail.vue";
import { getAreasData } from "@/api/areas/index";

import { reqCountMixins } from "@/mixins/reqCount";
import { paginationMixins } from "@/mixins/commonPagination";

export default {
  name: "InspectionItems",
  components: {
    TopBackTitle,
    PlanDetail,
  },
  mixins: [reqCountMixins, paginationMixins],
  data() {
    return {
      paramsData: {
        adcd: "",
        wagaName: "",
        wagaType: "",
        name: "",
        planDateArr: [],
      },
      choiceDate: '',
      pickerOption: { // 设置不能选择的日期
        onPick: ({ maxDate, minDate }) => {
          this.choiceDate = minDate.getTime()
          if (maxDate) {
            this.choiceDate = '';
          }
        },
        disabledDate: (time) => {//只能选择5年数据
          let curDate = (new Date()).getTime();
          let three = 5 * 12 * 30 * 24 * 3600 * 1000;
          let min = curDate + three;
          let max = curDate - three;
          if (this.choiceDate) {
            return time.getTime() < max || time.getTime() > min;
          } else {
            return false;
          }
        }
      },
      currentRow: {},
      dialogVisible: false,
      areasOptions: [], // 行政区划列表
      embankmentTypeOptions: [], // 水闸类型列表
      supplementOptions: [], // 资金来源列表
      tableData: [], // 表格列表
      tableCheckData: [], // 选中的数据
    };
  },
  methods: {
    // 新增
    handleAdd() {
      this.$router.push({
        path: "createMaintenancePlan",
        query: {
          type: 'plan',
        },
      });
    },
    // 获取行政区数据
    getTreeData() {
      getAreasData().then((items) => {
        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);
        this.areasOptions = res;
      });
    },
    // 查看维养计划
    handleCheck(row) {
      this.currentRow = row;
      this.dialogVisible = true;
    },
    // 提交审批
    handleSubmit(row) {
      postRunSzYhPlanApproval({
        formId: row.id
      }).then(() => {
        this.$alert('提交审批成功，请耐心等候', '提醒', {
          showConfirmButton: false,
          type: 'success'
        })
        this.getTableData();
      })
    },
    // 撤回
    handleReturn(row) {
      postRunSzYhPlanApprovalReturn({
        formId: row.id
      }).then(() => {
        this.$alert('撤回审批成功，请耐心等候', '提醒', {
          showConfirmButton: false,
          type: 'success'
        })
        this.getTableData();
      })
    },
    // 编辑巡查项目
    handleEdit(row) {
      this.$router.push({
        path: "createMaintenancePlan",
        query: {
          id: row.id,
          type: 'plan',
        },
      });
    },
    // 删除对应巡查项目
    deleteTableItem(row) {
      delRunSzYhPlan({id: row.id}).then((res) => {
        this.getTableData();
        this.$message.success("删除成功");
      });
    },
    // 获取数据
    getTableData() {
      postRunSzYhPlanList({
        data: {
          adcd: this.paramsData.adcd,
          name: this.paramsData.name,
          startDate: this.paramsData.planDateArr[0]
            ? this.paramsData.planDateArr[0] + " 00:00:00"
            : null,
          endDate: this.paramsData.planDateArr[1]
            ? this.paramsData.planDateArr[1] + " 23:59:59"
            : null,
          wagaName: this.paramsData.wagaName,
          wagaType: this.paramsData.wagaType,
        },
        pageSize: this.pageData.pageSize,
        pageNum: this.pageData.pageNum,
      }).then((res) => {
        if (res) {
          this.tableData = res.records;
          this.pageData.total = res.total;
        }
      });
    },
    // 批量删除
    handleDelAll() {
      if (this.tableCheckData.length === 0) {
        this.$message.warning("请选择要删除的数据");
        return;
      }
      let isstatus = false;
      this.tableCheckData.forEach((item) => {
        if (item.status != 0) {
          isstatus = true;
          this.$message.warning("不能删除已审批的数据");
        }
      });
      if (isstatus) return;
      this.$confirm("是否删除选中的记录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log("删除");
          const ids = this.tableCheckData.map((item) => item.id);
          delRunSzYhPlan({id: ids.join(",")}).then((res) => {
            if (res) {
              this.$message.success("删除成功");
              this.getTableData();
            }
          });
        })
        .catch(() => {
          console.log("取消删除");
        });
    },
    // 表格列表多选
    handleSelectionChange(e) {
      console.log(e)
      this.tableCheckData = e || [];
    },
    // 搜索
    handleChangeQuery() {
      this.reqCountCalc();
      this.pageData.pageNum = 1;
      this.getTableData();
    },
    // 重置
    handleResetQuery() {
      this.paramsData.adcd = "";
      this.paramsData.name = "";
      this.paramsData.planDateArr = [];
      this.paramsData.wagaName = "";
      this.paramsData.wagaType = "";

      this.reqCountCalc();
      this.pageData.pageNum = 1;
      this.getTableData();
    },
    // 过滤提防类型
    getwagaTypeName(type) {
      let name = "";
      this.embankmentTypeOptions?.forEach((element) => {
        if (element.dictValue == type) {
          name = element.dictLabel;
        }
      });
      return name || type;
    },
    // 过滤资金来源
    getSupplementName(supplements) {
      let name = "";
      supplements.forEach((supplement) => {
        const dict = this.supplementOptions?.find((element) => {
          return element.dictValue == supplement.type
        })
        let subName = `${dict.dictLabel}/${supplement.amount.replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`
        name = name + ' ' + subName
      })
      return name;
    },
  },
  created() {
    this.getTreeData();
    this.getDicts("sluice_type").then((response) => {
      this.embankmentTypeOptions = response.data;
    });

    this.getDicts("xs_yh_supplement").then((response) => {
      this.supplementOptions = response.data;
    });
  },
  mounted() {
    // 获取列表数据
    this.getTableData();
  },
};
</script>

<template>
  <div class="slider-right">
    <TopBackTitle :showBackBtn="false"></TopBackTitle>
    <div class="table-box slider-right-body">
      <div class="search-form flex flex-wrap">
        <div class="search-item flex items-center">
          <span class="search-label">行政区划</span>
          <el-cascader
            :options="areasOptions"
            v-model="paramsData.adcd"
            :props="{
              emitPath: false,
              checkStrictly: true,
            }"
            placeholder="请选择行政区划"
            clearable
            size="small"
            class="w-202 ml-10"
          >
          </el-cascader>
        </div>
        <div class="search-item flex items-center">
          <span class="search-label">水闸名称</span>
          <el-input
            clearable
            size="small"
            class="w-202 ml-10"
            :maxlength="50"
            v-model="paramsData.wagaName"
            placeholder="请输入名称"
          />
        </div>
        <div class="search-item flex items-center">
          <span class="search-label">水闸类型</span>
          <el-select
            clearable
            size="small"
            class="w-202 ml-10"
            v-model="paramsData.wagaType"
            :popper-append-to-body="false"
            filterable
            placeholder="请选择"
          >
            <el-option label="全部" value=""> </el-option>
            <el-option
              :label="item.dictLabel"
              :value="item.dictValue"
              v-for="(item, index) in embankmentTypeOptions"
              :key="index"
            ></el-option>
          </el-select>
        </div>
        <div class="search-item flex items-center">
          <span class="search-label">维养计划名称</span>
          <el-input
            clearable
            size="small"
            class="w-202 ml-10"
            :maxlength="50"
            v-model="paramsData.name"
            placeholder="请输入名称"
          />
        </div>
        <div class="search-item flex items-center">
          <span class="search-label">维养计划日期</span>
          <el-date-picker
            clearable
            size="small"
            class="ml-10"
            v-model="paramsData.planDateArr"
            :picker-options="pickerOption"
            type="daterange"
            placeholder="开始日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </div>
        <div class="flex-1 flex justify-end search-item">
          <el-button
            size="small"
            class="flex-shrink-0 myml-12"
            type="success"
            @click="handleChangeQuery"
            >查询</el-button
          >
          <el-button
            class="flex-shrink-0"
            size="small"
            @click="handleResetQuery"
            >重置</el-button
          >
        </div>
      </div>
      <div class="line"></div>
      <div class="flex justify-end mb-16">
        <div>
          <el-button type="primary" size="small" @click="handleAdd"
                     v-hasPermi="['sz:run:inspection:plan:add']"
            >新增</el-button
          >
          <el-button
            type="danger"
            size="small"
            @click="handleDelAll"
            :disabled="tableCheckData.length === 0"
            v-hasPermi="['sz:run:inspection:plan:delAll']"
            >删除</el-button
          >
        </div>
      </div>

      <el-table
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="wagaName" align="center" label="水闸名称" />
        <el-table-column prop="wagaType" align="center" label="水闸类型">
          <template slot-scope="scope">
            <span>{{ getwagaTypeName(scope.row.wagaType) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" align="center" label="维养计划名称" />
        <el-table-column prop="startDate" align="center" label="计划开始时间">
        </el-table-column>
        <el-table-column prop="endDate" align="center" label="计划结束时间">
        </el-table-column>
        <el-table-column prop="supplements" align="center" label="资金来源/万元" >
          <template slot-scope="scope">
            <span>{{ getSupplementName(scope.row.supplements) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          align="center"
          sortable
          label="创建时间"
        />
        <el-table-column prop="createTime" align="center" sortable label="状态">
          <template slot-scope="scope">
            <span
              v-if="scope.row.status == 0"
              style="color: #f56c6c; font-weight: 600"
              >待提交</span
            >
            <span
              v-else-if="scope.row.status == 1"
              style="color: #67c23a; font-weight: 600"
              >审批中</span
            >
            <span
              v-else-if="scope.row.status == 2"
              style="color: #67c23a; font-weight: 600"
              >已通过</span
            >
            <span
              v-else-if="scope.row.status == 3"
              style="color: #f56c6c; font-weight: 600"
              >已驳回</span
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="operate"
          align="center"
          label="操作"
          fixed="right"
          width="160"
        >
          <template slot-scope="scope">
            <el-button
              style="margin-right: 16px; margin-left: 10px;"
              type="text"
              size="small"
              @click="handleCheck(scope.row)"
              v-hasPermi="['sz:run:inspection:plan:item:check']"
              >查看</el-button
            >
            <el-button
              style="margin-right: 16px"
              v-if="scope.row.status == 0 || scope.row.status == 3"
              v-hasPermi="['sz:run:inspection:plan:item:submit']"
              type="text"
              size="small"
              @click="handleSubmit(scope.row)"
              >提交审批</el-button
            >
            <el-button
              style="color: red; margin-right: 16px"
              v-if="scope.row.status == 1"
              v-hasPermi="['sz:run:inspection:plan:item:return']"
              type="text"
              size="small"
              @click="handleReturn(scope.row)"
              >撤回</el-button
            >
            <el-button
              style="margin-right: 16px"
              v-if="scope.row.status == 0 || scope.row.status == 3"
              @click="handleEdit(scope.row)"
              type="text"
              size="small"
              v-hasPermi="['sz:run:inspection:plan:item:edit']"
              >编辑</el-button
            >
            <el-popconfirm
              v-if="scope.row.status == 0"
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="确定删除吗？"
              @confirm="deleteTableItem(scope.row)"
            >
              <el-button
                style="color: red; margin-right: 16px; margin-left: 10px;"
                type="text"
                size="small"
                slot="reference"
                v-hasPermi="['sz:run:inspection:plan:item:del']"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        class="pagination"
        style="margin-top: 16px; margin-right: 16px; float: right"
        :current-page="pageData.pageNum"
        :page-sizes="pageData.pageSizes"
        layout="total, prev, pager, next, sizes, jumper"
        :total="pageData.total"
        @size-change="(e) => handlePageSizeChange(e)"
        @current-change="(e) => handleCurrentPageChange(e)"
      >
      </el-pagination>
    </div>
    <el-drawer
      title="计划详情"
      :visible.sync="dialogVisible"
      direction="rtl"
      size="80%"
      :destroy-on-close="true"
    >
      <div class="drawer-body">
         <PlanDetail
          ref="formRef"
          :id="currentRow.id"
          :canEdit="false"
        ></PlanDetail>
      </div>
      <div class="drawer-footer p-16">
<!--        <el-button size="mini" type="primary" @click="handleEdit(currentRow)"
                   v-hasPermi="['sz:run:inspection:plan:item:edit']"
          >编辑</el-button
        >-->
        <el-button size="mini" @click="dialogVisible = false">取消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<style scoped lang="less">
.search-form {
  .search-item {
    margin-bottom: 16px;
    .search-label {
      width: 100px;
      text-align: right;
      flex-shrink: 0;
    }
  }
}
.line {
  background: #e5e5e5;
  width: 100%;
  height: 1px;
  margin-top: 8px;
  margin-bottom: 24px;
}

.table-box {
  // height: calc(100% - 50px - 24px);
  margin-top: 24px;
  padding: 16px;
  padding-bottom: 60px;
  background-color: white;
}

.drawer-footer {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  z-index: 2;
  border-top: 1px solid #ebeef5;
  background: #fff;
}

.drawer-body {
  height: 100%;
  padding: 0 16px;
  padding-bottom: 72px;
  overflow: auto;
}
</style>
