<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="downloadFn"
            >
              <a class="down" :href="downUrl" download>下载模板</a>
            </el-button>
            <el-upload
              class="upload-demo expintBtn"
              name="mppFile"
              :on-success="handleImportSuccess"
              :on-change="handleImportChange"
              :before-upload="beforeUpload"
              :file-list="fileList"
              :action="$http.defaults.baseURL + 'xmgl/progressTask/importData'"
              :data="{ projectSn: projectSn, createUserId: createUserId }"
              :show-file-list="false"
              :headers="headers"
            >
              <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"
            lazy
            row-key="id"
            default-expand-all
            :tree-props="{ children: 'children' }"
            @row-click="showDetail"
          >
            <!-- 分部分项工程名称 -->
            <el-table-column
              width="400"
              prop="taskName"
              :label="$t('message.projectManage.NameOfSubProject')"
            >
            </el-table-column>
            <!-- 计划开始日期 -->
            <el-table-column
              prop="startDate"
              :label="$t('message.projectManage.planStartDate')"
            >
            </el-table-column>
            <!-- 预计完成日期 -->
            <el-table-column prop="finishDate" label="计划完成日期">
            </el-table-column>
            <!-- 实际开始日期 -->
            <el-table-column prop="actualStartDate" label="实际开始日期">
            </el-table-column>
            <!-- 实际完成日期 -->
            <el-table-column
              prop="actualFinishDate"
              :label="$t('message.projectManage.realCompleteDate')"
            ></el-table-column>
            <!-- 负责人 -->
            <el-table-column
              prop="dutyUserName"
              :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="status"
              align="center"
              :label="$t('message.projectManage.status')"
            >
              <template slot-scope="scope">
                <el-tag
                  v-show="scope.row.id && scope.row.status == 0"
                  type="info"
                  effect="plain"
                  size="medium"
                >
                  <!-- 未开始 -->
                  {{ $t('message.projectManage.notStart') }}
                </el-tag>
                <el-tag
                  v-show="scope.row.id && scope.row.status == 1"
                  type="warning"
                  effect="plain"
                  size="medium"
                >
                  <!-- 进行中 -->
                  {{ $t('message.projectManage.underway') }}
                </el-tag>
                <el-tag
                  v-show="scope.row.id && scope.row.status == 2"
                  type="success"
                  effect="plain"
                  size="medium"
                >
                  <!-- 已完成 -->
                  {{ $t('message.projectManage.completed') }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column width="150" label="操作">
              <template slot-scope="scope">
                <el-button
                  @click.native.stop="editBefore(scope.row)"
                  type="text"
                >
                  <i class="el-icon-edit"></i>编辑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </vue-scroll>
      </div>
      <!-- '编辑分项工程' -->
      <el-dialog
        :modal-append-to-body="false"
        title="编辑分项工程"
        :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="taskName"
            >
              <el-input
                v-model="workerInfo.taskName"
                :disabled="isAddSon"
                :placeholder="$t('message.workType.placeholder')"
              ></el-input>
            </el-form-item>
            <!-- 预计开始日期 -->
            <el-form-item
              :label="$t('message.projectManage.predictStartDate')"
              prop="startDate"
            >
              <el-date-picker
                @change="time1"
                v-model="workerInfo.startDate"
                :picker-options="dateAfter"
                type="date"
                placeholder="计划开始日期"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
            <!-- 预计结束日期 -->
            <el-form-item
              :label="$t('message.projectManage.predictFinishDate')"
              prop="finishDate"
            >
              <el-date-picker
                @change="time2"
                v-model="workerInfo.finishDate"
                :picker-options="dateBefore"
                type="date"
                placeholder="计划完成时间"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
            <!-- 实际开始时间 -->
            <el-form-item label="实际开始时间" prop="actualStartDate">
              <el-date-picker
                v-model="workerInfo.actualStartDate"
                type="date"
                placeholder="实际开始时间"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
            <!-- 实际完成时间 -->
            <el-form-item label="实际完成时间" prop="actualFinishDate">
              <el-date-picker
                v-model="workerInfo.actualFinishDate"
                type="date"
                placeholder="实际完成时间"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
            <!-- 负责人 -->
            <el-form-item
              :label="$t('message.projectManage.principal')"
              prop="dutyUserName"
            >
              <el-select
                v-model="workerInfo.dutyUserId"
                :placeholder="$t('message.projectManage.pleaseChoose')"
              >
                <el-option
                  v-for="item in principalLsit"
                  :key="item.userId"
                  :label="item.realName"
                  :value="item.userId"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <!-- 完成状态 -->
            <el-form-item label="完成状态" prop="status">
              <el-select v-model="workerInfo.status" 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="进度" prop="progressRatio">
              <el-input
                v-model="workerInfo.progressRatio"
                :placeholder="$t('message.workType.placeholder')"
              ></el-input>
            </el-form-item>
            <!-- 任务模式 -->
            <el-form-item label="任务模式" prop="taskTypeId">
              <el-select v-model="workerInfo.taskTypeId" placeholder="请选择">
                <el-option label="手动" :value="0"></el-option>
                <el-option label="自动" :value="1"></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>
            <!-- 任务工期 -->
            <el-form-item label="任务工期" prop="duration">
              <el-input
                :disabled="workerInfo.taskTypeId == '1'"
                v-model="workerInfo.duration"
                :placeholder="$t('message.workType.placeholder')"
              ></el-input>
            </el-form-item>
            <!-- 备注 -->
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="workerInfo.remark"
                :placeholder="$t('message.workType.placeholder')"
              ></el-input>
            </el-form-item>
          </el-form>
        </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="submitBtn"
            size="medium"
            >{{ $t('message.personnelPosition.determine') }}
          </el-button>
        </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 {
  getProgressListDataApi,
  editProgressListDataApi,
  getPrincipalLsitApi
} from '@/assets/js/api/scheduleInfo'
import detailpage from './projectNodeDetail'
export default {
  components: {
    detailpage
  },
  mounted() {},
  data() {
    return {
      fileList: [], //上传文件
      downUrl: '', //下载文件地址
      projectSn: '',
      createUserId: '',
      listData: [],
      isAddSon: false,
      uploadUrl: '',
      fileUrl: '',
      dialogVisible: false, //新增弹窗
      workerInfo: {
        taskName: '',
        startDate: '',
        finishDate: '',
        actualStartDate: '',
        actualFinishDate: '',
        personCharge: '',
        status: '',
        taskTypeId: '',
        progressRatio: '',
        dutyUserId: '',
        fileUrl: '',
        duration: '',
        remark: ''
      },
      principalLsit: [], //负责人
      fileList: [],
      seedId: '',
      showTime: false, //工期
      queryInfo: {},
      type: 'add',
      // type: "detail",
      addEditRules: {
        taskName: [
          {
            required: true,
            message: this.$t('message.personnelPosition.required'),
            trigger: 'blur'
          }
        ],
        startDate: [
          {
            required: true,
            message: this.$t('message.personnelPosition.required'),
            trigger: 'blur'
          }
        ],
        finishDate: [
          {
            required: true,
            message: this.$t('message.personnelPosition.required'),
            trigger: 'blur'
          }
        ]
      },
      dialogImageUrl: '',
      showBigImg: false,
      times: '',
      // 时间限制
      pickerOptions: {
        // 对象
        disabledDate: (time) => {
          let nowData = this.times
          nowData = new Date(nowData.setDate(nowData.getDate() - 1))
          return time > nowData
          // return time.getTime() < Date.now()- 1 * 24 * 3600 * 1000;
        }
      }
    }
  },
  computed: {
    headers() {
      return { Authorization: this.$store.state.userInfo.token }
    },
    dateAfter() {
      // 动态起始时间
      const startTimestamp = Date.now() * 1 - 24 * 60 * 60 * 1000
      const endTimestamp =
        Date.parse(this.workerInfo.finishDate) * 1 - 24 * 60 * 60 * 1000
      return {
        disabledDate(time) {
          const timestamp = time.getTime()
          if (endTimestamp) {
            if (timestamp >= startTimestamp && timestamp <= endTimestamp) {
              return false
            } else {
              return true
            }
          } else {
            return timestamp <= startTimestamp
          }
        }
      }
    },
    dateBefore() {
      // 动态起始时间
      const startTimestamp = Date.parse(this.workerInfo.startDate) * 1
      return {
        disabledDate(time) {
          const timestamp = time.getTime()
          if (timestamp >= startTimestamp) {
            return false
          }
          return true
        }
      }
    }
  },
  created() {
    this.projectSn = this.$store.state.projectSn
    this.createUserId = this.$store.state.userInfo.userId
    this.uploadUrl = this.$store.state.UPLOADURL
    this.fileUrl = this.$store.state.FILEURL
    this.getProgressListData()
  },
  methods: {
    time1(val) {
      console.log('开始时间', val)
      this.times = val
    },
    time2(val) {
      console.log('结束时间', val)
    },
    // 下载模板
    downloadFn() {
      this.downUrl =
        this.$store.state.BASEURL + 'xmgl/progressTask/downloadTemplate'
      // window.location.href=this.downUrl
    },
    // 导入成功
    handleImportSuccess(res) {
      console.log('上传成功', res)
    },
    //
    beforeUpload(file) {
      console.log('=========', file)
    },
    // 上传mpp文件触发
    handleImportChange(file, fileList) {
      console.log('=[====]')
      // console.log((file, fileList))
    },

    // 点击行查看详情
    showDetail(row) {
      console.log('查详情', row)
      this.type = 'detail'
      this.seedId = row.id
    },
    //关闭详请组件
    closeDetailFn(val) {
      this.type = val
      this.getProgressListData()
    },

    //获取列表数据
    getProgressListData() {
      let data = {
        projectSn: this.projectSn
      }
      getProgressListDataApi(data).then((res) => {
        if (res.code == 200) {
          //   console.log("获取到的列表", res);
          this.listData = res.result
        }
      })
    },
    //获取负责人下拉
    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) {
      this.workerInfo = JSON.parse(JSON.stringify(val))
      console.log('当前点击的行', val)
      this.fileList = val.fileUrl ? JSON.parse(val.fileUrl) : []
      this.dialogVisible = true
      this.getPrincipalLsit()
    },
    //编辑
    submitBtn() {
      this.$refs.addEditForm.validate((valid) => {
        if (valid) {
          if (
            this.workerInfo.status == '1' &&
            this.workerInfo.actualStartDate == null
          ) {
            this.$message.error('请输入实际开始时间！')
          } else if (
            this.workerInfo.status == '2' &&
            this.workerInfo.actualFinishDate == null
          ) {
            // if (this.workerInfo.actualStartDate == null) {
            //   this.$message.error("请输入实际开始时间！");
            // } else if (this.workerInfo.actualFinishDate == null) {
            this.$message.error('请输入实际完成时间！')
            // }
          } else {
            //赋值
            let data = this.workerInfo
            data.projectSn = this.projectSn
            //   console.log('编辑的参数',data)
            editProgressListDataApi(data).then((res) => {
              if (res.code == 200) {
                this.$message.success('编辑成功！')
                this.dialogVisible = false
                this.getProgressListData()
              }
            })
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>
  <style lang="less" scoped>
.down {
  text-decoration: none;
  color: #fff;
}
.expintBtn {
  display: inline-block !important;
  margin-right: 10px;
}
.table_wrap {
  height: 800px;
  overflow: auto;
}
</style>
  