<template>
  <div class="fullHeight">
    <div v-if="type != 'detail'">
      <div class="searchBox whiteBlock">
        <el-form
          :inline="true"
          size="medium"
          :model="queryInfo"
          class="demo-form-inline"
        >
          <el-form-item>
            <el-button class="expintBtn" size="medium" type="primary" @click="addBefore"
              >
              <!-- 新增 -->
              {{$t('message.projectManage.add')}}
            </el-button>
            <!-- <el-button size="medium" type="primary"
              >
              导入
            </el-button> -->
            <!-- 2022.10.26  此处注释 不确定需求-->
            <!-- <el-upload
              class="upload-demo expintBtn"
              :action="uploadUrl"
              :file-list="fileList"
              show-file-list="false">
            <el-button size="medium" type="primary">导入</el-button>
            </el-upload> -->
          </el-form-item>
        </el-form>
      </div>
      <div class="table_wrap whiteBlock">
        <vue-scroll>
          <el-table
            class="tables"
            :data="listData"
            row-key="tempBranchId"
            default-expand-all
            :tree-props="{ children: 'children', hasChildren: 'id' }"
          >
            <el-table-column
              prop="branchProjectName"
              :label="$t('message.projectManage.NameOfSubProject')"
            >
              <template slot-scope="scope">
                {{
                  scope.row.id
                    ? scope.row.subitemProjectName
                    : scope.row.branchProjectName
                }}
              </template>
            </el-table-column>
            <!-- 计划开始日期 -->
            <el-table-column prop="branchStartTime" :label="$t('message.projectManage.planStartDate')">
              <template slot-scope="scope">
                {{
                  scope.row.id ? scope.row.startTime : scope.row.branchStartTime
                }}
              </template>
            </el-table-column>
            <!-- 预计完成日期 -->
            <el-table-column prop="endTime" :label="$t('message.projectManage.predictCompleteDate')">
              <template slot-scope="scope">
                {{ scope.row.id ? scope.row.endTime : scope.row.branchEndTime }}
              </template>
            </el-table-column>
            <!-- 实际完成日期 -->
            <el-table-column
              prop="actualEndTime"
              :label="$t('message.projectManage.realCompleteDate')"
            ></el-table-column>
            <!-- 负责人 -->
            <el-table-column
              prop="personChargeName"
              :label="$t('message.projectManage.principal')"
            ></el-table-column>
            <el-table-column
              prop="progressRatio"
              :label="$t('message.projectManage.progressRatio')"
            ></el-table-column>
            <!-- 状态 -->
            <el-table-column prop="state" :label="$t('message.projectManage.status')">
              <template slot-scope="scope">
                <el-tag
                  v-show="
                    (scope.row.id && scope.row.state == 0) ||
                    scope.row.branchState == 0
                  "
                  type="info"
                  effect="plain"
                  size="medium"
                >
                  <!-- 未开始 -->
                  {{$t('message.projectManage.notStart')}}
                </el-tag>
                <el-tag
                  v-show="
                    (scope.row.id && scope.row.state == 1) ||
                    scope.row.branchState == 1
                  "
                  type="warning"
                  effect="plain"
                  size="medium"
                >
                  <!-- 进行中 -->
                  {{$t('message.projectManage.underway')}}
                </el-tag>
                <el-tag
                  v-show="
                    (scope.row.id && scope.row.state == 2) ||
                    scope.row.branchState == 2
                  "
                  type="success"
                  effect="plain"
                  size="medium"
                >
                  <!-- 已完成 -->
                   {{$t('message.projectManage.completed')}}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column width="300">
              <template slot-scope="scope">
                <div class="tableBtns">
                  <!-- <div @click="editBefore(scope.row)" class="operationText">
                    <span>{{ $t("message.markRoomOverview.addSon") }}</span>
                </div> -->
                  <div
                    @click="editBefore(scope.row)"
                    v-if="scope.row.state != 2 && scope.row.branchState != 2"
                    class="operationText"
                  >
                    <img
                      src="@/assets/images/icon-edit.png"
                      width="15px"
                      height="15px"
                    />
                    <span>{{ $t("message.workType.edit") }}</span>
                  </div>
                  <div @click="deleteBefore(scope.row)" class="operationText">
                    <img
                      src="@/assets/images/icon-delete.png"
                      width="15px"
                      height="15px"
                    />
                    <span>{{ $t("message.workType.delete") }}</span>
                  </div>
                  <el-button
                    v-if="!scope.row.id"
                    size="small"
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    class="operationText"
                    @click="addSublevel(scope.row)"
                    >
                    <!-- 子分项工程 -->
                    {{$t('message.projectManage.subProjects')}}
                    </el-button
                  >
                  <el-button
                    v-if="scope.row.id"
                    size="small"
                    type="text"
                    class="operationText"
                    @click="detailsBtn(scope.row)"
                    >
                    <!-- 详情 -->
                     {{$t('message.projectManage.detail')}}
                    </el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </vue-scroll>
      </div>
      <!-- '新增分项工程' '编辑分项工程' -->
      <el-dialog
        :modal-append-to-body="false"
        :title="
          type == 'add'
            ? $t('message.projectManage.newSubprojects')
            : type == 'edit'
            ? $t('message.projectManage.editSubprojects')
            : $t('message.projectManage.detail')
        "
        :visible.sync="dialogVisible"
        width="667px"
      >
        <div class="dialog_content">
          <el-form
            ref="addEditForm"
            label-width="140px"
            size="medium"
            class="dialogFormBox"
            :rules="addEditRules"
            :model="workerInfo"
          >
            <el-form-item :label="$t('message.projectManage.NameOfSubProject')" prop="branchProjectName">
              <el-input
                v-model="workerInfo.branchProjectName"
                :disabled="isAddSon"
                :placeholder="$t('message.workType.placeholder')"
              ></el-input>
            </el-form-item>
            <div v-if="isAddSon">
              <!-- 子分项工程名称 -->
              <el-form-item :label="$t('message.projectManage.subProjectsName')" prop="subitemProjectName">
                <el-input
                  v-model="workerInfo.subitemProjectName"
                  :placeholder="$t('message.workType.placeholder')"
                ></el-input>
              </el-form-item>
              <!-- 施工位置 -->
              <el-form-item :label="$t('message.projectManage.constructionLocation')" prop="buildPosition">
                <el-input
                  v-model="workerInfo.buildPosition"
                  :placeholder="$t('message.workType.placeholder')"
                ></el-input>
              </el-form-item>
              <!-- 任务描述 -->
              <el-form-item :label="$t('message.projectManage.taskDescription')" prop="taskDescription">
                <el-input
                  v-model="workerInfo.taskDescription"
                  :placeholder="$t('message.workType.placeholder')"
                ></el-input>
              </el-form-item>
              <!-- 预计开始日期 -->
              <el-form-item :label="$t('message.projectManage.predictStartDate')" prop="startTime">
                <!-- 选择日期 -->
                <el-date-picker
                  v-model="workerInfo.startTime"
                  type="date"
                  :placeholder="$t('message.projectManage.chooseDate')"
                  value-format="yyyy-MM-dd"
                >
                </el-date-picker>
              </el-form-item>
              <!-- 预计结束日期 -->
              <el-form-item :label="$t('message.projectManage.predictFinishDate')" prop="endTime">
                <el-date-picker
                  v-model="workerInfo.endTime"
                  type="date"
                  :placeholder="$t('message.projectManage.chooseDate')"
                  value-format="yyyy-MM-dd"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="实际完成时间" prop="actualEndTime">
                <el-date-picker
                  v-model="workerInfo.actualEndTime"
                  type="date"
                  :placeholder="$t('message.projectManage.chooseDate')"
                  value-format="yyyy-MM-dd"
                >
                </el-date-picker>
              </el-form-item>
              <!-- 重要程度 -->
              <el-form-item :label="$t('message.projectManage.degreeOfImportance')" prop="importance">
                <el-select v-model="workerInfo.importance" :placeholder="$t('message.projectManage.pleaseChoose')">
                  <el-option :value="1" :label="$t('message.projectManage.ordinary')"> </el-option>
                  <el-option :value="2" :label="$t('message.projectManage.importent')"> </el-option>
                  <el-option :value="3" :label="$t('message.projectManage.veryImportent')"> </el-option>
                </el-select>
              </el-form-item>
              <!-- 负责人 -->
              <el-form-item :label="$t('message.projectManage.principal')" prop="personCharge">
                <el-select
                  v-model="workerInfo.personCharge"
                  filterable
                  :placeholder="$t('message.projectManage.pleaseChoose')"
                >
                  <el-option
                    v-for="item in principalLsit"
                    :key="item.userId"
                    :label="item.workerName"
                    :value="item.userId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <!-- 完成状态 -->
              <el-form-item label="完成状态" prop="state">
                 <el-select v-model="workerInfo.state" placeholder="请选择">
                  <el-option label="未开始" :value="0"></el-option>
                  <el-option label="进行中" :value="1"></el-option>
                  <el-option label="已完成" :value="2"></el-option>
                 </el-select>
                </el-form-item>
              <el-form-item :label="$t('message.projectManage.accessory')" prop="fileUrl">
                <el-upload
                  class="upload-demo"
                  :action="uploadUrl"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  multiple
                  :file-list="fileList"
                  :limit="5"
                  name="files"
                >
                  <el-button size="small" type="primary" plain
                    >
                    <!-- 点击上传 -->
                    {{$t('message.projectManage.clickUpdate')}}
                    </el-button
                  >
                </el-upload>
              </el-form-item>
            </div>
            <div class="dialog-footer">
              <el-button
                class="cancleBtn"
                @click="dialogVisible = false"
                icon="el-icon-circle-close"
                size="medium"
                >{{ $t("message.personnelPosition.cancel") }}
              </el-button>
              <el-button
                type="primary"
                icon="el-icon-circle-check"
                @click="addWorker"
                size="medium"
                >{{ $t("message.personnelPosition.determine") }}
              </el-button>
            </div>
          </el-form>
        </div>
      </el-dialog>

        <!-- //查看大图 -->
    <el-dialog :modal-append-to-body="false" :visible.sync="showBigImg">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
    </div>
    <detailpage
      v-if="type=='detail'"
      :id='seedId'
      @closeDetail='closeDetailFn'
    ></detailpage>
  </div>
</template>
<script>
import {
  getProgressManageListDataApi,
  addProgressManageApi,
  addProgressItemApi,
  getPrincipalLsitApi,
  editProgressManageApi,
  editProgressItemApi,
  deleteProgressManageApi,
  deletetProgressItemApi,
} from "@/assets/js/api/scheduleInfo";
import detailpage from "./projectNodeDetail";
export default {
  components: {
    detailpage,
  },
  mounted() {},
  data() {
    return {
      fileList:[], //上传文件
      projectSn: "",
      listData: [],
      isAddSon: false,
      uploadUrl: "",
      fileUrl: "",
      dialogVisible: false, //新增弹窗
      workerInfo: {
        branchProjectName: "",
        subitemProjectName: "",
        buildPosition: "",
        taskDescription: "",
        personCharge: "",
        importance: "",
        startTime: "",
        endTime: "",
        fileUrl: "",
        actualEndTime:"", //实际完成时间
        state:'',
      },
      principalLsit: [], //负责人
      fileList: [],
      seedId:'',

      queryInfo: {},
      type: "add",
      // type: "detail",
      addEditRules: {
        branchProjectName: [
          {
            required: true,
            message: this.$t("message.personnelPosition.required"),
            trigger: "blur",
          },
        ],
        subitemProjectName: [
          {
            required: true,
            message: this.$t("message.personnelPosition.required"),
            trigger: "blur",
          },
        ],
        buildPosition: [
          {
            required: true,
            message: this.$t("message.personnelPosition.required"),
            trigger: "blur",
          },
        ],
        startTime: [
          {
            required: true,
            message: this.$t("message.personnelPosition.required"),
            trigger: "change",
          },
        ],
        endTime: [
          {
            required: true,
            message: this.$t("message.personnelPosition.required"),
            trigger: "change",
          },
        ],
        importance: [
          {
            required: true,
            message: this.$t("message.personnelPosition.required"),
            trigger: "change",
          },
        ],
        personCharge: [
          {
            required: true,
            message: this.$t("message.personnelPosition.required"),
            trigger: "change",
          },
        ],
        // {required: true, message: this.$t('message.personnelPosition.required'), trigger: "change"}
      },
      dialogImageUrl:'',
      showBigImg:false
    };
  },
  created() {
    this.projectSn = this.$store.state.projectSn;
    this.uploadUrl = this.$store.state.UPLOADURL;
    this.fileUrl = this.$store.state.FILEURL;
    this.getProgressListData();
  },
  methods: {

    //关闭详请组件
    closeDetailFn(val){
      this.type= val;
      this.getProgressListData();
  },



    //获取列表数据
    getProgressListData() {
      let data = {
        projectSn: this.projectSn,
      };
      getProgressManageListDataApi(data).then((res) => {
        if (res.code == 200) {
          console.log('获取到的列表',res)
          this.listData = res.result;
        }
      });
    },

    //新增一级按钮
    addBefore() {
      this.dialogVisible = true;
      this.isAddSon = false; //显示子级输入框
      this.type = "add";
      this.workerInfo = {
        branchProjectName: "",
        subitemProjectName: "",
        buildPosition: "",
        taskDescription: "",
        personCharge: "",
        importance: "",
        startTime: "",
        endTime: "",
        fileUrl: "",
      };
      setTimeout(() => {
        this.$refs.addEditForm.clearValidate();
      }, 300);
    },

    //新增子级
    addSublevel(val) {
      this.type = "add";
      this.isAddSon = true; //显示子级输入框
      this.dialogVisible = true;
      this.workerInfo = {
        branchProjectName: "",
        subitemProjectName: "",
        buildPosition: "",
        taskDescription: "",
        personCharge: "",
        importance: "",
        startTime: "",
        endTime: "",
        fileUrl: "",
      };
      this.getPrincipalLsit();
      this.workerInfo.branchProjectName = val.branchProjectName;
      this.workerInfo.branchId = val.branchId;
      setTimeout(() => {
        this.$refs.addEditForm.clearValidate();
      }, 300);
    },

    //获取负责人下拉
    getPrincipalLsit() {
      let data = {
        projectSn: this.projectSn,
      };
      getPrincipalLsitApi(data).then((res) => {
        if (res.code == 200) {
          this.principalLsit = res.result;
        }
      });
    },

    //点击文件时
    handlePreview(file) {
      this.showBigImg = true;
      this.dialogImageUrl = this.fileUrl+file.url;
    },

      //附件删除成功
    handleRemove(file) {
      let url = file.url;
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].url == url) {
          //删除数据
          this.fileList.splice(i, 1);
        }
      }
    },

    //上传附件 成功
    handleSuccess(res, file) {
      let data = { name: res.data[0].filename, url: res.data[0].imageUrl };
      this.fileList.push(data);

    },

    // 编辑按钮
    editBefore(val) {
      setTimeout(() => {
        this.$refs.addEditForm.clearValidate();
      }, 300);
      this.type = "edit";
      this.getPrincipalLsit();
      if (val.id) {
        val.importance = Number(val.importance);
        this.fileList = val.fileUrl ? JSON.parse(val.fileUrl) : [];
        this.workerInfo = JSON.parse(JSON.stringify(val));
        this.dialogVisible = true;
        this.isAddSon = true;
      } else {
        this.isAddSon = false;
        this.dialogVisible = true;
        this.workerInfo = {
          branchProjectName: JSON.parse(JSON.stringify(val.branchProjectName)),
          id: val.branchId,
        };
      }
    },

    //删除按钮
    deleteBefore(worker) {
      this.type = "delete";
      this.workerInfo = worker;
      let name = worker.id
        ? worker.subitemProjectName
        : worker.branchProjectName;
      this.$confirm(
        this.$t("message.personnelPosition.beaconManage.table.confirmText") +
          "【" +
          name +
          "】?",
        this.$t("message.personnelPosition.beaconManage.table.Tips"),
        {
          confirmButtonText: this.$t(
            "message.personnelPosition.confirmButtonText"
          ),
          cancelButtonText: this.$t(
            "message.personnelPosition.cancelButtonText"
          ),
          type: "warning",
        }
      )
        .then(() => {
          this.addWorker();
        })
        .catch(() => {});
    },

    //详情按钮
    detailsBtn(val) {
      this.type = "detail";
      this.seedId = val.id;
    },

    //新增 编辑 删除  保存
    addWorker() {
      if (this.type === "add") {
        this.$refs.addEditForm.validate((valid) => {
          if (valid) {
            if(this.workerInfo.state == '2' && this.workerInfo.actualEndTime == null ){
              this.$message.error('请输入实际完成时间')
            }else{
              console.log('不用')
                let data = !this.isAddSon
              ? {
                  branchProjectName: this.workerInfo.branchProjectName,
                }
              : this.workerInfo;

            data.projectSn = this.projectSn;
            if (!this.isAddSon) {
              //新增一级保存
              addProgressManageApi(data).then((result) => {
                if (result.success) {
                  this.dialogVisible = false;
                  this.$message.success(result.message);
                  this.getProgressListData();
                }
              });
            } else {
              data.fileUrl = JSON.stringify(this.fileList);
              //新增二级保存
              addProgressItemApi(data).then((res) => {
                if (res.code == 200) {
                  this.$message.success(res.message);
                  this.dialogVisible = false;
                  this.getProgressListData();
                }
              });
            }
            }           
          } else {
            return false;
          }
        });
      } else if (this.type === "edit") {
        this.$refs.addEditForm.validate((valid) => {
          console.log('this.workerInfo',this.workerInfo)
          if (valid) {
            if(this.workerInfo.state == '2' && this.workerInfo.actualEndTime == "" ){
              this.$message.error('请输入实际完成时间')
            }else{
              //赋值
            let data = this.workerInfo;
            data.projectSn = this.projectSn;
            //编辑一级
            if (!this.isAddSon) {
              editProgressManageApi(data).then((res) => {
                if (res.code == 200) {
                  this.$message.success(res.message);
                  this.dialogVisible = false;
                  this.getProgressListData();
                } else {
                  this.$message.error(res.message);
                }
              });
              //编辑二级
            } else {
              data.fileUrl = JSON.stringify(this.fileList);
              editProgressItemApi(data).then((res) => {
                if (res.code == 200) {
                  this.$message.success(res.message);
                  this.dialogVisible = false;
                  this.getProgressListData();
                } else {
                  this.$message.error(res.message);
                }
              });
            }
            }
          } else {
            return false;
          }
        });
      } else if (this.type === "delete") {
        //删除一级
        if (!this.workerInfo.id) {
          let data = {
            id: this.workerInfo.branchId,
            projectSn: this.projectSn,
          };
          deleteProgressManageApi(data).then((res) => {
            if (res.code == 200) {
              this.dialogVisible = false;
              this.$message.success(res.message);
              this.getProgressListData();
            } else {
              this.$message.error(res.message);
            }
          });
          //删除二级
        } else {
          let data = {
            id: this.workerInfo.id,
            projectSn: this.projectSn,
          };
          deletetProgressItemApi(data).then((res) => {
            if (res.code == 200) {
              this.dialogVisible = false;
              this.$message.success(res.message);
              this.getProgressListData();
            } else {
              this.$message.error(res.message);
            }
          });
        }
      }
    },
  },
};
</script>
<style lang="less" scoped>
.expintBtn{
  display: inline-block !important;
  margin-right: 10px;
}
</style>
