<template>
  <el-dialog
    title="上传信息"
    :visible="visible"
    width="490px"
    :before-close="handleClose"
    :close-on-click-modal="false"
  >
    <div class="popup-content">
      <el-form
        ref="postForm"
        :model="postForm"
        :rules="postFormRule"
        label-width="80px"
        @keyup.enter.native="postFormSubmit()"
      >
        <el-form-item label="运营中心" prop="operationsCenterId" v-if="userInfo.userTypeModel == 'admin'">
          <el-select
            v-model="postForm.operationsCenterId"
            clearable
            filterable
            placeholder="请选择运营中心"
            @change="onOperationsCenterChange"
          >
            <el-option v-for="item in operationsCenterList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="项目名称"
          prop="projectId"
          v-if="userInfo.userTypeModel == 'admin' || userInfo.userTypeModel == 'operationsCenter'"
        >
          <el-select
            v-model="postForm.projectId"
            :disabled="!postForm.operationsCenterId"
            filterable
            clearable
            placeholder="请选择项目"
          >
            <el-option v-for="item in projectList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="上传文件" prop="fileList">
          <el-upload
            :file-list="postForm.fileList"
            ref="upload"
            :action="action"
            :multiple="false"
            name="file"
            :data="uploadData"
            :auto-upload="false"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-change="handleUploadChange"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <!-- <div slot="tip" class="el-upload__tip">只能上传.xlsx, .xls, .csv文件，且不超过500kb</div> -->
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { companyGetselectlist, organizationGetselectlist } from "@/api/flashdeliver/jiaoshuima";

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      operationsCenterList: [], // 运营中心列表
      projectList: [], // 项目列表
      postForm: {
        operationsCenterId: "",
        projectId: "",
        fileList: []
      },
      postFormRule: {
        operationsCenterId: [{ required: true, message: "运营中心不能为空", trigger: "change" }],
        projectId: [{ required: true, message: "项目不能为空", trigger: "change" }],
        fileList: [
          {
            required: true,
            type: "array",
            validator: (rule, value, callback) => {
              if (!value.length) {
                return callback(new Error("上传文件不能为空"));
              }

              callback();
            },
            trigger: "change"
          }
        ]
      },
      userInfo: {},
      action: `${process.env.BASE_API}/organisation/customermgt/importRoomInfo`
    };
  },
  computed: {
    uploadData() {
      const { projectId, operationsCenterId } = this.postForm;

      return {
        compId: operationsCenterId,
        orgId: projectId
      };
    }
  },
  methods: {
    handleClose() {
      this.loading = false;
      this.$emit("update:visible", false);
    },
    handleOpen() {
      this.$emit("update:visible", true);
    },
    handleOpen() {
      this.$emit("update:visible", true);
    },
    handleSubmit() {
      this.$refs["postForm"].validate(valid => {
        if (!valid) {
          return;
        }
        this.loading = true;
        this.$refs.upload.submit();
      });
    },
    init() {
      this.getOperationsCenterList();
    },
    handleUploadChange(file, fileList) {
      const isExcel = /\.(xlsx|xls|csv)$/.test(file.name);
      const isLimit = fileList.length > 1;

      if (!isExcel) {
        this.$message.error("上传信息只能是 .xlsx, .xls, .csv格式!");
        fileList.splice(-1, 1);
        return;
      }

      if (isLimit) {
        this.$message({
          type: "error",
          message: `只能选择 1 个文件，当前共选择了 ${fileList.length} 个`
        });
        fileList.splice(-1, 1);
        return;
      }

      this.postForm.fileList = fileList;
    },
    handleUploadSuccess(res, file) {
      console.log("handleUploadSuccess", res, file);
      this.loading = false;
      if (Number(res.code) === 200) {
        this.$message({
          type: "success",
          dangerouslyUseHTMLString: true,
          message: res.msg,
          duration: 2500
        });
        this.$emit("submit");
      } else {
        this.$message({
          type: "error",
          dangerouslyUseHTMLString: true,
          message: res.msg,
          duration: 2500
        });
      }
    },
    handleUploadError(err) {
      console.error("handleUploadError", err);
      this.loading = false;
      this.$message({
        type: "error",
        message: `上传失败`,
        duration: 2500
      });
    },
    async getProjectList() {
      const params = {
        pageNo: 1,
        pageSize: 999
      };

      this.postForm.operationsCenterId && (params["conditions[companyId]"] = this.postForm.operationsCenterId);

      const res = await organizationGetselectlist(params);
      this.projectList = res.data;
      if (res.data && res.data.length === 1) {
        this.postForm.projectId = res.data[0].value;
      }
    },
    onOperationsCenterChange() {
      this.postForm.projectId = "";
      this.getProjectList();
    },
    async getOperationsCenterList() {
      const res = await companyGetselectlist();
      this.operationsCenterList = res.data;
      if (res.data && res.data.length) {
        const operationsCenterId = res.data[0].value;
        this.postForm.operationsCenterId = operationsCenterId;
        this.getProjectList();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.ul {
}

.li {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  &-hd {
    width: 100px;
    margin-right: 20px;
  }
  &-bd {
    margin-right: 20px;
  }

  &-ft {
    display: flex;
    align-items: center;
    &-split {
      padding: 0 5px;
      display: inline-block;
      color: #606266;
      font-size: 14px;
    }
  }

  /deep/ .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 240px;
  }
  /deep/ .el-range-editor--mini.el-input__inner {
    height: 34px;
  }
}
</style>
