<template>
  <div class="app-container">
    <el-form :inline="true" :model="queryParams" class="demo-form-inline">
      <el-form-item :label="$t('area_management.StartDate')">
        <el-date-picker
          v-model="queryParams.createTime"
          type="date"
          :placeholder="
            $t('share.PleaseChoose') + $t('area_management.StartDate')
          "
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('area_management.EndDate')">
        <el-date-picker
          v-model="queryParams.startTime"
          type="date"
          :placeholder="
            $t('share.PleaseChoose') + $t('area_management.EndDate')
          "
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">{{
          $t("share.search")
        }}</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">{{
          $t("share.reset")
        }}</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" @click="add">{{
          $t("share.new")
        }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :disabled="ids.length <= 0"
          @click="issueFn"
          >{{ $t("area_management.RegionalDistribution") }}</el-button
        >
      </el-col>
    </el-row>
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 10px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        :label="$t('area_management.index')"
        type="index"
        align="center"
        width="55"
      />
      <el-table-column
        prop="configCode"
        :label="$t('area_management.MaintenanceAreaConfigurationCode')"
        align="center"
      />
      <el-table-column
        prop="createTime"
        :label="$t('area_management.TheMaintenanceTimelineBegins')"
        align="center"
      />
      <el-table-column
        prop="endTime"
        :label="$t('area_management.EndOfMaintenanceTimeNode')"
        align="center"
      />
      <el-table-column
        prop="enable"
        :label="$t('area_management.ValidOrNot')"
        align="center"
      >
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.enable == 1">有效</el-tag>
          <el-tag type="info" v-if="scope.row.enable == 0">无效</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          >
            <!-- {{ $t("area_management.loseEfficacy") }} -->
            {{ scope.row.enable == 1 ? "无效" : "有效" }}
          </el-button>
          <el-button
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row.lineId)"
          >
            {{ $t("share.delete") }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
    />
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose"
    >
      <el-row :gutter="10">
        <el-col :span="9">
          <el-input></el-input>
          <el-tree
            :props="defaultProps"
            :data="treeData"
            node-key="id"
            :render-content="renderContent"
            @check-change="handleCheckChange"
            ref="tree"
          >
          </el-tree>
        </el-col>
        <el-col :span="15">
          <el-form
            :model="dialogForm"
            label-width="160px"
            :rules="rules"
            ref="form"
          >
            <el-form-item
              :label="$t('area_management.type')"
              prop="deviceLevel"
            >
              <el-select
                v-model="dialogForm.deviceLevel"
                :placeholder="
                  $t('share.PleaseChoose') + $t('area_management.type')
                "
                @change="deviceLevelChange"
              >
                <el-option label="区域" value="area"></el-option>
                <el-option label="主设备" value="main"></el-option>
                <el-option label="部件" value="part"></el-option>
                <el-option label="点位" value="point"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              :label="$t('area_management.MaintenanceAreaConfigurationCode')"
              prop="configCode"
            >
              <el-input
                v-model="dialogForm.configCode"
                :placeholder="
                  $t('share.PleaseEnter') +
                  $t('area_management.MaintenanceAreaConfigurationCode')
                "
              ></el-input>
            </el-form-item>
            <el-form-item
              :label="$t('area_management.TimeAndDate')"
              prop="dateRange"
            >
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="-"
                :start-placeholder="$t('area_management.StartDate')"
                :end-placeholder="$t('area_management.EndDate')"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <div style="text-align: center">
                <el-button type="primary" @click="submitForm">{{
                  $t("share.confirm")
                }}</el-button>
                <el-button @click="handleClose">{{
                  $t("share.cancel")
                }}</el-button>
              </div>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {
  getList,
  treeAreaDeviceSelectAgain,
  postRemove,
  postAdd,
  edit,
  issue,
} from "@/api/area/area_management";
export default {
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 4,
      tableData: [],
      title: this.$t("area_management.AddMaintenancePlan"),
      dialogVisible: false,
      treeData: [],
      defaultProps: {
        children: "children",
        label: "label",
        isLeaf: "leaf", // 标识节点是否为叶子节点
      },
      dialogForm: {
        deviceLevel: "area",
      },
      dateRange: [],
      ids: [],
      rules: {
        deviceLevel: [
          {
            required: true,
            message: "请选择设备类型",
            trigger: "change",
          },
        ],
        configCode: [
          {
            required: true,
            message: "请输入检修区域配置编码",
            trigger: "blur",
          },
        ],
        // dateRange: [
        //   {
        //     required: true,
        //     message: "请选择时间",
        //     trigger: "change",
        //   },
        // ],
      },
    };
  },

  created() {
    this.init();
    this.initTree();
  },
  mounted() {},
  methods: {
    submitForm() {
      this.dialogForm.startTime = this.dateRange[0];
      this.dialogForm.endTime = this.dateRange[1];
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // return
          postAdd(this.dialogForm).then((res) => {
            if (res.code == 200) {
              this.dialogVisible = false;
              this.$message({
                message: `新增成功`,
                type: "success",
              });
              this.init();
            }
          });
        }
      });
    },
    // 初始化
    init() {
      getList(this.queryParams).then((res) => {
        if (res.code == 200) {
          this.tableData = res.rows;
          this.total = res.total;
          this.$message({
            message: `查询成功`,
            type: "success",
          });
        }
      });
    },
    initTree() {
      treeAreaDeviceSelectAgain().then((res) => {
        if (res.code == 200) {
          this.treeData = res.data;
          // this.treeData=this.flattenTree(res.data)
          console.log(this.treeData, 1111111111);
        }
      });
    },
    // 查询
    handleQuery() {
      console.log(this.queryParams);
      this.init();
    },
    // 重置
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.init();
    },
    add() {
      this.dialogVisible = true;
    },
    handleClose() {
      this.dialogVisible = false;
      this.dialogForm.deviceLevel = "area";
      this.$refs.form.resetFields();
    },

    // 修改
    handleEdit(row) {
      // lineId
      let data = {
        lineId: row.lineId,
        enable: row.enable == 0 ? 1 : 0,
      };
      edit(data).then((res) => {
        if (res.code == 200) {
          this.init();
        }
      });
    },
    // 删除
    handleDelete(id) {
      this.$confirm(`确定要删除Id为${id}的数据吗？`, "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          postRemove(id).then((res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.init();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 树结构多选框处理
    renderContent(h, { node, data, store }) {
      const showCheckbox = data.type == this.dialogForm.deviceLevel;
      return h("span", [
        showCheckbox
          ? h("el-checkbox", {
              style: { marginRight: "8px" },
              on: {
                change: (checked) => {
                  store.setChecked(node, checked, false);
                },
              },
            })
          : null,
        h("span", node.label),
      ]);
    },
    handleCheckChange(data, checked, indeterminate) {
      this.dialogForm.deviceList = null;
      this.dialogForm.pointList = null;
      let deviceList = [];
      let pointList = [];
      let allCheckedNodes = this.$refs.tree.getCheckedNodes();

      allCheckedNodes.forEach((item) => {
        deviceList.push(item.id);
        if (item.children && item.children.length > 0) {
          item.children.forEach((child) => {
            pointList.push(child.id);
          });
        }
      });
      this.dialogForm.deviceList = deviceList.toString();
      this.dialogForm.pointList = pointList.toString();
      console.log(this.dialogForm);
      // console.log(this.dialogForm, allCheckedNodes);
    },
    deviceLevelChange() {
      this.dialogForm.deviceList = null;
      this.dialogForm.pointList = null;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.lineId);
    },
    issueFn() {
      issue(this.ids.toString()).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: `下发成功`,
            type: "success",
          });
          this.init();
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-date-editor {
  width: 100%;
}
::v-deep .el-select {
  width: 100%;
}
</style>
