<template>
  <div class="cooperator">
    <div class="left whiteBlock">
      <vue-scroll style="height: 95%">
        <div class="title">日期</div>
        <ul>
          <li
            class="el-menu-item2"
            :class="checkedId == item.id ? 'checked_item' : ''"
            v-for="(item, index) in centerModuleList"
            @click="selectMenu(item)"
            :key="index"
          >
            {{ item.name }}
          </li>
        </ul>
      </vue-scroll>
    </div>
    <div class="fullHeight right">
      <div
        class="searchBox whiteBlock"
        style="justify-content: space-between"
        v-if="dialogFormVisible"
      >
        <div class="title">节目单</div>
        <el-form
          :inline="true"
          ref="searchForm"
          :model="searchForm"
          size="medium"
        >
          <!-- 人员名称 -->
          <!-- <el-form-item label="操作员名称" prop="userName">
            <el-input
              v-model="searchForm.userName"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item> -->
          <!-- 时间 -->
          <!-- <el-form-item label="操作时间">
            <el-date-picker
              v-model="searchForm.timeRange"
              clearable
              type="daterange"
              range-separator="至"
              value-format="yyyy-MM-dd"
              :start-placeholder="'开始日期'"
              :end-placeholder="'结束日期'"
            >
            </el-date-picker>
          </el-form-item> -->
          <!-- 条件查询按钮 -->
          <el-form-item>
            <!-- <el-button type="primary" plain @click="searchList">查询</el-button> -->
            <el-button type="warning" plain @click="refresh">刷新</el-button>
            <el-button type="primary" plain @click="addProgram()">
              新增节目
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="table_wrap whiteBlock" v-if="dialogFormVisible">
        <el-table class="tables" v-loading="loading" :data="tableData">
          <el-table-column label="节目名称" align="center" prop="programName" />
          <el-table-column label="播放文件" align="center" prop="fileName">
            <template slot-scope="scope">
              <a :href="scope.row.filePath" target="_blank">{{
                scope.row.fileName
              }}</a>
            </template>
          </el-table-column>
          <el-table-column label="节目排序" align="center" prop="sort" />
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <div class="tableBtns">
                <div
                  @click.stop="editProgram(scope.row)"
                  class="operationText"
                  style="
                    margin-right: 10px !important;
                    margin-left: 20px !important;
                  "
                >
                  <img
                    src="@/assets/images/icon-edit.png"
                    width="15px"
                    height="15px"
                  />
                  <span>编辑</span>
                </div>
                <div @click.stop="deleteDev(scope.row)" class="operationText">
                  <img
                    src="@/assets/images/icon-delete.png"
                    width="15px"
                    height="15px"
                  />
                  <span>删除</span>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="pagerBox"
          @size-change="SizeChange"
          @current-change="CurrentChange"
          :current-page="pageInfo.pageNo"
          :page-sizes="$store.state.PAGESIZRS"
          :page-size="pageInfo.pageSize"
          layout="total, sizes, prev, pager, next"
          :total="Number(pageInfo.total)"
          background
        ></el-pagination>
      </div>
    </div>
    <el-dialog
      :modal-append-to-body="false"
      :title="title"
      :visible.sync="dialogShow"
      @close="close"
    >
      <div class="dialog_content">
        <el-form
          ref="form"
          :model="addForm"
          :rules="rules"
          label-width="150px"
          size="medium"
        >
          <el-form-item label="节目名称：" prop="programName">
            <el-input
              placeholder="请输入节目名称"
              v-model="addForm.programName"
            ></el-input>
          </el-form-item>
          <el-form-item label="文件类型：" prop="fileType">
            <el-radio-group v-model="addForm.fileType">
              <el-radio :label="1">视频</el-radio>
              <el-radio :label="2">图片</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="fileList">
            <div class="videoBtn">
              <div class="videoInner">
                <el-upload
                  ref="upload"
                  class="upload-demo"
                  :action="$store.state.UPLOADURL"
                  :on-success="(file) => handleSuccess(file)"
                  :on-remove="(file) => handleRemove(file)"
                  :beforeUpload="handleBeforeUploadVideo"
                  name="files"
                  :file-list="addForm.fileList"
                >
                  <el-button type="primary" size="medium"
                    >上传<i class="el-icon-upload"></i
                  ></el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      {{
                        addForm.fileType == 1
                          ? "仅支持mp4格式"
                          : "支持图片格式"
                      }}
                    </div>
                  </template>
                </el-upload>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="节目排序：" prop="sort">
            <el-input-number
              v-model="addForm.sort"
              :step="1"
              step-strictly
            ></el-input-number>
          </el-form-item>
          <el-form-item
            v-if="addForm.fileType == 2"
            label="图片显示定时："
            prop="showTime"
          >
            <div style="display: flex">
              <el-input
                placeholder="请输入"
                type="number"
                v-model="addForm.showTime"
                style="width: 140px"
              ></el-input>
              <el-select
                v-model="addForm.showUnit"
                placeholder="请选择"
                style="width: 140px; margin-left: 10px"
              >
                <el-option
                  v-for="item in optionTime"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </el-form-item>

          <div class="dialog-footer">
            <el-button
              @click="dialogShow = false"
              size="medium"
              icon="el-icon-circle-close"
              >取 消</el-button
            >
            <el-button
              type="primary"
              @click="editSave('form')"
              :loading="isloading"
              size="medium"
              icon="el-icon-circle-check"
              >确 定</el-button
            >
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getLiveScreenProgramPage,
  getLiveScreenProgramAdd,
  getLiveScreenProgramEdit,
  getLiveScreenProgramDelete,
} from "@/assets/js/api/largeScreen";
export default {
  mounted() {},
  created() {
    this.selectNowDate();
    this.getList();
  },
  data() {
    return {
      devSn: "",
      // 遮罩层
      loading: false,
      pageInfo: {
        pageNo: 1, //页数
        pageSize: 10, //条数
        total: 0, //总条数
      },
      searchForm: {
        userName: "",
        operModul: "",
        timeRange: [],
      },
      tableData: [],
      dialogFormVisible: true,
      dialogTitle: "",
      detailRow: {},
      formLabelWidthDetail: "110px",
      checkedId: 1,
      centerModuleList: [
        { id: 1, name: "周一" },
        { id: 2, name: "周二" },
        { id: 3, name: "周三" },
        { id: 4, name: "周四" },
        { id: 5, name: "周五" },
        { id: 6, name: "周六" },
        { id: 7, name: "周日" },
      ],
      addForm: {
        id: "",
        fileType: 1,
        sort: 0,
        programName: "",
        fileList: [],
        showTime: "",
        showUnit: 1,
      }, //表单
      oldFileType: 0,
      oldFileList: [],
      rules: {
        programName: [
          { required: true, message: "请输入节目名称", trigger: "blur" },
        ],
        fileList: [
          { required: true, message: "请上传文件", trigger: "blur" },
        ],
        fileType: [
          { required: true, message: "请上传文件类型", trigger: "change" },
        ],
        showTime: [
          { required: true, message: "请输入定时时间", trigger: "blur" },
        ],
      },
      isloading: false,
      title: "",
      dialogShow: false,
      dialogInfo: {
        postData: "",
        videoUploadList: [
          { id: 1, title: "周一" },
          { id: 1, title: "周二" },
          { id: 1, title: "周三" },
          { id: 1, title: "周四" },
          { id: 1, title: "周五" },
          { id: 1, title: "周六" },
          { id: 1, title: "周日" },
        ],
      },
      optionTime: [
        {
          value: 1,
          label: "秒",
        },
        {
          value: 2,
          label: "分",
        },
        {
          value: 3,
          label: "时",
        },
      ],
    };
  },
  watch: {
    "addForm.fileType": {
      handler(newVal, oldVal) {
        console.log(11111111, this.oldFileType.length, this.addForm.fileList);
       if(this.oldFileType == newVal) {
         this.addForm.fileList = this.oldFileList;
       }else {
        this.addForm.fileList = [];
       }
        // this.addForm.fileList = [];
      },
      deep: true,
    },
  },
  methods: {
    editSave(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.isloading = true;
          const data = {
            id: this.addForm.id,
            dayOfWeek: this.checkedId,
            fileName: this.addForm.fileList[0].name,
            filePath: this.addForm.fileList[0].url,
            fileType: this.addForm.fileType,
            programName: this.addForm.programName,
            projectSn: this.$store.state.projectSn,
            showTime: this.addForm.showTime,
            showUnit: this.addForm.showUnit,
            sort: this.addForm.sort,
          };
          const isEditAdd = data.id
            ? getLiveScreenProgramEdit(data)
            : getLiveScreenProgramAdd(data);

          isEditAdd
            .then((res) => {
              if (res.success) {
                this.getList();
                this.$message({
                  type: "success",
                  message: data.id ? "编辑成功!" : "添加成功!",
                });
                this.dialogShow = false;
              } else {
                this.$message({
                  type: "error",
                  message: res.message,
                });
              }
            })
            .finally(() => {
              this.isloading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    addProgram() {
      this.title = "新增节目";
      this.dialogShow = true;
      this.addForm = {
        id: "",
        fileType: 1,
        sort: 0,
        programName: "",
        fileList: [],
        showTime: "",
        showUnit: 1,
      }; //表单
      this.oldFileType = 0;
      this.oldFileList = [];
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    editProgram(obj) {
      this.title = "编辑节目";
      console.log(obj);
      this.addForm = {
        ...obj,
        fileList: [
          {
            name: obj.fileName,
            url: obj.filePath,
          },
        ],
      };
      this.oldFileType = obj.fileType;
      this.oldFileList = this.addForm.fileList;
      this.dialogShow = true;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    deleteDev(obj) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          getLiveScreenProgramDelete({ id: obj.id }).then((res) => {
            if (res.success) {
              this.getList();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            } else {
              this.$message({
                type: "error",
                message: res.message,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //切换 单位类型
    selectMenu(value) {
      console.log("切换菜单", value);
      this.checkedId = value.id;
      this.getList();
    },
    goBack() {
      this.dialogFormVisible = true;
    },
    deilBtn(val) {
      console.log("!!!!!!!!!!!!!!!!!!", val);
      this.dialogFormVisible = false;
      // 详细
      this.dialogTitle = "详细";
      this.detailRow = val;
    },
    handleSuccess(file) {
      if (file.code == 200 || file.status == "SUCCESS") {
        console.log(file, "上传成功");
        this.addForm.fileList = [
          {
            name: file.data[0].fileInfo.originalFilename
              ? file.data[0].fileInfo.originalFilename
              : file.data[0].fileInfo.filename,
            url: this.$store.state.FILEURL + file.data[0].imageUrl,
          },
        ];
        this.$refs.form.clearValidate("fileList");
        console.log(this.addForm.fileList);
      }
    },
    handleRemove(file, index){
      const findIndex = this.addForm.fileList.findIndex(item => item.uid == file.uid);
      if(findIndex > -1) {
        this.addForm.fileList.splice(findIndex, 1);
        this.oldFileList = this.addForm.fileList;
      }
      // console.log(file.uid, index);
    },
    handleBeforeUploadVideo(file) {
      console.log(file, "上传之前");
      // let fileType = file.type.split("/")[0];
      // const imageType = ["image/jpeg", "image/png"];
      // imageType.includes(file.type)
      if (
        (file.type == "video/mp4" && this.addForm.fileType == 1) ||
        (file.type.includes("image") && this.addForm.fileType == 2)
      ) {
        return true;
      } else {
        this.$message({
          showClose: true,
          message:
            this.addForm.fileType == 1
              ? "请选择正确的视频文件"
              : "请选择正确的图片文件",
          type: "warning",
        });
        return false;
      }
    },
    close() {
      this.addForm = {
        fileType: 1,
        sort: 0,
        programName: "",
        fileList: [],
      }; //表单
    },
    // 获取当前时间 返回YYYY-MM-DD HH:mm:ss
    selectNowDate() {
      var date = new Date(),
        year = date.getFullYear(),
        month = date.getMonth() + 1,
        day = date.getDate(),
        hours = date.getHours(), //获取当前小时数(0-23)
        minutes = date.getMinutes(), //获取当前分钟数(0-59)
        seconds = date.getSeconds();
      month >= 1 && month <= 9 ? (month = "0" + month) : "";
      day >= 0 && day <= 9 ? (day = "0" + day) : "";
      hours >= 0 && hours <= 9 ? (hours = "0" + hours) : "";
      minutes >= 0 && minutes <= 9 ? (minutes = "0" + minutes) : "";
      seconds >= 0 && seconds <= 9 ? (seconds = "0" + seconds) : "";
      // var timer = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes+ ':' + seconds;
      var timer = year + "-" + month + "-" + day;
      this.searchForm.timeRange = [timer, timer];
      console.log(timer);
      // return timer;
    },
    //查询列表
    getList() {
      let requestData = {
        sn: this.$store.state.projectSn,
        // sn: this.$store.state.userInfo.sn || this.$store.state.userInfo.headquartersSn,
        pageNo: this.pageInfo.pageNo,
        pageSize: this.pageInfo.pageSize,
        dayOfWeek: this.checkedId,
        // projectSn: this.$store.state.projectSn,
        // userName: this.searchForm.userName,
        // operModul: this.searchForm.operModul,
      };
      // if (this.$store.state.userInfo.accountType == 6) {
      //   requestData.operUserId = this.$store.state.userInfo.userId;
      // }
      // if (this.searchForm.timeRange && this.searchForm.timeRange.length > 0) {
      //   requestData.startTime = this.searchForm.timeRange[0];
      //   requestData.endTime = this.searchForm.timeRange[1];
      // }
      getLiveScreenProgramPage(requestData).then((result) => {
        if (result.success) {
          console.log(result);
          this.tableData = result.result.records;
          this.pageInfo.total = result.result.total;
        }
      });
    },
    SizeChange(val) {
      this.pageInfo.pageSize = val;
      this.getList();
    },
    CurrentChange(val) {
      this.pageInfo.pageNo = val;
      this.getList();
    },
    searchList() {
      this.pageInfo.pageNo = 1; //页数
      this.getList();
    },
    refresh() {
      this.searchForm = {};
      this.pageInfo.pageNo = 1; //页数
      this.pageInfo.pageSize = 10; //条数
      this.getList();
    },
    //选择条数
    handleSizeChange(val) {
      this.pageSize2 = val;
      this.getPageList();
    },
    //选择分页
    handleCurrentChange(val) {
      this.pageNo2 = val;
      this.getPageList();
    },
  },
};
</script>
<style lang="less" scoped>
a:link {
  text-decoration: none;
  cursor: pointer;
  color: #1684fc;
}
a:visited,
a:active {
  cursor: pointer;
  color: #1684fc;
}

.videoInner {
  margin-top: 10px;
}
.title {
  padding: 10px;
  font-size: 16px;
  font-weight: bold;
}
.cooperator {
  width: 100%;
  height: 100%;
  display: flex;
  .left {
    height: 100%;
    width: 16%;
    font-size: 15px;
    .el-menu-item2 {
      border-bottom: 2px #ebf0fc solid;
      height: 43px;
      line-height: 43px;
      padding: 0 30px !important;
      cursor: pointer;
    }
    .checked_item {
      border-left: 3px solid #5181f6;
      padding: 0 27px !important;
      background-color: #e1e8fa !important;
    }
  }
  .right {
    height: 100%;
    width: 84%;
    margin-left: 10px;
  }
}
.form-box {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  max-height: calc(100% - 50px);
  overflow-y: scroll;

  /deep/.el-form-item {
    width: 50%;
    padding-right: 10px;
    box-sizing: border-box;
  }

  // /deep/.el-col-12{
  //     padding-left: 20px;
  // }
  /deep/.el-input__inner {
    width: 100%;
  }

  /deep/.el-select {
    width: 100%;
  }

  /deep/.el-cascader {
    width: 100%;
  }
}
// 美化滚动条
.form-box::-webkit-scrollbar {
  width: 5px;
  height: 5px;
}

.form-box::-webkit-scrollbar-track {
  width: 6px;
  background: rgba(#101f1c, 0.1);
  -webkit-border-radius: 2em;
  -moz-border-radius: 2em;
  border-radius: 2em;
}

.form-box::-webkit-scrollbar-thumb {
  background-color: rgba(144, 147, 153, 0.5);
  background-clip: padding-box;
  min-height: 28px;
  -webkit-border-radius: 2em;
  -moz-border-radius: 2em;
  border-radius: 2em;
  transition: background-color 0.3s;
  cursor: pointer;
}

.form-box::-webkit-scrollbar-thumb:hover {
  background-color: rgba(144, 147, 153, 0.3);
}

.tables {
  min-height: 0;
  max-height: calc(100% - 56px);
}
.table_wrap {
  position: relative;
}
.pagerBox {
  margin-top: 0;
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
}
.backText {
  padding: 8px 0;
  padding-left: 10px;

  /deep/.el-page-header__content {
    font-size: 14px;
  }
}
.dark {
  /deep/.el-page-header__content {
    color: #fff;
  }

  /deep/ .print-btn {
    background: none;
    color: #262d47;
    font-size: 14px;
  }
}
</style>
