<template>
  <div class="container">
    <el-row :gutter="20">
      <el-col :xl="12" :lg="12" :md="12" :sm="12" :xs="24">
        <el-form
          ref="form"
          :model="projectFrom"
          label-width="120px"
          :rules="rules"
        >
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="projectFrom.projectName"></el-input>
          </el-form-item>
          <el-form-item label="项目编号" prop="projectNumber">
            <el-input v-model="projectFrom.projectNumber"></el-input>
          </el-form-item>
          <el-form-item label="项目合同金额" prop="projectAmount">
            <el-input v-model="projectFrom.projectAmount"></el-input>
          </el-form-item>
          <el-form-item label="项目总收入" prop="projectIncome">
            <el-input v-model="projectFrom.projectIncome" disabled></el-input>
          </el-form-item>
          <el-form-item label="项目总支出" prop="projectExpend">
            <el-input v-model="projectFrom.projectExpend" disabled></el-input>
          </el-form-item>
          <el-form-item label="项目总报销" prop="projectExpense">
            <el-input v-model="projectFrom.projectExpense" disabled></el-input>
          </el-form-item>
          <el-form-item label="项目合作方" prop="projectPartyb">
            <el-input v-model="projectFrom.projectPartyb"></el-input>
          </el-form-item>
          <el-form-item label="项目时间" prop="timeSlot">
            <el-date-picker
              v-model="projectFrom.timeSlot"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="time"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="项目详情" prop="projectInformation">
            <el-input
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 6 }"
              placeholder="请输入内容"
              v-model="projectFrom.projectInformation"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button
              type="success"
              icon="el-icon-upload2"
              @click="submitForm()"
              >提交</el-button
            >
            <el-button
              type="info"
              icon="el-icon-refresh-left"
              @click="resetForm()"
              >重置信息</el-button
            >
            <el-button @click="back()">返回</el-button>
          </el-form-item>
        </el-form>
      </el-col>

      <el-col :xl="12" :lg="12" :md="12" :sm="12" :xs="24">
        <div>
          负责人：
          <el-tag
            :key="index"
            v-for="(projectLeader, index) in userIdAdd"
            closable
            :disable-transitions="false"
            @close="delectTag(index)"
            style="margin: 0px 10px"
            >{{ projectLeader }}</el-tag
          >
        </div>
        <div class="projectLeader">
          <div style="marrgin">选择区：</div>
          <div style="padding: 20px">
            角色：
            <el-select
              v-model="personListForm.rlId"
              placeholder="请选择"
              @change="selsetperson()"
            >
              <el-option
                v-for="item in rolesList"
                :key="item.rlId"
                :label="item.rlName"
                :value="item.rlId"
              ></el-option>
            </el-select>
            <div class="personList">
              <el-checkbox-group v-model="projectLeaderList">
                <el-checkbox
                  :label="ch.userId"
                  v-for="ch in checkList"
                  :key="ch.userId"
                  style="margin: 10px 20px"
                  @change="AddSelect(ch)"
                  >{{ ch.userName }}</el-checkbox
                >
              </el-checkbox-group>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { insert } from "@/api/project";
import { selectAllByCompanyId, insertBatch, secletAllByRlid } from "@/api/role";
import { money, account_password_valid } from "@/utils/myValidate";
export default {
  data() {
    return {
      //查询员工的数组
      checkList: [],
      //收集查询员工数据
      list: {
        rlId: 0,
        companyId: 0,
      },
      //添加负责人数组
      insertBatch: [],
      projectFrom: {
        projectName: null,
        projectNumber: null,
        projectAmount: null,
        projectIncome: 0,
        projectExpend: 0,
        projectExpense: 0,
        projectStartTime: null,
        projectEndTime: null,
        projectFile: null,
        userId: null,
        companyId: null,

        projectPartyb: null,
        projectInformation: null,

        timeSlot: null,
      },
      rules: {
        projectName: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
        ],
        projectNumber: [{ validator: account_password_valid, trigger: "blur" }],
        projectAmount: [
          {
            required: true,
            validator: money,
            trigger: "change",
          },
        ],
        timeSlot: [
          { required: true, message: "请选择日期", trigger: "change" },
        ],

        projectPartyb: [
          {
            required: true,
            message: "请输入项目合作方",
            trigger: "blur",
          },
        ],
      },
      isgetrules: false,
      //显示tag
      projectLeaderList: [],
      rolesList: [], //角色列表
      personList: [], //员工列表
      //收集userId
      userIdAdd: [],
      personListForm: {
        rlId: null,
      },
    };
  },
  created() {
    this.projectFrom.userId = this.$store.getters.urId;
    this.projectFrom.companyId = this.$store.getters.companyId;
    this.getRoleList();
  },
  methods: {
    //获取公司全部角色
    getRoleList() {
      selectAllByCompanyId({ companyId: this.$store.getters.companyId })
        .then((res) => {
          if (res.success) {
            this.rolesList = res.data;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((error) => {
          this.$message.error("查询数据失败");
        });
      //添加负责人
    },
    //查询员工
    async selsetperson() {
      this.list.rlId = this.personListForm.rlId;
      this.list.companyId = this.$store.getters.companyId;
      let result = await secletAllByRlid(this.list);
      if (result.success) {
        this.checkList = result.data;
      }
    },
    //删除
    delectTag(index) {
      this.projectLeaderList.splice(index, 1);
      this.userIdAdd.splice(index, 1);
    },
    AddSelect(row) {
      if (this.projectLeaderList.indexOf(row.userId) > -1) {
        this.userIdAdd.push(row.userName);
      } else {
        let index = this.userIdAdd.indexOf(row.userName);
        this.userIdAdd.splice(index, 1);
      }
    },
    //时间处理
    time(val) {
      if (val == null) {
        this.projectFrom.projectStartTime = null;
        this.projectFrom.projectEndTime = null;
      } else {
        this.projectFrom.projectStartTime = this.timestampToTime(val[0]);
        this.projectFrom.projectEndTime = this.timestampToTime(val[1]);
      }
    },
    //重置数据
    resetForm() {
      this.$refs.form.resetFields();
    },
    //提交数据
    submitForm() {
      //第一步校验数据完整性
      this.$refs.form.validate((valid) => {
        if (this.projectLeaderList.length < 1) {
          this.$message.warning("请选择项目负责人");
        } else if (valid) {
          //第四步提交
          insert(this.projectFrom)
            .then((res) => {
              if (res.success) {
                let dateadd = [];
                this.projectLeaderList.forEach((item) => {
                  dateadd.push({
                    userId: item,
                    projectId: res.data,
                    memberPression: 0,
                  });
                });
                insertBatch(dateadd).then((res) => {
                  if (res.success) {
                    this.$message.success("新建成功");
                    this.back();
                  } else {
                    this.$message.error("发生错误");
                  }
                }).catch(e=>{
                  this.$message.error("提交失败");
                })
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch((error) => {
              this.$message.error(error.msg);
            });
        }
      });
    },
    //返回
    back() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push("/projectList");
    },
    //时间处理
    timestampToTime(date) {
      var Y = date.getFullYear() + "-";
      var M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      var h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var m =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },
  },
};
</script>

<style scoped>
.container {
  padding: 10px;
}
.projectLeader {
  width: 100%;
  border: 1px solid black;
  margin: 20px 0px;
  padding: 20px;
  border-radius: 20px;
  box-shadow: 1px 1px 1px black;
}
.personList {
  margin-top: 20px;
  width: 400px;
}
</style>