<template>
  <div class="simple-container workersList-container">
    <simple-form
      :form="table_form"
      :handle="table_handle"
      @search="handleSearch"
      @summary="handleVisible('summary')"
      @add="handleVisible('add')"
    >
    </simple-form>
    <simple-table
      :list="table_list"
      :config="table_config"
      :loading="table_loading"
      :multiple="true"
      :handle-row="table_handle_row"
      @selection="handleSelect"
      :selectable="handleSelectFilter"
      @check="handleCheck"
      @edit="handleEdit"
      @approve="handleApprove"
    ></simple-table>
    <simple-pagination
      :page="page"
      :total="total"
      @change="handleChange"
    ></simple-pagination>
    <simple-dialog
      :title="title"
      :fullscreen="true"
      @cancel="handleVisible('add')"
      :visible="add_visible"
    >
      <el-form
        label-width="120px"
        :rules="rules"
        :model="add_form"
        ref="add_ref"
      >
        <el-form-item label="提出人" prop="proposer">
          <el-input
            :disabled="title === '审批' || title === '查看'"
            v-model="add_form.proposer"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="telephone">
          <el-input
            :disabled="title === '审批' || title === '查看'"
            v-model="add_form.telephone"
          ></el-input>
        </el-form-item>
        <el-form-item label="网格划分需求" prop="wanggeText">
          <el-input
            type="textarea"
            :disabled="title === '审批' || title === '查看'"
            v-model="add_form.wanggeText"
          ></el-input>
        </el-form-item>
        <el-form-item label="附件上传" prop="file">
          <!-- <myUpload
            v-if="title === '新建' || title === '发起人处理'"
            @uploadBack="uploadBack"
            :fileInfo="fileInfo"
            :fileList="fileInfo.fileList"
          ></myUpload> -->
          <el-upload
            v-if="title === '新建' || title === '发起人处理'"
            class="upload-demo"
            drag
            :limit="3"
            :on-exceed="uploadExceed"
            :on-remove="uploadRemove"
            :http-request="uploadBack"
            action="http://192.168.1.228:9600/spfm"
            multiple
            :file-list="file"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
          </el-upload>
          <div v-else>
            <div v-if="file.length === 0">暂无附件</div>
            <div
              v-for="(item, index) in file"
              :key="index"
              class="simple-table-click cursor-pointer margin-left-10"
              @click="handleDownload(item)"
            >
              {{ item.fileName }}
            </div>
          </div>
        </el-form-item>
        <el-form-item label="审批轨迹" prop="" v-if="edit_visible">
          <simple-table
            :list="table_list_approve"
            :config="table_config_approve"
            :loading="table_loading_approve"
          ></simple-table>
        </el-form-item>
        <el-form-item
          label="审批意见"
          prop="desc"
          v-if="edit_visible && approve_visible"
        >
          <el-input type="textarea" v-model="add_form.remark"></el-input>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div v-if="title === '新建'">
          <el-button @click="handleSubmit('save')" type="primary"
            >保存</el-button
          >
          <el-button @click="handleSubmit('add')" type="primary"
            >提交</el-button
          >
          <el-button @click="handleVisible('add')" type="default"
            >取消</el-button
          >
        </div>
        <div v-else-if="title === '查看'">
          <div>
            <el-button @click="handleVisible('add')" type="primary"
              >确定</el-button
            >
          </div>
        </div>
        <div v-else-if="title === '发起人处理'">
          <el-button @click="handleSubmit('save')" type="primary"
            >保存</el-button
          >
          <el-button @click="handleSubmit('add')" type="primary"
            >重新提交</el-button
          >
          <el-button @click="handleVisible('add')" type="default"
            >取消</el-button
          >
        </div>
        <div v-else>
          <el-button @click="handleSubmit('adopt')" type="primary"
            >保存</el-button
          >
          <el-button @click="handleSubmit('failed')" type="default"
            >退回修改</el-button
          >
          <el-button @click="handleVisible('add')" type="default"
            >取消</el-button
          >
        </div>
      </template>
    </simple-dialog>
    <simple-dialog
      title="工单汇总"
      width="40%"
      @cancel="handleVisible('summary')"
      @confirm="handleSummary"
      :visible="summary_visible"
    >
      <div class="summary">
        <p>是否要对所选工单进行汇总？</p>
        <p class="summary-tip">
          可对未审批的区县网格划分审批工单合并为同一条工单，由相关审批人员进行审批，减少审批工作量
        </p>
      </div>
    </simple-dialog>
  </div>
</template>

<script>
// import myUpload from "../../../components/upload";
import simpleForm from "../performance/components/form.vue";
import simpleTable from "../performance/components/table.vue";
import simpleDialog from "../performance/components/dialog.vue";
import simplePagination from "../performance/components/pagination.vue";

export default {
  components: {
    simpleForm,
    simpleDialog,
    // myUpload,
    simpleTable,
    simplePagination,
  },
  data() {
    const chcekPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/;
      if (!value) {
        return callback(new Error("联系人为空"));
      }

      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error("请输入数字值"));
        } else {
          if (phoneReg.test(value)) {
            callback();
          } else {
            callback(new Error("联系人格式不正确"));
          }
        }
      }, 100);
    };
    return {
      rules: {
        proposer: [
          {
            required: true,
            message: "提出人不能为空",
            trigger: "blur",
          },
        ],
        telephone: [
          {
            required: true,
            // message: "联系电话不能为空",
            trigger: "blur",
            validator: chcekPhone,
          },
        ],
        wanggeText: [
          {
            required: true,
            message: "网格划分需求不能为空",
            trigger: "blur",
          },
        ],
      },
      file: [],
      file1: "",
      file2: "",
      file3: "",
      // 删除的文件
      delFile: "",
      // 暂存删除文件
      tmpDeleteFile: [],
      // 当前用户标识
      loginNoStr: "",
      fileInfo: {
        limit: 3,
        url: "/market/mkWangge/upload",
        fileList: [],
      },
      attList: [],
      page: 1,
      rows: 10,
      total: 0,
      // 模态框标题
      title: "",
      // 是否为查看状态
      isCheck: false,
      // 汇总id列表
      summaryIds: [],
      table_search: {},
      // 新建模态框
      add_visible: false,
      summary_visible: false,
      edit_visible: false,
      approve_visible: false,
      ids: [],
      add_form: {},
      table_handle: [
        {
          label: "工单汇总",
          props: "summary",
        },
        {
          label: "新建",
          props: "add",
        },
      ],
      table_form: [
        {
          label: "公司名称",
          props: "companyName",
          type: "input",
        },
        {
          label: "状态",
          props: "sts",
          type: "select",
          // 0.待办  1.已办
          dictionary: [
            {
              label: "待办",
              value: "0",
            },
            {
              label: "已办",
              value: "1",
            },
          ],
        },
      ],
      // 列表数据
      table_list: [],
      table_loading: false,
      //   表格里的操作按钮
      table_handle_row: [
        {
          label: "查看",
          props: "check",
        },
        {
          label: "编辑",
          props: "edit",
          visible: {
            isEdit: ["1"],
          },
        },
        {
          label: "处理",
          props: "approve",
          visible: {
            deal: ["1"],
          },
        },
      ],
      //  表头配置
      table_config: [
        {
          label: "序号",
          props: "No",
        },
        {
          label: "公司名称",
          props: "companyName",
        },
        {
          label: "发起人",
          props: "proposer",
        },
        {
          label: "发起时间",
          props: "createTime",
        },
        {
          label: "状态",
          props: "sts",
          type: "dictionary",
          dictionary: { 0: "待办", 1: "已办" },
        },
      ],
      // 模态框内表数据
      table_list_approve: [],
      table_loading_approve: false,
      // 模态框内表头配置
      table_config_approve: [
        {
          label: "编号",
          props: "No",
        },
        {
          label: "流程环节",
          props: "liuchengName",
        },
        {
          label: "处理人",
          props: "createId",
        },
        {
          label: "处理工号",
          props: "createName",
        },
        {
          label: "处理时间",
          props: "createTime",
        },
        {
          label: "审批意见",
          props: "desc",
          // type: "dictionary",
          // dictionary: { 0: "同意", 1: "不同意" },
        },
      ],
    };
  },
  mounted() {
    this.handleInit();
    this.loginNoStr = JSON.parse(sessionStorage.getItem("userInfo")).loginNoStr;
  },
  methods: {
    // 表格数据初始化
    handleInit() {
      this.table_loading = true;
      // console.log(data);
      let reqdata = {
        ...this.table_search,
        type: "1",
        page: this.page,
        pageSize: this.rows,
      };
      this.$http({
        url: "/market/mkWangge/queryPage",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: reqdata,
      }).then(({ data: body }) => {
        this.table_loading = false;
        console.log(body.body);

        // 汇总或新建权限判断是否显示按钮
        let huiZongButton = body.body.huiZongButton;
        let insertButton = body.body.insertButton;

        if (huiZongButton && insertButton) {
          this.table_handle = [
            {
              label: "工单汇总",
              props: "summary",
            },
            {
              label: "新建",
              props: "add",
            },
          ];
        } else if (huiZongButton && !insertButton) {
          this.table_handle = [
            {
              label: "工单汇总",
              props: "summary",
            },
          ];
        } else if (!huiZongButton && insertButton) {
          this.table_handle = [
            {
              label: "新建",
              props: "add",
            },
          ];
        } else {
          this.table_handle = [];
        }

        // 列表数据回显
        let data = body.body.page.data;
        let count = body.body.page.count;

        this.total = count;
        this.table_list = data
          ? data.map((element, index) => ({
              ...element,
              id: element.id + "",
              deal: element.draft === "1" && element.sts === "0" ? "1" : "0",
              isEdit:
                element.draft === "0" &&
                element.createId === this.loginNoStr &&
                element.parentLevel === "0"
                  ? "1"
                  : "0",
              No: index + 1,
            }))
          : [];
        // console.log(this.table_list);
      });
    },
    // 搜索事件
    handleSearch(data) {
      this.table_search = data;
      this.page = 1;
      this.handleInit();
    },
    handleVisible(props) {
      this.approve_visible = false;
      switch (props) {
        case "add":
          this.add_visible = !this.add_visible;
          this.edit_visible = false;
          this.approve_visible = false;
          this.title = "新建";
          this.isCheck = false;
          this.add_form = {};
          this.file = [];
          break;
        case "summary":
          this.summary_visible = !this.summary_visible;
          break;

        case "edit":
          this.edit_visible = !this.edit_visible;
          this.add_visible = !this.add_visible;
          this.title = "发起人处理";
          this.isCheck = false;
          break;
        case "check":
          this.edit_visible = !this.edit_visible;
          this.add_visible = !this.add_visible;
          this.title = "查看";
          this.isCheck = true;
          break;
        case "approve":
          this.edit_visible = !this.edit_visible;
          this.add_visible = !this.add_visible;
          this.title = "审批";
          this.isCheck = false;
          this.approve_visible = !this.approve_visible;
          break;
      }
    },
    handleSelect(val) {
      this.summaryIds = val.map((item) => {
        return item.wanggeId + "";
      });
      // console.log(this.summaryIds);
    },
    //文件返回值
    uploadBack({ file }) {
      // console.log( file instanceof Object,'sasdas');
      this.file.push(file);
      console.log(this.file, "file");
      this.file1 = this.file[0];
      this.file2 = this.file[1];
      this.file3 = this.file[2];
    },
    // 删除文件
    uploadRemove(file) {
      console.log(file,'dada');
      this.file.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.file.splice(index, 1);
          if (item.id) {
            this.tmpDeleteFile.push(item.id);
            // this.delFile = this.delFile + item.id + ','
            this.delFile = this.tmpDeleteFile.join(",");
          }
        }
      });
      this.file1 = this.file[0];
      this.file2 = this.file[1];
      this.file3 = this.file[2];
    },
    // 超出文件上传限制
    uploadExceed(file) {
      this.$message({
        message: "附件最多可上传3个！",
        type: "error",
      });
      console.log(file);
    },
    // 获取模态框信息
    getDialogData(row) {
      let id = row.wanggeId;
      let type = row.parentId === null ? "1" : "0";
      this.$http({
        url: "/market/mkWangge/getMkWanggeById",
        method: "get",
        headers: {
          "Content-Type": "application/json",
        },
        params: {
          id,
          type,
        },
      }).then(({ data: { body } }) => {
        // console.log(body, "body");
        this.ids = [body.wanggeId.toString()];
        this.add_form = {
          id: body.wanggeId,
          proposer: body.proposer,
          telephone: body.telephone,
          wanggeText: body.wanggeText,
          fileNames: body.fileNames,
          fileIds: body.fileIds,
        };
        this.table_list_approve = body.mkWanggeLogList
          ? body.mkWanggeLogList.map((item, index) => ({
              ...item,
              No: index + 1,
            }))
          : [];
        this.file = body.attList
          ? body.attList.map((item) => ({
              ...item,
              name: item.fileName,
            }))
          : [];
      });
    },
    // 查看按钮
    handleCheck(row) {
      if (row.parentLevel === "1") {
        this.$router.push({
          path: "/approvalExamination",
          query: {
            parentId: row.wanggeId.toString(),
            status: row.sts.toString(),
          },
        });
      } else {
        this.getDialogData(row);
        this.handleVisible("check");
      }
    },
    // 编辑按钮
    handleEdit(row) {
      this.getDialogData(row);
      this.handleVisible("edit");
    },
    // 处理按钮
    handleApprove(row) {
      if (row.parentLevel === "1") {
        this.$router.push({
          path: "/approvalExamination",
          query: {
            parentId: row.wanggeId.toString(),
            status: row.sts.toString(),
          },
        });
      } else {
        this.getDialogData(row);
        this.handleVisible("approve");
      }
    },
    handleSubmit(type) {
      // console.log(this.add_form);
      // let _this = this;
      let draft = "";
      if (type === "add") {
        draft = "1";
      } else if (type === "save") {
        draft = "0";
      }
      let isAdopt = "";
      if (type === "adopt") {
        isAdopt = "0";
      } else if (type === "failed") {
        isAdopt = "1";
      }
      this.$refs.add_ref.validate((valid) => {
        if (valid) {
          let formData = new FormData();
          // console.log(this.file1,'adasdsa')
          let reqdata = {
            ...this.add_form,
            procId: "729294602773110788",
            draft: draft,
            num: "1",
            delFileId: this.delFile ? this.delFile : "",
          };
          // 这是处理文件的参数
          this.file.forEach((el, index) => {
            if (el.constructor.name === "File") {
              formData.append(`file${index + 1}`, el);
            }
          });
          // 表单的其他参数
          for (let key in reqdata) {
            formData.append(key, reqdata[key]);
          }
          // this.file1 ? formData.append("file1", this.file1) : "";
          // this.file2 ? formData.append("file2", this.file2) : "";
          // this.file3 ? formData.append("file3", this.file3) : "";
          // this.file ? formData.append("file", this.file) : [] ;
          // ;
          if (!this.approve_visible) {
            // 编辑/新增
            this.$http({
              url: "/market/mkWangge/saveOrUpdateList",
              method: "post",
              headers: {
                "Content-Type": "multipart/form-data",
              },
              data: formData,
            }).then((res) => {
              console.log(res);
              this.handleInit();
              this.handleVisible("add");
            });
          } else {
            // 审批
            let reqdata = {
              ids: this.ids,
              remark: this.add_form.remark,
              type: isAdopt,
            };
            console.log(reqdata, "reqdata");
            this.$http({
              url: "/market/mkWangge/review",
              method: "post",
              headers: {
                "Content-Type": "application/json",
              },
              data: {
                ...reqdata,
              },
            }).then((res) => {
              console.log(res);
              this.handleInit();
              this.handleVisible("add");
            });
          }
          // this.edit_visible = false;
          // this.add_visible = false;
          this.file = [];
        }
      });
    },
    handleSummary() {
      if (this.summaryIds.length === 0) {
        this.$message({
          message: "还未选择要合并的项目",
          type: "error",
        });
        this.handleVisible("summary");
        return;
      } else {
        this.$http({
          url: "/market/mkWangge/huizongWangge",
          method: "post",
          headers: {
            "Content-Type": "application/json",
          },
          data: this.summaryIds,
        }).then((res) => {
          console.log(res);
          if (res.data.result === 1) {
            this.$message({
              message: res.data.desc,
              type: "error",
            });
          } else {
            this.$message({
              message: res.data.desc,
              type: "success",
            });
          }
          this.handleInit();
        });
        this.handleVisible("summary");
      }
    },
    handleChange(page) {
      this.page = page;
      this.handleInit();
    },
    handleSelectFilter(row) {
      // 过滤可被选中的数组
      if (row.parentLevel === "1") {
        return false;
      } else {
        return true;
      }
    },
    // 附件下载
    handleDownload({ fileCode, fileName }) {
      console.log(fileCode, fileName);
      this.$http({
        url: "/bpm/api/download",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        responseType: "blob",
        data: { id: fileCode, fileName: fileName },
      }).then((response) => {
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          let blob = new Blob([response.data], {
            type: "application/vnd.ms-excel",
          });
          window.navigator.msSaveOrOpenBlob(blob, fileName);
        } else {
          /* 火狐谷歌的文件下载方式 */
          var blob = new Blob([response.data]);
          var downloadElement = document.createElement("a");
          var href = window.URL.createObjectURL(blob);
          downloadElement.href = href;
          downloadElement.download = fileName;
          document.body.appendChild(downloadElement);
          downloadElement.click();
          document.body.removeChild(downloadElement);
          window.URL.revokeObjectURL(href);
        }
      });
      // // /market/compatt/downfile
      // console.log(item);
    },
  },
};
</script>

<style lang="scss" scoped>
.workersList-container {
  background: #ffffff;
  padding: 0 20px;
  margin: 15px;
  overflow: auto;
  width: calc(100% - 30px);
  max-width: calc(100% - 30px);
  height: 100%;
  overflow-x: hidden;
}
.simple-container .el-form-item {
  padding-bottom: 22px;
}
.summary {
  padding: 20px 50px 100px;
  font-size: 16px;
  .summary-tip {
    color: #7f7f7f;
    padding-top: 30px;
  }
}
::v-deep .el-row {
  padding-top: 12px;
  padding-bottom: 12px;
}
</style>
