<template>
  <div>
    <el-drawer title="执行计划" :visible.sync="showDrawerTow" direction="btt" class="all-derawer" :before-close="handleClose">
      <div class="flex-box" style="height: calc(100vh - 10%);">
        <div class="drawer-left scroll-bar">
          <div class="draft-content" v-for="(item, index) in actionPlanList" :key="index">
            <div class="drawer-left-title font-flex-word">{{ item.name }}</div>
            <div
              class="drawer-item  flex-box-ce"
              :class="[activeDrawerIndex == index + '-' + index2 ? 'active-drawer-item' : '']"
              v-for="(item2, index2) in item.index"
              :key="index2"
              @click="activeItem(index, index2)"
            >
              <div style="width:200px;" class="font-flex-word">{{ item2.name }}</div>
              <div style="padding: 0 10px;" class="blue">({{ item2.schedule.length }})</div>
            </div>
          </div>
        </div>
        <div class="drawer-right scroll-bar flex-1" style="overflow: auto;background-color: #fff;">
          <div class="drawer-right-header">
            <div class="drawer-right-title">{{ indexItem.name }}</div>
            <div class="yellow" style="margin: 10px 0;">考核标准</div>
            <div class="remark">{{ indexItem.per_remark }}</div>
          </div>
          <div class="drawer-right-main">
            <div class="flex-box-ce">
              <div class="flex-1" style="font-size: 16px;">执行计划</div>
              <el-button type="primary" size="mini" @click="addPlan()" v-if="!isShowAdd && !isFill && isOperation && isCz">新增</el-button>
            </div>
          </div>
          <div class="flex-box" v-if="indexItem.schedule.length > 0">
            <div class="plan-left flex-1" style="padding-bottom: 60px;">
              <div
                class="plan-left-content flex-box"
                @click="activePlan(item, index)"
                :class="[activePlanIndex == index ? 'active-drawer-item' : '']"
                v-for="(item, index) in indexItem.schedule"
                :key="index"
              >
                <div class="plan-title flex-1">{{ item.title }}</div>
<!--                <template v-if="item.append">
                   <i v-if="item.append.length > 0" class="el-icon-picture fontColorB" style="font-size: 18px;padding-right: 10px;"></i>
                </template> -->
                <i v-if="item.append.length > 0" class="el-icon-paperclip fontColorB" style="font-size: 18px;padding-right: 10px;"></i>
                <div style="position: relative;top: 3px;">{{ item.date }}</div>
              </div>
            </div>
            <div class="plan-right flex-3">
              <div class="flex-box-end btns" v-if="isOperation && isCz">
                <el-button class="dangerBtn" size="mini" round plain @click="deletePlan()">删除</el-button>
                <el-button class="primaryBtn" size="mini" round @click="saveActionPlan()">提交</el-button>
              </div>
              <div class="plan-right-date fontColorB">{{ planData.date }}</div>
              <el-input
                type="textarea"
                @blur="inputBlur"
                @focus="inputFocus"
                @input="inputText"
                class="plan-right-title"
                rows="4"
                clearable
                ref="inputTitle"
                placeholder="请输入执行计划内容"
                v-model="planData.title"
                maxlength="200"
                show-word-limit
              ></el-input>
              <el-input
                ref="inputTitle2"
                type="textarea"
                @blur="inputBlur"
                @focus="inputFocus"
                @input="inputText"
                class="plan-textarea"
                rows="5"
                clearable
                maxlength="500"
                show-word-limit
                placeholder="选填,请输入备注"
                v-model="planData.remark"
              ></el-input>
			  <div style="margin-bottom: 20px;" class="flex-box-ce fontColorC">
			  	<el-button class="primaryBtn" icon="el-icon-paperclip" plain size="small" @click="uploadOss">附件</el-button>
			  	<div style="padding-left:10px;font-size: 12px;">附件存放在企业钉盘，请确保钉盘有足够空间</div>
			  </div>
			<div class="">
				<div v-for="(item, index) in planData.append" style="cursor: pointer;margin-bottom: 5px;" :key="index" class="blue flex-box-ce">
					<i  class="el-icon-paperclip fontColorB" style="font-size: 18px;padding-right: 10px;"></i>
					<div style="width: 400px;" class="font-flex-word" @click="openImg(item)">{{ item.fileName }}</div>
					<i class="el-icon-close fontColorB" @click="deleteFile(index)" style="font-size: 18px;padding-left: 10px;"></i>
				</div>
			</div>
			  
			  
<!--              <div class="flex-box">
                <uploadOss
                  :headers="Xtoken"
                  class="avatar-uploader"
                  :action="'https://' + 'integralsys.oss-cn-shenzhen.aliyuncs.com'"
                  :show-file-list="true"
                  :file-list="img_fileList"
                  :on-success="handleFilesSuccess"
                  :on-preview="onFilePreView"
                  :before-upload="beforeUpload"
                  :on-remove="onFileRemove"
                  :limit="3"
                  :multiple="true"
                >
                  <el-button class="primaryBtn" icon="el-icon-picture-outline" plain size="small">图片</el-button> -->
                  <!-- (最多选择3张) -->
<!--                </uploadOss>
                <div style="width: 30px;"></div>
                <uploadOss
                  class="avatar-uploader"
                  :headers="Xtoken"
                  :show-file-list="true"
                  :multiple="true"
                  ref="upload"
                  :limit="1"
                  :file-list="file_fileList"
                  :action="'https://' + 'integralsys.oss-cn-shenzhen.aliyuncs.com'"
                  :on-preview="onFilePreView2"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  :before-upload="beforeFilesUpload"
                >
                  <el-button class="primaryBtn" icon="el-icon-paperclip" plain size="small">附件</el-button> -->
                  <!-- (仅支持上传xlsx,xls,doc,docx,pdf,txt,最多一份附件) -->
<!--                </uploadOss>
              </div> -->
            </div>
          </div>
          <div v-else style="background-color: #fff;padding-top: 10px;">
            <el-alert title="执行计划用来做什么？" type="info" description show-icon>
              <div class="alert-text">
                1.可以填写如何达成指标的计划，并记录进展行动
                <br />
                2.填写的内容将给评分人作为参考
              </div>
            </el-alert>
            <NoData content="暂无执行计划" imgW="150px" imgH="100px">
              <el-button type="primary" round style="width: 100px;margin: 0 auto;margin-top: 10px;" @click="addPlan()" v-if="isOperation && isCz">
                <i class="el-icon-plus"></i>
                新建
              </el-button>
            </NoData>
          </div>
        </div>
      </div>
    </el-drawer>
    <el-dialog title="图片查看" :visible.sync="isShowImg" width="50%" >
      <img :src="imgUrl" style="width: 100%;">
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowImg = false">取 消</el-button>
        <el-button type="primary" @click="isShowImg = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import uploadOss from '@/components/public/upload';
export default {
  components: { uploadOss },
  name: 'ActionPlan',
  props: {
    id: {
      //员工考核记录的ID
      type: Number,
      default: 0
    },
    // 是否显示组件
    showDrawer: {
      type: Boolean,
      default: false
    },
    //数据源
    apList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    //默认显示的指标 [0]：维度下标，[1]:指标下标
    planIndex: {
      type: Array,
      default: () => {
        return [];
      }
    },
    //绩效考核的被考核人ID
    assessId: {
      type: Number,
      default: 0
    },
    // 是否在关闭时刷新外面的表格，和是否可以操作
    isCz: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      drawer: false,
      activeDrawerIndex: '0-0',
      actionPlanList: [],
      indexItem: {
        //选中的指标
        schedule: []
      },
      activePlanIndex: 0,
      planData: {
        //执行计划（单个）
        title: '',
        employee_id: '',
        images: [],
        append: [], //附件
        appendName: '' //附件名称
      },
      planData2: {}, //备用数据，当不修改时使用
      showDrawerTow: false,
      isFill: false, //是否填写了
      isFill2: false, //添加执行计划时用，判断是要清空添加的，还是还原编辑的数据
      isShowAdd: false,
      isOperation: false, //判断是否能操作执行计划

      selectItemIndex: 0, //维度当前下标

      // 上传图标与附件
      Xtoken: { 'X-Token': this.$getToken() },
      img_fileList: [], // 图片附件
      file_fileList: [], //文件附件
      imgs: [],
      doc: '',
      isShowImg:false,
      imgUrl:'',
    };
  },
  watch: {
    showDrawer(val) {
      this.showDrawerTow = val;
      if (val) {
        if (this.assessId == this.$getUserData().id) {
          this.isOperation = true;
        }
        this.actionPlanList = this.apList;
        this.getShowData();
      }
    }
  },
  methods: {
	deleteFile(index) {
		if (this.planData.append.length == 0) {
			this.planData.append = [];
			return false;
		}
		this.planData.append.splice(index, 1);
		this.isFill = true;
	},
	openImg(item) {
		let corpId = this.$getCache('corpId');
		let loading = this.$loading({
			lock: true,
			text: 'Loading',
			spinner: 'el-icon-loading'
			// background: 'rgba(0, 0, 0, 0.7)'
		});
		if (item) {
			this.$axios('get', 'api/drive/grant',{file_id:item.fileId}).then(res => {
				this.$dd.ready(() => {
					this.$dd.biz.cspace.preview({
						corpId: corpId,
						spaceId: item.spaceId,
						fileId: item.fileId,
						fileName: item.fileName,
						fileSize: item.fileSize,
						fileType: item.fileType,
						onSuccess: function(res) {
							console.log(JSON.stringify(res))
						},
						onFail: function(err) {
							console.log(JSON.stringify(err))
						}
					});
				});
			}).finally(()=>{
				loading.close();
			});
		}
	},
	uploadOss() {
		let that = this;
		let corpId = this.$getCache('corpId');
		this.$axios('get', 'api/drive/info').then(res => {
			let spaceId = res.data.data.space_id.toString();
			this.$dd.ready(() => {
				this.$dd.biz.util.uploadAttachment({
					image: {
						multiple: true,
						compress: false,
						max: 5,
						spaceId: spaceId
					},
					space: {
						corpId: corpId,
						spaceId: spaceId,
						max: 5
					},
					file: {
						spaceId: spaceId,
						max: 5
					},
					types: ['photo', 'file', 'space'], //PC端支持["photo","file","space"]
					onSuccess: function(res) {
						console.log(JSON.stringify(res))
						let data = res.data;
						that.planData.append.push(...data);
						that.isFill = true;
					},
					onFail: function(err) {
						console.log(JSON.stringify(err))
					}
				});
			});
		});
	},  
    // 图片上传
    beforeUpload(file) {
      const isJPG = /^image\/(jpeg|png|jpg)$/.test(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传图片只能是 jpeg|png|jpg 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    onFilePreView(file) {
      this.imgUrl=file.url;
      this.isShowImg=true;
    },
    onFilePreView2(file) {
      window.open(file.url, '_blank');
    },
    onFileRemove(file, fileList) {
      this.img_fileList = fileList;
      this.planData.images = [];
      let images = [];
      fileList.forEach((element, index) => {
        images.push({ url: element.url, name: element.name });
      });
      this.planData.images = images;
      this.isFill = true;
    },
    handleFilesSuccess(response, file, fileList) {
      this.img_fileList = fileList;
      this.planData.images = [];
      let images = [];
      fileList.forEach((element, index) => {
        images.push({ url: element.url, name: element.name });
      });
      this.planData.images = images;
      this.isFill = true;
    },

    handleSuccess(response, file, fileList) {
      this.file_fileList = fileList;
      this.planData.append = fileList[0].url;
      this.planData.append_name = fileList[0].name;
      this.isFill = true;
    },
    handleRemove(file, fileList) {
      this.file_fileList = fileList;
      this.planData.append = '';
      this.planData.append_name = '';
      this.isFill = true;
    },
    beforeFilesUpload(file) {
      const $ext_list = ['xlsx', 'xls', 'doc', 'docx', 'pdf'];
      const isLt2M = file.size / 1024 / 1024 < 5;
      let len = file.name.split('.').length - 1;
      const $ext_name = file.name.split('.')[len];
      let isFile = $ext_list.indexOf($ext_name) != -1;
      if (!isLt2M) {
        this.$message.error('文件大小不能超过 5MB!');
      }
      if (!isFile) {
        this.$message.warning('文件格式上传错误,仅支持上传xlsx,xls,doc,docx,pdf）');
      }
      return isFile && isLt2M;
    },

    deletePlan() {
      this.$confirm('确认删除执行计划：' + this.planData.title + '？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let data = {
            action_id: this.planData.id ? this.planData.id : '', //执行计划id 编辑的时候要传
            package_employee_id: this.id, //员工考核记录信息id
            index_id: this.indexItem.id, //指标id
            dimension_xb: this.selectItemIndex
          };
          if (this.planData.id) {
            this.$axios('post', 'api/per/package/action/del', data).then(res => {
              this.indexItem.schedule.splice(this.activePlanIndex, 1);
              this.activePlanIndex = 0;
              this.planData = this.indexItem.schedule[0] ? this.indexItem.schedule[0] : [];
              this.isFill = false;
              this.isFill2 = false;
              this.$message.success('删除成功');
            });
          } else {
            this.indexItem.schedule.splice(this.activePlanIndex, 1);
            this.activePlanIndex = 0;
            this.planData = this.indexItem.schedule[0] ? this.indexItem.schedule[0] : [];
            this.isFill = false;
            this.isFill2 = false;
            this.$message.success('删除成功');
          }
        })
        .catch(() => {});
    },
    // 添加
    addPlan() {
      var len = this.indexItem.schedule.length;
     this.img_fileList=[]; // 图片附件
     this.file_fileList=[]; //文件附件
      let obj = {
        date: this.$moment().format('YYYY-MM-DD'),
        title: '执行计划' + (len + 1),
        remark: '',
        images: [],
        append: [], //附件
        appendName: '' //附件名称
      };
      this.indexItem.schedule.unshift(obj);
      if (this.indexItem.schedule.length == 1) {
        this.planData = this.indexItem.schedule[0];
        this.$nextTick(() => {
          this.$refs.inputTitle.focus();
          this.isFill = true;
        });
      } else {
        this.activePlanIndex = 0;
        this.planData = this.indexItem.schedule[0];
        this.$nextTick(() => {
          this.$refs.inputTitle.focus();
          this.isFill = true;
        });
      }
      this.isFill2 = true;
    },
    // 提交执行计划
    saveActionPlan(f = function() {}) {
      if (!this.planData.title) {
        this.$message.error('请输入执行计划内容');
        return false;
      }
      this.isFill = false;
      let data = {
        action_id: this.planData.id ? this.planData.id : '', //执行计划id 编辑的时候要传
        dimension_xb: this.selectItemIndex,
        package_employee_id: this.id, //员工考核记录信息id
        index_id: this.indexItem.id, //指标id
        title: this.planData.title, //标题
        remark: this.planData.remark, //内容
		// images: JSON.stringify(this.planData.images),
		append: JSON.stringify(this.planData.append)
		// append_name: this.planData.append_name
      };
      this.$axios('post', '/api/per/package/action', data).then(res => {
        this.$message.success('填写成功');
        this.planData.id = res.data.data.id;
        f();
      });
    },
    setActivePlan(item, index) {
      this.planData = item;
      this.setFlie();
      this.activePlanIndex = index;
      this.isFill = false;
      this.isFill2 = false;
    },
    // 点击执行计划
    activePlan(item, index) {
      if (this.activePlanIndex == index) {
        return false;
      }
      if (this.isFill) {
        this.$confirm('请确认提交执行计划：' + this.planData.title + '？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.saveActionPlan(() => {
              this.setActivePlan(item, index);
            });
          })
          .catch(() => {
            if (this.isFill2) {
              this.indexItem.schedule.splice(this.activePlanIndex, 1);
              this.setActivePlan(item, index);
            } else {
              this.indexItem.schedule[this.activePlanIndex] = this.planData2;
              this.planData = this.planData2;
              this.$nextTick(() => {
                setTimeout(() => {
                  this.setActivePlan(item, index);
                }, 200);
              });
            }
          });
      } else {
        this.planData2 = JSON.parse(JSON.stringify(item));
        this.setActivePlan(item, index);
      }
    },
    setActiveItem(index, index2) {
      this.getShowData(index, index2);
      this.activeDrawerIndex = index + '-' + index2;
      this.activePlanIndex = 0;
      this.isFill = false;
      this.isFill2 = false;
    },
    // 点击指标
    activeItem(index, index2) {
      this.selectItemIndex = index;
      if (this.activeDrawerIndex == index + '-' + index2) {
        return false;
      }
      if (this.isFill) {
        this.$confirm('请确认提交执行计划：' + this.planData.title + '？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.saveActionPlan(() => {
              this.setActiveItem(index, index2);
            });
          })
          .catch(() => {
            if (this.isFill2) {
              this.indexItem.schedule.splice(this.activePlanIndex, 1);
              this.setActiveItem(index, index2);
            } else {
              this.indexItem.schedule[this.activePlanIndex] = this.planData2;
              this.planData = this.planData2;
              this.$nextTick(() => {
                setTimeout(() => {
                  this.setActiveItem(index, index2);
                }, 200);
              });
            }
          });
      } else {
        this.setActiveItem(index, index2);
      }
    },
    // 设置选中数据
    getShowData(index, index2) {
      if (index != undefined) {
        this.indexItem = this.actionPlanList[index].index[index2];
        this.planData = this.indexItem.schedule[0];
        // this.setFlie();
        if (this.planData) {
          this.planData2 = JSON.parse(JSON.stringify(this.planData));
        }
      } else {
        if (this.planIndex.length > 0) {
          //如果有指定下标展示
          this.indexItem = this.actionPlanList[this.planIndex[0]].index[this.planIndex[1]];
          this.planData = this.indexItem.schedule[0];
          this.selectItemIndex = this.planIndex[0];
          // this.setFlie();
          if (this.planData) {
            this.planData2 = JSON.parse(JSON.stringify(this.planData));
          }
          this.activeDrawerIndex = this.planIndex[0] + '-' + this.planIndex[1];
        } else {
          this.indexItem = this.actionPlanList[0].index[0];
          this.planData = this.indexItem.schedule[0];
          // this.setFlie();
          if (this.planData) {
            this.planData2 = JSON.parse(JSON.stringify(this.planData));
          }
        }
      }
    },
    setFlie() {
      this.img_fileList = [];
      this.file_fileList = [];
      if (this.planData) {
        this.img_fileList = this.planData.images;
        if (this.planData.append) {
          this.file_fileList = [{ name: this.planData.append_name, url: this.planData.append }];
        }
      }
    },
    handleClose(done) {
      this.$emit('update:showDrawer', false);
      if (this.isCz) {
        this.$emit('confirm');
      }
      this.activeDrawerIndex = '0-0';
      this.activePlanIndex = 0;
      this.showDrawerTow = false;
      this.isFill = false; //是否填写了
      this.isFill2 = false; //添加执行计划时用，判断是要清空添加的，还是还原编辑的数据
      this.isShowAdd = false;
        done();
    },
    // 监听是否填写
    inputText(val) {
      if (!this.isFill) {
        this.isFill = true;
      }
    },
    inputBlur() {
      this.isShowAdd = false;
    },
    inputFocus() {
      this.isShowAdd = true;
    }
  }
};
</script>

<style scoped="scoped">
.all-derawer ::v-deep.el-drawer {
  height: 90% !important;
  border-radius: 10px 10px 0 0;
  background-color: #f5f7fa;
  min-width: 1100px !important;
}
.all-derawer ::v-deep.el-drawer__header {
  background-color: #f5f7fa;
  padding: 12px 20px;
  margin-bottom: 0px;
  font-size: 16px;
}
::v-deep .el-upload-list__item-name {
  max-width: 250px;
}
::v-deep :focus {
  outline: 0;
}
.btns {
  position: absolute;
  right: 20px;
  top: 16px;
  z-index: 999;
}
.plan-right {
  padding: 20px;
  position: relative;
  background-color: #f5f7fa;
  min-height: 600px;
}
.plan-right-date {
  text-align: center;
  position: relative;
  margin-bottom: 30px;
}
.plan-textarea ::v-deep textarea {
  background-color: #f5f7fa;
  border: none;
}
.plan-right-title {
  border-bottom: 1px solid #f1f1f1;
}
.plan-right-title ::v-deep textarea {
  background-color: #f5f7fa;
  border: none;
}
.drawer-left {
  background-color: #fff;
  padding: 0 15px;
  width: 280px;
  border-right: 1px solid #f1f1f1;
  overflow: auto;
  padding-bottom: 60px;
}
.drawer-left-title {
  padding: 16px 0;
  font-weight: 600;
  font-size: 16px;
  color: #222;
  border-bottom: 1px solid #f1f1f1;
}
.drawer-item {
  padding: 16px 0;
  cursor: pointer;
}
.drawer-item:hover {
  background-color: #f5f7fa;
}
.drawer-left .active-drawer-item {
  background-color: #f5f7fa;
  border-right: 2px solid #409eff;
}
.plan-left-content:hover {
  background-color: #f5f7fa;
}
.plan-left .active-drawer-item {
  background-color: #f5f7fa;
}
.drawer-right-header {
  background-color: #fff;
  border-bottom: 1px solid #f1f1f1;
  padding: 20px;
}
.drawer-right-main {
  padding: 0px 20px;
  height: 50px;
  line-height: 50px;
  background-color: #fff;
  border-bottom: 1px solid #f1f1f1;
}
.plan-title {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  padding-right: 5px;
}
.plan-left {
  background-color: #fff;
  border-right: 1px solid #f1f1f1;
  overflow: auto;
}
.remark {
  height: 100px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 6;
  overflow: hidden;
}
.plan-left-content {
  border-bottom: 1px solid #f1f1f1;
  padding: 16px;
  cursor: pointer;
  box-sizing: border-box;
}
.plan-left-content div:nth-child(2) {
  font-size: 12px;
  color: #666666;
}
</style>
