<template>
  <basic-container>
    <div>
      <Card class="cardTitle">
        <p>
          <el-button type="primary" @click="backPage" style="width: 80px"
            >返回</el-button
          >
        </p>
      </Card>

      <!-- 任务成员 -->
      <div class="leftCont">
        <avue-crud
          :data="memberData"
          :option="memberOption"
          :page.sync="memberPage"
          :table-loading="tableLoading"
          @on-load="getList"
          @size-change="sizeChange"
          @current-change="currentChange"
          :row-class-name="tableRowClassName"
          @row-click="handleRowClick"
          :row-style="selectedHighlight"
        >
          <template slot="menuLeft">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="addMember()"
              :disabled="viewType == 'lookType'"
              >添加任务成员</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-download"
              size="small"
              @click="exportMember()"
              :disabled="viewType == 'lookType'"
              >导入任务成员</el-button
            >
          </template>
          <template slot="menu" slot-scope="scope">
            <el-button
              type="text"
              size="small"
              icon="el-icon-tickets"
              :disabled="viewType == 'lookType'"
              @click="editMember(scope.row, scope.index)"
              >编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              icon="el-icon-close"
              :disabled="viewType == 'lookType'"
              @click="delMember(scope.row, scope.index)"
              >删除
            </el-button>
          </template>
        </avue-crud>

        <!-- 添加任务成员 -->
        <el-dialog
          :title="showTit"
          :visible.sync="memberDialog"
          width="50%"
          center
          :before-close="memberClose"
        >
          <el-form
            :model="memberForm"
            :rules="memberRules"
            ref="memberForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="姓名" prop="importName">
              <el-input v-model="memberForm.importName"></el-input>
            </el-form-item>

            <el-form-item label="手机号" prop="importPhone">
              <el-input
                onkeyup="value=value.replace(/[^\d]/g,'')"
                maxlength="11"
                v-model="memberForm.importPhone"
              ></el-input>
            </el-form-item>

            <el-form-item label="身份证号" prop="importIdCardNumber">
              <el-input
                onkeyup="value=value.replace(/[^A-Za-z0-9]/g,'')"
                maxlength="18"
                v-model="memberForm.importIdCardNumber"
              ></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="memberCancel">取 消</el-button>
            <el-button type="primary" @click="memberSure('memberForm')"
              >确 定</el-button
            >
          </span>
        </el-dialog>

        <!-- 任务成员-导入 -->
        <el-dialog
          :visible.sync="memberUploaddialog"
          :before-close="memberClose"
          title="导入任务成员"
          width="40%"
          custom-class="add-customer"
        >
          <el-upload
            ref="upload"
            :headers="headers"
            :limit="1"
            :on-preview="handlePreview"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
            :file-list="fileList"
            :auto-upload="false"
            :on-error="uploadError"
            :on-success="uploadSuccess"
            :action="uploadPath()"
            accept=".xls,.xlsx"
            class="upload-demo"
          >
            <div slot="tip" class="el-upload__tip">选择上传文件</div>

            <el-button slot="trigger" size="mini" type="primary"
              >添加文件</el-button
            >
            <el-button
              style="margin-left: 10px;"
              size="mini"
              type="success"
              @click="submitUpload"
              >开始上传</el-button
            >
            <el-button
              style="margin-left: 10px;"
              size="mini"
              type="warning"
              @click="uploadTemplate"
              >下载模板</el-button
            >
          </el-upload>
        </el-dialog>
      </div>

      <!-- 上传证据链 -->
      <div class="rightCont">
        <avue-crud
          :data="uploadData"
          :option="uploadOption"
          :page.sync="uploadPage"
          @on-load="selectSettleTask"
          @size-change="uploadSizechange"
          @current-change="uploadCurrentchange"
        >
          <template slot="menuLeft">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              :disabled="viewType == 'lookType'"
              @click="addUpload()"
              >上传证据链</el-button
            >
          </template>
          <template slot="menu" slot-scope="scope">
            <el-button
              type="text"
              size="small"
              icon="el-icon-tickets"
              :disabled="viewType == 'lookType'"
              @click="editUpload(scope.row, scope.index)"
              >编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              icon="el-icon-close"
              :disabled="viewType == 'lookType'"
              @click="delUpload(scope.row, scope.index)"
              >删除
            </el-button>
          </template>
        </avue-crud>

        <el-dialog
          :title="showTit"
          :visible.sync="uploadDialog"
          width="30%"
          :before-close="uploadClose"
        >
          <el-form
            :model="taskForm"
            :rules="taskRules"
            ref="taskForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="任务类型" prop="taskTypeId">
              <el-select
                v-model="taskForm.taskTypeId"
                placeholder="请选择"
                style="width: 335px"
              >
                <el-option
                  v-for="item in taskTypeList1"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="前端系统" prop="temp1">
              <el-input v-model="taskForm.temp1"></el-input>
            </el-form-item>

            <el-form-item label="项目名称" prop="temp2">
              <el-input v-model="taskForm.temp2"></el-input>
            </el-form-item>

            <el-form-item label="项目编码" prop="temp3">
              <el-input v-model="taskForm.temp3"></el-input>
            </el-form-item>

            <el-form-item label="说明" prop="temp4">
              <el-input v-model="taskForm.temp4"></el-input>
            </el-form-item>
          </el-form>
          <!--         <span slot="footer" class="dialog-footer">-->
          <!--					<el-button @click="memberCancel">取 消</el-button>-->
          <!--					<el-button type="primary" @click="memberSure('memberForm')">确 定</el-button>-->
          <!--				</span>-->

          <span slot="footer" class="dialog-footer">
            <el-button @click="uploadCancle">取 消</el-button>
            <el-button type="primary" @click="uploadSure('taskForm')"
              >确 定</el-button
            >
          </span>
        </el-dialog>
      </div>
    </div>
  </basic-container>
</template>

<script>
import store from "@/store";
import {
  memberOption,
  uploadOption
} from "@/const/crud/assignPoints/settlement/proofUpload";
import {
  showMember,
  showUpload,
  wmImportuser,
  getTaskTypeTree,
  editUser,
  saveTaskSettle,
  updateTaskSettle,
  selectSettleTask,
  delUser
} from "@/api/assignPoints/currency/proofUpload";

export default {
  name: "proofUpload",
  data() {
    return {
      // 任务成员
      memberData: [],
      memberOption: memberOption,
      memberPage: {
        pageSize: 10,
        pagerCount: 5
      },
      memberForm: {},
      memberRules: {
        importName: [
          { required: true, message: "请输入姓名", trigger: "blur" }
        ],
        importPhone: [
          { required: true, message: "请输入手机号", trigger: "change" },
          {
            pattern: /^1[3|5|7|8|9]\d{9}$/,
            message: "请输入正确的号码格式",
            trigger: "change"
          }
        ],
        importIdCardNumber: [
          { required: true, message: "请输入身份证号", trigger: "blur" },
          {
            pattern: /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/,
            message: "请输入正确的证件号"
          }
        ]
      },
      tableLoading: false,
      memberUploaddialog: false,
      fileList: [],
      memberDialog: false,
      getIndex: "",
      idVal: "",
      showTit: "",
      headers: {
        Authorization: "Bearer " + store.getters.access_token
      },

      taskUserId: "", //选中任务成员
      // 举证上传
      uploadDialog: false,
      uploadData: [],
      uploadOption: uploadOption,
      uploadPage: {
        pageSize: 10,
        pagerCount: 5,
        pageSize: 10,
        currentPage: 1
      },
      taskTypeList1: [],
      taskForm: {},
      taskRules: {
        taskTypeId: [
          { required: true, message: "请选择任务类型", trigger: "blur" }
        ],
        wmTaskContent: {
          temp1: [
            { required: true, message: "请输入前端系统", trigger: "blur" }
          ],
          temp2: [
            { required: true, message: "请输入项目名称", trigger: "blur" }
          ],
          temp3: [
            { required: true, message: "请输入项目编码", trigger: "blur" }
          ]
        }
      },
      viewType: ""
    };
  },
  mounted() {
    this.viewType = this.$route.query.type;
    this.idVal = this.$route.query.id;
    this.getTaskTypeList();
    this.selectSettleTask();
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      //把每一行的索引放进row
      row.index = rowIndex;
    },
    selectedHighlight({ row, rowIndex }) {
      if (this.getIndex === rowIndex) {
        return {
          "background-color": "#CAE1FF"
        };
      }
    },
    handleRowClick(row, rowIndex) {
      this.getIndex = row.index;
      this.taskUserId = row.id;
      this.selectSettleTask();
    },
    selectSettleTask() {
      // 0,1是为了区分是否为 初始化 或 单次点击
      selectSettleTask(
        Object.assign({
          scorePackageId: this.$route.query.id,
          taskUserId: this.taskUserId,
          current: this.uploadPage.currentPage,
          size: this.uploadPage.pageSize
        })
      )
        .then(response => {
          this.uploadData = [];
          this.uploadData = response.data.data.records;
          this.uploadPage.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    uploadClose() {
      this.uploadDialog = false;
    },
    // 上传举证-弹窗
    addUpload() {
      if (this.taskUserId == "") {
        this.$message.info("请先选中任务成员！");
      } else {
        this.uploadDialog = true;
        this.showTit = "新增";
        this.taskForm = {};
      }
    },
    uploadSure(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          (this.taskForm.scorePackageId = this.idVal), // 积分包id
            (this.taskForm.taskUserId = this.taskUserId), // 任务成员id
            (this.taskForm.wmTaskContent = {}),
            (this.taskForm.wmTaskContent.temp1 = this.taskForm.temp1),
            (this.taskForm.wmTaskContent.temp2 = this.taskForm.temp2),
            (this.taskForm.wmTaskContent.temp3 = this.taskForm.temp3),
            (this.taskForm.wmTaskContent.temp4 = this.taskForm.temp4);
          if (this.showTit == "新增") {
            saveTaskSettle(this.taskForm)
              .then(response => {
                this.uploadDialog = false;
                this.$message.success("保存成功！");
                this.selectSettleTask();
              })
              .catch(() => {
                this.$message.success("保存失败！");
              });
          } else {
            updateTaskSettle(this.taskForm)
              .then(response => {
                this.uploadDialog = false;
                this.$message.success("保存成功！");
                this.selectSettleTask();
              })
              .catch(() => {
                this.$message.success("保存失败！");
              });
          }
        }
      });
    },
    uploadCancle() {
      this.uploadDialog = false;
    },
    // 任务类型列表
    getTaskTypeList() {
      this.taskTypeList1 = [];
      let arg = {
        id: this.idVal
      };
      getTaskTypeTree(arg).then(response => {
        response.data.data.treeList.forEach(item => {
          item.children.forEach(item1 => {
            const addnew = {
              value: item1.taskTypeId,
              label: item1.taskTypeName
            };
            this.taskTypeList1.push(addnew);
          });
        });
      });
    },
    // 返回按钮
    backPage() {
      this.$router.$avueRouter.closeTag();
      this.$router.push({ path: "/admin/assignPoints/settlement/index" });
    },

    // 初始化页面-任务成员
    getList(page, params) {
      this.tableLoading = true;
      showMember(
        Object.assign(
          {
            scoreId: this.$route.query.id,
            current: page.currentPage,
            size: page.pageSize
          },
          params,
          this.searchForm
        )
      )
        .then(response => {
          this.memberData = [];
          this.memberData = response.data.data.records;
          this.memberPage.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },

    // 初始化页面-举证列表
    uploadList(page, params) {
      this.tableLoading = true;
      showUpload(
        Object.assign(
          {
            scorePackageId: this.$route.query.id,
            current: page.currentPage,
            size: page.pageSize
          },
          params,
          this.searchForm
        )
      )
        .then(response => {
          this.uploadData = [];
          this.uploadData = response.data.data.records;
          // this.uploadPage.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },

    // 添加任务成员-弹窗
    addMember(row) {
      this.memberDialog = true;
      this.showTit = "新增";
    },

    // 添加任务成员-确定
    memberSure(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.memberForm.scoreId = this.idVal;
          if (this.showTit == "新增") {
            // 新增
            wmImportuser(this.memberForm)
              .then(response => {
                this.$message.success("添加任务成员成功！");
                this.getList(this.memberPage);
                this.memberDialog = false;
                this.memberForm = {};
              })
              .catch(() => {
                this.memberDialog = false;
                this.memberForm = {};
              });
          } else {
            // 编辑
            editUser(this.memberForm)
              .then(response => {
                this.$message.success("编辑任务成员成功！");
                this.getList(this.memberPage);
                this.memberDialog = false;
                this.memberForm = {};
              })
              .catch(() => {
                this.memberDialog = false;
                this.memberForm = {};
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 导入任务成员-一系列事件
    exportMember() {
      this.memberUploaddialog = true;
    },
    uploadPath() {
      // 上传地址
      return "/admin/wmimportuser/impImportUser?scoreId=" + this.idVal;
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    uploadError(res, file, fileList) {
      // 上传错误
      this.loading = false;
      this.$message({
        message: "网络错误，请稍后再试",
        type: "error"
      });
      this.memberUploaddialog = false;
      this.getList(this.memberPage);
    },
    uploadSuccess(res, file, fileList) {
      // 上传成功后的回调
      this.$message({
        type: "success",
        message: res.data
      });
      this.getList(this.memberPage);
      this.memberUploaddialog = false;
      this.$refs.upload.clearFiles();
    },
    submitUpload() {
      // 开始上传按钮
      this.loading = true;
      this.$refs.upload.submit();
    },
    uploadTemplate() {
      // 下载模板
      let a = document.createElement("a");
      a.href =
        "http://localhost:8080/admin/sys-file/wmkj/导入任务成员模版.xlsx"; // 这里的请求方式为get，如果需要认证，接口上需要带上token
      a.click();
    },
    // 任务成员-编辑，删除
    editMember(row) {
      this.memberDialog = true;
      this.showTit = "编辑";
      this.memberForm = row;
    },
    delMember(row) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.tableLoading = true;
          let id = row.id;
          delUser(id)
            .then(() => {
              this.getList(this.memberPage);
              this.tableLoading = false;
            })
            .catch(() => {
              this.tableLoading = false;
            });
        })
        .catch(() => {
          //console.log("请求异常");
        });
    },

    // 上传举证-编辑，删除
    editUpload(row) {
      this.uploadDialog = true;
      this.showTit = "编辑";
      this.taskForm = row;
    },
    delUpload(row) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.tableLoading = true;
          // 编辑
          updateTaskSettle({
            id: row.id,
            delFlag: 1
          })
            .then(response => {
              this.uploadDialog = false;
              this.$message.success("删除成功！");
              this.selectSettleTask();
            })
            .catch(() => {
              this.$message.success("删除失败！");
            });
        })
        .catch(() => {});
    },

    // 取消-任务成员
    memberCancel() {
      this.memberDialog = false;
      this.memberForm = {};
      this.getList(this.memberPage);
    },
    memberClose() {
      this.memberDialog = false;
      this.memberForm = {};
      this.memberUploaddialog = false;
      this.getList(this.memberPage);
    },
    // 分页查询-任务成员
    sizeChange(pageSize) {
      this.memberPage.pageSize = pageSize;
    },
    currentChange(current) {
      this.memberPage.currentPage = current;
    },

    // 分页查询-举证上传
    uploadSizechange(pageSize) {},
    uploadCurrentchange(current) {}
  }
};
</script>

<style>
.cardTitle {
  margin-bottom: 15px;
}
.leftCont {
  width: 50%;
  float: left;
  border-right: 1px solid #a39f9f;
}
.rightCont {
  width: 50%;
  float: left;
}
</style>
