<template>
  <div>
    <!-- 添加搜索区域 -->
    <div class="search-container">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入关键词进行搜索"
        prefix-icon="el-icon-search"
        clearable
        size="small"
        style="width: 300px; margin-bottom: 20px;"
        @input="handleSearch"
      ></el-input>
    </div>
    
    <!-- <h2 style="text-align: left">任务</h2>
    <h5 style="text-align: left">管理任务人员</h5> -->
    <el-table
      :data="filteredData"
      max-height="720px"
      style="width: 100%;"
      :header-cell-class-name="sinClo"
    >
      <el-table-column
        prop="taskName"
        label="任务名称"
        min-width="100"
        sortable
      ></el-table-column>
      <el-table-column min-width="110" filterable label="是否需要分配" sortable>
        <template slot="header" slot-scope="scope">
          <span>是否需要分配</span>
          <el-dropdown @command="handleFilter" style="margin-left: 5px;">
            <span class="el-dropdown-link">
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="all">全部</el-dropdown-item>
              <el-dropdown-item command="need">需要分配</el-dropdown-item>
              <el-dropdown-item command="notNeed">不需分配</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
        <template slot-scope="scope">
          <el-checkbox
            label="需要分配"
            v-model="scope.row.isAllocationOptional"
            @change="changeisAllocationOptional(scope.row.id)"
          ></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column min-width="95" filterable label="是否已分配" sortable>
        <template slot-scope="scope">
          <el-checkbox
            label="已分配"
            v-model="scope.row.allocated"
            disabled
          ></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        class-name="comClo"
        label="自动分配"
      >
        <el-table-column min-width="120" label="工作区域">
          <template slot-scope="scope">
            <el-upload
              accept=".shp"
              class="upload-demo"
              action="shp"
              :auto-upload="false"
              :limit="1"
              :before-upload="beforeAvatarUpload"
              :on-change="
                (file, fileList) => {
                  getFile(file, fileList, scope.row.id);
                }
              "
              :on-remove="
                (file, fileList) => {
                  removeFile(file, fileList, scope.row.id);
                }
              "
            >
              <el-button
                size="small"
                type="primary"
                plain
                :disabled="!scope.row.isAllocationOptional"
                >上传shp数据</el-button
              >
            </el-upload>
          </template>
        </el-table-column>
        <el-table-column min-width="120" filterable label="任务人员">
          <template slot-scope="scope">
            <el-button
              type="primary"
              plain
              size="small"
              @click.native="selectWorkers(scope.row.id)"
              :disabled="!scope.row.isAllocationOptional"
              >选择任务人员</el-button
            >
          </template>
        </el-table-column>
        <el-table-column min-width="100" label="划分等级">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.precision"
              size="small"
              placeholder="请选择"
              :disabled="!scope.row.isAllocationOptional"
            >
              <el-option
                v-for="item in precisionOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column min-width="100" label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="small"
              @click.native="submitUploadShp(scope.row.id)"
              :disabled="!scope.row.isAllocationOptional"
              >自动分配</el-button
            >
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column min-width="100" label="手动分配">
        <template slot-scope="scope">
          <el-button
            type="primary"
            style="margin-left: 10px !important"
            size="small"
            @click.native="manualAllocate(scope.row.id, false)"
            :disabled="!scope.row.isAllocationOptional"
            >手动分配</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-dialogDrag
      class="taskDialog"
      title="选择任务人员"
      :visible.sync="WorkersVisible"
      :close-on-click-modal="false"
      style="position: absolute !important"
    >
      <el-table
        :data="workers"
        :height="400"
        stripe
        highlight-current-row
        class="tb-edit"
        style="width: 100%"
      >
        <el-table-column type="index" min-width="40"></el-table-column>
        <el-table-column prop="username" label="工作人员" min-width="100">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.username"
              filterable
              placeholder="请选择"
              @focus="makeuername(scope.$index)"
              @change="makeId(scope.$index)"
            >
              <el-option
                v-for="item in selectworkersdata"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="工作角色" min-width="100">
          <template slot-scope="scope">
            <el-select v-model="scope.row.role" placeholder="请选择">
              <el-option
                v-for="item in roleOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column fixed="right" min-width="80">
          <template slot="header">
            <el-button @click="addWorker()" type="primary" class="allomapBtn"
              >添加人员</el-button
            >
          </template>
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="deleteWorker(scope.$index)"
              type="text"
              size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="UploadWorkers()" class="allomapBtn"
        >确认</el-button
      >
    </el-dialog>
  </div>
</template>
<script>
import { ajax as request } from "@/request.js";
import axios from "axios";
export default {
  data() {
    return {
      WorkersVisible: false,
      DialogVisible: false,
      workersIndex: -1,
      tasksData: [],
      filteredData: [], // 过滤后的数据
      currentFilter: 'all', // 当前筛选状态
      workers: [],
      selectworkersdata: [],
      options: [],
      roleOptions: [
        {
          value: "0",
          label: "采集人员",
        },
        {
          value: "1",
          label: "巡查人员",
        },
      ],
      precisionOptions: [
        {
          value: "0",
          label: "默认",
        },
        {
          value: "1",
          label: "1(2500km)",
        },
        {
          value: "2",
          label: "2(630km)",
        },
        {
          value: "3",
          label: "3(78km)",
        },
        {
          value: "4",
          label: "4(20km)",
        },
        {
          value: "5",
          label: "5(2.4km)",
        },
        {
          value: "6",
          label: "6(610m)",
        },
        {
          value: "7",
          label: "7(76m)",
        },
        {
          value: "8",
          label: "8(19.11m)",
        },
        {
          value: "9",
          label: "9(4.78m)",
        },
        {
          value: "10",
          label: "10(0.5971m)",
        },
        {
          value: "11",
          label: "11(0.1492m)",
        },
        {
          value: "12",
          label: "12(0.0186m)",
        },
      ],
      searchKeyword: "", // 搜索关键词
    };
  },
  methods: {
    // 搜索处理方法
    handleSearch() {
      this.applyFilter();
    },

    // 应用筛选和搜索
    applyFilter() {
      let filtered = [...this.tasksData];
      
      // 先应用分配状态筛选
      if (this.currentFilter === 'need') {
        filtered = filtered.filter(item => item.isAllocationOptional === true);
      } else if (this.currentFilter === 'notNeed') {
        filtered = filtered.filter(item => item.isAllocationOptional === false);
      }
      
      // 再应用搜索关键词筛选
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase();
        filtered = filtered.filter(item => {
          return item.taskName && item.taskName.toLowerCase().includes(keyword);
        });
      }
      
      this.filteredData = filtered;
    },

    // 筛选处理方法
    handleFilter(command) {
      this.currentFilter = command;
      this.applyFilter();
    },

    // 修改方法参数，从index改为taskId
    changeisAllocationOptional(taskId) {
      let row = this.tasksData.find(item => item.id === taskId);
      if (!row) return;
      
      let that = this;
      let str = row.isAllocationOptional === true
        ? "确认任务需要分配吗？"
        : "确认任务无需分配吗？";
      let res = row.isAllocationOptional === true ? 0 : 1;

      this.$confirm(str, "提示", {})
        .then(() => {
          request({
            url: "/allocation/optional",
            method: "get",
            params: {
              taskId: taskId,
              optional: res,
            },
          }).then(function (response) {
            if (response.data.success == true) {
              that.$message.success("设置成功");
              
              // 重新获取数据以确保状态同步
              that.init();
            } else if (response.data.status == "401") {
              that.$alert(response.data.message);
              that.$router.push({ path: "/login" });
            } else {
              that.$message.error("设置失败");
            }
          });
        })
        .catch(() => {
          // 取消操作，不需要回滚状态
        });
    },
    init() {
      let that = this;
      // 请求任务列表
      request({
        url: "/task/selectTaskHasCreated",
        method: "get",
      }).then(function (response) {
        if (response.data.success == true) {
          var jsondata = JSON.parse(response.data.data);
          that.tasksData = jsondata.data;
          //0表示需要分配
          for (var i = 0; i < that.tasksData.length; i++) {
            if (that.tasksData[i].isAllocationOptional == 0) {
              that.tasksData[i].isAllocationOptional = true;
            } else {
              that.tasksData[i].isAllocationOptional = false;
            }
            if (that.tasksData[i].allocated == "true") {
              that.tasksData[i].allocated = true;
            } else {
              that.tasksData[i].allocated = false;
            }
          }
          // 应用当前筛选和搜索
          that.applyFilter();
        } else if (response.data.status == "401") {
          that.$alert(response.data.message);
          that.$router.push({ path: "/login" });
        }
      });
      request({
        url: "/user/all_worker",
        method: "get",
      }).then(function (response) {
        if (response.data.success == true) {
          var worksdata = response.data.data;
          that.options = [];
          for (var i = 0; i < worksdata.length; i++) {
            that.options.push({
              value: worksdata[i].id,
              label: worksdata[i].username,
            });
          }
        } else if (response.data.status == "401") {
          that.$alert(response.data.message);
          that.$router.push({ path: "/login" });
        }
      });
    },
    // onchange文件改变时的钩子 可以通过参数file找到文件 filr.raw获取文件流
    getFile(file, fileList, taskId) {
      let row = this.tasksData.find(item => item.id === taskId);
      if (!row) return;
      
      let fileList1 = [];
      fileList1.push(file.raw);
      row.fileList = fileList1;
    },
    submitUploadShp(taskId) {
      let row = this.tasksData.find(item => item.id === taskId);
      if (!row) return;
      
      if (row.allocated) {
        let that = this;
        this.$confirm("任务已经完成自动分配，是否重新分配？", "提示", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning",
        })
          .then(() => {
            that.AutoTask(taskId);
          })
          .catch(() => {});
      } else {
        this.AutoTask(taskId);
      }
    },
    AutoTask(taskId) {
      let row = this.tasksData.find(item => item.id === taskId);
      if (!row) return;
      
      let that = this;
      let fd = new FormData();
      if (row.fileList && row.fileList[0]) {
        fd.append("shp", row.fileList[0]);
      } else {
        that.$alert("请上传shp文件！", "提示", { confirmButtonText: "确定" });
        return;
      }
      if (!row.workers) {
        that.$alert("请选择任务人员！", "提示", { confirmButtonText: "确定" });
        return;
      }
      fd.append("taskId", taskId);
      fd.append("workers", JSON.stringify(row.workers));
      if (row.precision) {
        fd.append("precision", row.precision);
      }
      axios({
        url: "/allocation/assignment",
        method: "post",
        data: fd,
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }).then(function (response) {
        if (response.data.success == true) {
          that.$notify.success({
            title: "提示",
            message: "自动分配完成！",
          });
          that.manualAllocate(taskId, true);
        } else if (response.data.status == "401") {
          that.$alert(response.data.message);
          that.$router.push({ path: "/login" });
        } else {
          that.$notify.error({
            title: "提示",
            message: response.data.message,
          });
        }
      });
    },
    beforeAvatarUpload(file) {
      if (file.type != "shp") {
        this.$message.error("只能上传shp格式数据!");
        return false;
      }
      return true;
    },
    selectWorkers(taskId) {
      let row = this.tasksData.find(item => item.id === taskId);
      if (!row) return;
      
      this.workersIndex = taskId; // 存储任务ID而不是索引
      if (row.workers) {
        this.workers = row.workers;
      } else {
        this.workers = [];
      }
      this.WorkersVisible = true;
    },
    addWorker() {
      let row = this.tasksData.find(item => item.id === this.workersIndex);
      if (!row) return;
      
      if (row.taskType === "0") {
        this.workers.push({
          username: "",
          role: "0",
        });
      } else {
        this.workers.push({
          username: "",
          role: "1",
        });
      }
    },
    removeFile(file, fileList, taskId) {
      let row = this.tasksData.find(item => item.id === taskId);
      if (!row) return;
      
      row.fileList = [];
    },
    deleteWorker(index) {
      this.workers.splice(index, 1);
    },
    UploadWorkers() {
      for (var i = 0; i < this.workers.length; i++) {
        if (this.workers[i].username == "") {
          this.$alert("任务人员不可为空！", "提示", {
            confirmButtonText: "确定",
          });
          return;
        }
      }
      let row = this.tasksData.find(item => item.id === this.workersIndex);
      if (row) {
        row.workers = this.workers;
      }
      this.WorkersVisible = false;
      //            this.$alert(this.tasksData[this.workersIndex].workers, '提示', {confirmButtonText: '确定'})
    },
    makeuername() {
      this.selectworkersdata = this.options.slice();
      for (var i = 0; i < this.workers.length; i++) {
        for (var j = 0; j < this.selectworkersdata.length; j++) {
          if (this.selectworkersdata[j].label == this.workers[i].username) {
            this.selectworkersdata.splice(j, 1);
          }
        }
      }
    },
    makeId(index) {
      for (var j = 0; j < this.options.length; j++) {
        if (this.options[j].label == this.workers[index].username) {
          this.workers[index].id = this.options[j].value;
        }
      }
    },
    manualAllocate(taskId, isRequest) {
      let row = this.tasksData.find(item => item.id === taskId);
      if (!row) return;
      
      if (isRequest) {
        this.$router.push({
          path: "/manualallocate/" + taskId + "/" + row.taskName,
        });
      } else {
        request({
          url: "/allocation/is_assigned?taskId=" + Number(taskId),
          method: "get",
        }).then((response) => {
          if (response.data.data) {
            this.$router.push({
              path: "/manualallocate/" + taskId + "/" + row.taskName,
            });
          } else if (response.data.status == "401") {
            this.$alert(response.data.message);
            this.$router.push({ path: "/login" });
          } else {
            this.$notify.error({
              title: "提示",
              message: response.data.message + "，" + "请先进行自动分配",
            });
          }
        });
      }
    },
    sinClo({ row, column, rowIndex, columnIndex }) {
      if (!(columnIndex == 3 && rowIndex == 0)) {
        return "sinCl";
      }
    },
  },
  mounted() {
    this.init();
  },
};
</script>
<style lang="scss" scoped>
.el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
  background-color: rgb(89, 103, 120) !important;
  border-color: #304156 !important;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}

.el-dropdown-link:hover {
  color: #66b1ff;
}

.search-container {
  text-align: left;
}
</style>
