<template>
  <section class="content" style="margin-top: -18px;">
    <div class="box box-info">
      <!-- 头信息 -->
      <div
        class="box-header with-border"
        style="background-color:#d3dce6;margin-bottom:20px;"
      >
        <h2 class="box-title">项目列表</h2>
        <div class="box-tools pull-right">
          <button type="button" class="btn btn-box-tool" data-widget="collapse">
            <i class="fa fa-minus"></i>
          </button>
        </div>
      </div>

      <!-- 正文信息 -->
      <div class="box-body">
        <el-form
          :model="formSearch"
          :inline="true"
          label-position="right"
          label-width="100px"
        >
          <el-form-item label="学校">
            <el-select
              v-model="formSearch.orgId"
              placeholder="请选择"
              clearable
              @change="searchExamList(formSearch.orgId);"
            >
              <el-option
                v-for="item in orgList"
                :label="item.orgName"
                :value="item.orgId"
                :key="item.orgId"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="考试">
            <el-select
              v-model="formSearch.examId"
              @change="searchRecords"
              placeholder="请选择"
            >
              <el-option
                v-for="item in examList"
                :label="item.examName"
                :value="item.examId"
                :key="item.examId"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="项目经理">
            <el-select
              v-model="formSearch.pmId"
              placeholder="请选择"
              filterable
              clearable
              remote
              :remote-method="searchPmList"
            >
              <el-option label="请选择" value=""></el-option>
              <el-option
                v-for="item in pmList"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="印刷供应商">
            <el-select
              v-model="formSearch.supplierId"
              placeholder="请选择"
              filterable
              clearable
              remote
              :remote-method="searchSupplierList"
            >
              <el-option label="请选择" value=""></el-option>
              <el-option
                v-for="item in supplierList"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item style="padding-left: 60px">
            <el-button
              size="small"
              type="primary"
              icon="el-icon-search"
              @click="searchRecords"
              >查询
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 数据列表 -->
        <el-table
          v-loading="loading"
          :data="tableData"
          element-loading-text="数据加载中"
          style="width:100%;"
          border
        >
          <el-table-column width="220" label="学校名称" prop="orgName" />
          <el-table-column label="考试名称" prop="examName" />
          <el-table-column width="200" label="印刷供应商" prop="supplierName" />
          <el-table-column width="150" label="项目经理" prop="pmName" />

          <el-table-column width="120" label="项目统计">
            <template slot-scope="scope">
              <el-button
                size="mini"
                icon="el-icon-view"
                @click="gotoProjectStatistic(scope.row);"
                >查看
              </el-button>
            </template>
          </el-table-column>

          <el-table-column width="120" label="操作" :context="_self">
            <template slot-scope="scope">
              <el-button
                size="mini"
                icon="el-icon-menu"
                @click="openProjectSettingDialog(scope.row);"
                :disabled="!hasPermit"
                >项目设置
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="page pull-right">
          <el-pagination
            @current-change="handlePager"
            :current-page="formSearch.pageNo"
            :page-size="formSearch.pageSize"
            :total="totalElements"
            layout="total, prev, pager, next, jumper"
          ></el-pagination>
        </div>
      </div>

      <!-- 项目设置弹窗 -->
      <el-dialog
        title="项目设置"
        width="750px"
        :visible.sync="projectSettingDialog"
        @close="closeProjectSettingDialog"
      >
        <el-form
          :model="projectSettingForm"
          ref="projectSettingForm"
          :rules="rules"
          label-position="right"
          label-width="110px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="学校" prop="orgId">
                <el-select
                  v-model="projectSettingForm.orgId"
                  placeholder="请选择"
                  :disabled="true"
                  class="w220"
                >
                  <el-option
                    v-for="item in orgList"
                    :label="item.orgName"
                    :value="item.orgId"
                    :key="item.orgId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="考试" prop="examId">
                <el-select
                  v-model="projectSettingForm.examId"
                  placeholder="请选择"
                  :disabled="true"
                  class="w220"
                >
                  <el-option
                    v-for="item in examList"
                    :label="item.examName"
                    :value="item.examId"
                    :key="item.examId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="项目经理" prop="pmId">
                <el-select
                  v-model="projectSettingForm.pmId"
                  placeholder="请选择"
                  @change="selectPmName"
                  clearable
                  class="w220"
                >
                  <el-option
                    v-for="item in pmList"
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="供应商" prop="supplierId">
                <el-select
                  v-model="projectSettingForm.supplierId"
                  placeholder="请选择"
                  @change="selectSupplierName"
                  clearable
                  class="w220"
                >
                  <el-option
                    v-for="item in supplierList"
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="准备开始时间" prop="prepareStartTime">
                <el-date-picker
                  v-model="projectSettingForm.prepareStartTime"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择开始时间"
                  class="w220"
                ></el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="准备结束时间" prop="prepareEndTime">
                <el-date-picker
                  v-model="projectSettingForm.prepareEndTime"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择结束时间"
                  class="w220"
                  :picker-options="prepareEndTimePicker"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="印刷开始时间" prop="printStartTime">
                <el-date-picker
                  v-model="projectSettingForm.printStartTime"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择开始时间"
                  class="w220"
                ></el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="印刷结束时间" prop="printEndTime">
                <el-date-picker
                  v-model="projectSettingForm.printEndTime"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择结束时间"
                  class="w220"
                  :picker-options="printEndTimePicker"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="邮寄开始时间" prop="mailStartTime">
                <el-date-picker
                  v-model="projectSettingForm.mailStartTime"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择开始时间"
                  class="w220"
                ></el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="邮寄结束时间" prop="mailEndTime">
                <el-date-picker
                  v-model="projectSettingForm.mailEndTime"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择结束时间"
                  class="w220"
                  :picker-options="mailEndTimePicker"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <div style="text-align: center">
          <el-button type="primary" @click="editProjectSetting"
            >确 定
          </el-button>
          <el-button @click="closeProjectSettingDialog">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </section>
</template>

<script>
import { CORE_API, PRINT_API } from "@/constants/constants";
import { userRole } from "../constants/constants.js";
import { mapState } from "vuex";

export default {
  data() {
    let validatePrepareStartTime = (rule, value, callback) => {
      if (!this.projectSettingForm.prepareStartTime) {
        callback(new Error("请选择开始日期！"));
      } else {
        this.$refs.projectSettingForm.validateField("prepareEndTime");
        callback();
      }
    };

    let validatePrepareEndTime = (rule, value, callback) => {
      if (!this.projectSettingForm.prepareEndTime) {
        callback(new Error("请选择结束日期！"));
      } else if (
        this.projectSettingForm.prepareStartTime >
        this.projectSettingForm.prepareEndTime
      ) {
        callback(new Error("开始日期大于结束日期！"));
      } else {
        callback();
      }
    };

    let validatePrintStartTime = (rule, value, callback) => {
      if (!this.projectSettingForm.printStartTime) {
        callback(new Error("请选择开始日期！"));
      } else {
        this.$refs.projectSettingForm.validateField("printEndTime");
        callback();
      }
    };

    let validatePrintEndTime = (rule, value, callback) => {
      if (!this.projectSettingForm.printEndTime) {
        callback(new Error("请选择结束日期！"));
      } else if (
        this.projectSettingForm.printStartTime >
        this.projectSettingForm.printEndTime
      ) {
        callback(new Error("开始日期大于结束日期！"));
      } else {
        callback();
      }
    };

    let validateMailStartTime = (rule, value, callback) => {
      if (!this.projectSettingForm.mailStartTime) {
        callback(new Error("请选择开始日期！"));
      } else {
        this.$refs.projectSettingForm.validateField("mailEndTime");
        callback();
      }
    };

    let validateMailEndTime = (rule, value, callback) => {
      if (!this.projectSettingForm.mailEndTime) {
        callback(new Error("请选择结束日期！"));
      } else if (
        this.projectSettingForm.mailStartTime >
        this.projectSettingForm.mailEndTime
      ) {
        callback(new Error("开始日期大于结束日期！"));
      } else {
        callback();
      }
    };

    return {
      formSearch: {
        orgId: "",
        examId: "",
        pmId: "",
        supplierId: "",
        pageNo: 1,
        pageSize: 10
      },
      curUserRole: userRole,
      hasPermit: false,
      totalElements: 0,
      loading: false,
      tableData: [],
      orgList: [],
      examList: [],
      pmList: [],
      supplierList: [],
      projectSettingDialog: false,
      projectSettingForm: {
        id: "",
        orgId: "",
        examId: "",
        pmId: "",
        pmName: "",
        supplierId: "",
        supplierName: "",
        prepareStartTime: "",
        prepareEndTime: "",
        printStartTime: "",
        printEndTime: "",
        mailStartTime: "",
        mailEndTime: ""
      },
      rules: {
        orgId: [
          {
            type: "number",
            required: true,
            message: "请选择学校！",
            trigger: "change"
          }
        ],
        examId: [
          {
            type: "number",
            required: true,
            message: "请选择考试！",
            trigger: "change"
          }
        ],
        supplierId: [
          {
            type: "number",
            required: true,
            message: "请选择供应商！",
            trigger: "change"
          }
        ],
        pmId: [
          {
            type: "number",
            required: true,
            message: "请选择项目经理！",
            trigger: "change"
          }
        ],
        prepareStartTime: [
          {
            type: "date",
            required: true,
            validator: validatePrepareStartTime,
            trigger: "change"
          }
        ],
        prepareEndTime: [
          {
            type: "date",
            required: true,
            validator: validatePrepareEndTime,
            trigger: "change"
          }
        ],
        printStartTime: [
          {
            type: "date",
            required: true,
            validator: validatePrintStartTime,
            trigger: "change"
          }
        ],
        printEndTime: [
          {
            type: "date",
            required: true,
            validator: validatePrintEndTime,
            trigger: "change"
          }
        ],
        mailStartTime: [
          {
            type: "date",
            required: true,
            validator: validateMailStartTime,
            trigger: "change"
          }
        ],
        mailEndTime: [
          {
            type: "date",
            required: true,
            validator: validateMailEndTime,
            trigger: "change"
          }
        ]
      },
      prepareEndTimePicker: this.prepareEndTimePickerLimit(),
      printEndTimePicker: this.printEndTimePickerLimit(),
      mailEndTimePicker: this.mailEndTimePickerLimit()
    };
  },
  methods: {
    prepareEndTimePickerLimit() {
      let self = this;
      return {
        disabledDate(time) {
          if (self.projectSettingForm.prepareStartTime) {
            return (
              new Date(self.projectSettingForm.prepareStartTime).getTime() >
              time.getTime()
            );
          }
        }
      };
    },
    printEndTimePickerLimit() {
      let self = this;
      return {
        disabledDate(time) {
          if (self.projectSettingForm.printStartTime) {
            return (
              new Date(self.projectSettingForm.printStartTime).getTime() >
              time.getTime()
            );
          }
        }
      };
    },
    mailEndTimePickerLimit() {
      let self = this;
      return {
        disabledDate(time) {
          if (self.projectSettingForm.mailStartTime) {
            return (
              new Date(self.projectSettingForm.mailStartTime).getTime() >
              time.getTime()
            );
          }
        }
      };
    },
    handlePager(current) {
      /* 处理分页 */
      this.formSearch.pageNo = current;
      this.searchRecords();
    },
    searchRecords() {
      /* 查询记录列表 */
      let orgId = this.formSearch.orgId;
      if (this.isEmptyNumber(orgId)) {
        this.$notify({
          message: "请选择学校！",
          type: "warning"
        });
        return;
      }

      let examId = this.formSearch.examId;
      if (this.isEmptyNumber(examId)) {
        this.$notify({
          message: "请选择考试！",
          type: "warning"
        });
        return;
      }

      this.loading = true;
      let url = PRINT_API + "/printing/project/list";
      this.$http.post(url, this.formSearch).then(
        response => {
          this.tableData = response.data.content;
          this.totalElements = response.data.totalElements;
          this.loading = false;
        },
        error => {
          console.log(error);
          this.loading = false;
        }
      );
    },
    searchExamList(orgId) {
      /* 查询考试列表 */
      this.formSearch.examId = "";
      this.examList = [];
      this.tableData = [];
      //console.log("orgId:" + orgId);
      if (!this.isEmptyNumber(orgId)) {
        let url = PRINT_API + "/printing/project/exam/list?orgId=" + orgId;
        this.$http.post(url).then(response => {
          this.examList = response.data;
        });
      }
    },
    searchPmList(query) {
      /* 查询项目经理列表 */
      this.pmList = [];
      let url =
        CORE_API + "/user/query?rootOrgCode=qmth&roleCode=PRINT_PROJECT_LEADER";

      if (!this.isEmptyStr(query)) {
        url += "&name=" + query;
      }

      this.$http.get(url).then(response => {
        this.pmList = response.data;
      });
    },
    searchSupplierList(query) {
      /* 查询印刷供应商列表 */
      this.supplierList = [];
      let url =
        CORE_API + "/user/query?rootOrgCode=qmth-print&roleCode=PRINT_SUPPLIER";

      if (!this.isEmptyStr(query)) {
        url += "&name=" + query;
      }

      this.$http.get(url).then(response => {
        this.supplierList = response.data;
      });
    },
    gotoProjectStatistic(row) {
      /* 查看项目统计 */
      let url = "/print/project/statistic/" + row.orgId + "/" + row.examId;
      this.$router.push({ path: url });
    },
    editProjectSetting() {
      /* 保存项目设置 */
      this.$refs.projectSettingForm.validate(valid => {
        if (!valid) {
          return false;
        }
        this.selectPmName(this.projectSettingForm.pmId);

        this.selectSupplierName(this.projectSettingForm.supplierId);

        this.projectSettingForm.prepareStartTime = this.formatDateStr(
          this.projectSettingForm.prepareStartTime
        );
        this.projectSettingForm.prepareEndTime = this.formatDateStr(
          this.projectSettingForm.prepareEndTime
        );
        this.projectSettingForm.printStartTime = this.formatDateStr(
          this.projectSettingForm.printStartTime
        );
        this.projectSettingForm.printEndTime = this.formatDateStr(
          this.projectSettingForm.printEndTime
        );
        this.projectSettingForm.mailStartTime = this.formatDateStr(
          this.projectSettingForm.mailStartTime
        );
        this.projectSettingForm.mailEndTime = this.formatDateStr(
          this.projectSettingForm.mailEndTime
        );

        let url = PRINT_API + "/printing/project/update";
        this.$http.post(url, this.projectSettingForm).then(
          () => {
            this.$notify({
              type: "success",
              message: "项目设置成功！"
            });
            this.projectSettingDialog = false;
            this.searchRecords();
          },
          error => {
            console.log(error);
            this.$notify({
              message: "项目设置失败！",
              type: "error"
            });
          }
        );
      });
    },
    openProjectSettingDialog(row) {
      /* 打开项目设置弹窗 */
      this.projectSettingDialog = true;
      this.projectSettingForm.id = row.id;
      this.projectSettingForm.orgId = row.orgId;
      this.projectSettingForm.examId = row.examId;
      this.projectSettingForm.pmId = row.pmId;
      this.projectSettingForm.pmName = row.pmName;
      this.projectSettingForm.supplierId = row.supplierId;
      this.projectSettingForm.supplierName = row.supplierName;

      if (row.prepareStartTime) {
        this.projectSettingForm.prepareStartTime = new Date(
          row.prepareStartTime
        );
      } else {
        this.projectSettingForm.prepareStartTime = "";
      }
      if (row.prepareEndTime) {
        this.projectSettingForm.prepareEndTime = new Date(row.prepareEndTime);
      } else {
        this.projectSettingForm.prepareEndTime = "";
      }
      if (row.printStartTime) {
        this.projectSettingForm.printStartTime = new Date(row.printStartTime);
      } else {
        this.projectSettingForm.printStartTime = "";
      }
      if (row.printEndTime) {
        this.projectSettingForm.printEndTime = new Date(row.printEndTime);
      } else {
        this.projectSettingForm.printEndTime = "";
      }
      if (row.mailStartTime) {
        this.projectSettingForm.mailStartTime = new Date(row.mailStartTime);
      } else {
        this.projectSettingForm.mailStartTime = "";
      }
      if (row.mailEndTime) {
        this.projectSettingForm.mailEndTime = new Date(row.mailEndTime);
      } else {
        this.projectSettingForm.mailEndTime = "";
      }
    },
    closeProjectSettingDialog() {
      /* 关闭项目设置弹窗 */
      this.projectSettingDialog = false;
    },
    selectPmName(key) {
      /* 处理项目经理名称 */
      if (this.isEmptyNumber(key)) {
        return;
      }
      let obj = {};
      obj = this.pmList.find(function(item) {
        return item.id === key;
      });
      this.projectSettingForm.pmName = obj.name;
    },
    selectSupplierName(key) {
      /* 处理供应商名称 */
      if (this.isEmptyNumber(key)) {
        return;
      }
      let obj = {};
      obj = this.supplierList.find(function(item) {
        return item.id === key;
      });
      this.projectSettingForm.supplierName = obj.name;
    }
  },
  computed: {
    ...mapState({ user: state => state.user })
  },
  created() {
    this.loadOrgList();

    this.loadUserRole(this.user);

    if (this.curUserRole.isSuperLeader) {
      this.hasPermit = true;
      this.searchPmList();
      this.searchSupplierList();
    } else if (this.curUserRole.isPM) {
      this.hasPermit = true;
      this.loadPmInfo(this.user);
    } else if (this.curUserRole.isSupplier) {
      this.hasPermit = false;
      this.loadSupplierInfo(this.user);
    } else {
      this.hasPermit = false;
    }
  }
};
</script>

<style scoped>
.page {
  margin-top: 10px;
}
.pull-right {
  float: right;
}
.pull-left {
  float: left;
}
.w220 {
  width: 220px;
}
</style>
