<template>
  <!-- 文案素材-->
  <div class="app-container">
    <el-row style="margin-bottom: 20px">
      <el-select v-model="appId" placeholder="关联应用" filterable clearable>
        <el-option
          v-for="item in selectApps"
          :key="item.id"
          :label="item.label"
          :value="item.id"
        >
        </el-option>
      </el-select>

      <el-date-picker
        type="daterange"
        range-separator="-"
        :picker-options="pickerOptions2"
        v-model="dateTime"
        value-format="yyyy-MM-dd"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      >
        clearable
      </el-date-picker>

      <el-button type="primary" @click="APIgetBusinText">查询</el-button>

      <!-- <el-button type="primary" @click="addCopywriting">添加文案</el-button> -->
      <el-button type="danger" style="float: right" @click="Delete"
        >删除</el-button
      >
      <el-checkbox
        :indeterminate="isIndeterminate"
        style="float: right; line-height: 43px"
        v-model="checkAll"
        @change="handleCheckAllChange"
        >全选当前筛选项</el-checkbox
      >
    </el-row>

    <div style="margin-bottom: 20px">
      <!-- 添加文案 -->
      <el-input
        style="width: 500px; margin-left: 23px"
        ref="inputText"
        v-model="inputValue2"
        @keyup.enter.native="addText(inputValue2, appId)"
      >
        <template slot="append">回车添加文案</template>
      </el-input>
    </div>

    <el-checkbox-group v-model="checkedCities">
      <el-checkbox
        v-for="(inText, index) in newGetText"
        style="margin-bottom: 20px; width: 100%"
        :key="index"
        :label="inText.id"
        @change="handleCheckedCitiesChange(inText)"
      >
        <el-input
          ref="saveTagInput"
          placeholder="请输入内容"
          style="width: 500px"
          v-model="inText.text"
          @change="editCopy(inText)"
          ><el-button
            slot="append"
            @click.stop="beforeSaveText(inText.id, inText.text)"
            >保存</el-button
          ></el-input
        >
        <el-link :underline="false" type="info">{{ inText.datadate }}</el-link>
      </el-checkbox>
    </el-checkbox-group>
    <el-pagination
      background
      :total="copyWriting.total"
      :page-size="copyWriting.size"
      :current-page="copyWriting.page"
      style="text-align: right; margin-top: 20px"
      layout="total, prev, pager, next, sizes"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    ></el-pagination>

    <el-dialog :visible.sync="dialogFormVisible">
      <el-form>
        <el-form-item label="选择应用">
          <el-select
            v-model="addForm.appId"
            filterable
            placeholder="请选择"
            style="width: 200px"
          >
            <el-option
              v-for="item in selectApps"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCopy">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getBusinText,
  getBusinTextDel,
  getBusinTextEdit,
  getBusinTextAdd,
  getEnums,
  getSelectApps,
} from "@/api/cloud";
export default {
  data() {
    return {
      inputValue2: "", // 要添加的文案
      addForm: {
        appId: "",
        text: "",
      },
      dialogFormVisible: false,
      appId: "",
      selectApps: [],
      appCate: [],
      isIndeterminate: false,
      newGetText: [
        {
          text: " ",
        },
      ],
      inText: {
        text: "",
      },
      checkAll: false,
      checkedCities: [],
      copyWriting: {
        page: 1,
        size: 20,
        total: null,
      },
      newids: [],

      textBusinessCondition: {
        appCategory: "",
        startDate: "",
        endDate: "",
        dateRange: [],
      },
      pickerOptions2: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const start = new Date();
              picker.$emit("pick", [start, start]);
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, start]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  created() {
    this.APIgetBusinText();
    this.APIGetEnums();
    this.APIgetSelectApps();
  },
  computed: {
    dateTime: {
      get() {
        if (
          this.textBusinessCondition.startDate &&
          this.textBusinessCondition.endDate
        ) {
          return [
            this.textBusinessCondition.startDate,
            this.textBusinessCondition.endDate,
          ];
        } else {
          return [];
        }
      },
      set(v) {
        console.log("设置时间范围：", v);
        if (v !== null) {
          this.textBusinessCondition.startDate = v[0];
          this.textBusinessCondition.endDate = v[1];
        } else {
          this.textBusinessCondition.startDate = "";
          this.textBusinessCondition.endDate = "";
        }
      },
    },
  },

  methods: {
    APIgetSelectApps() {
      const params = {
        platformId: 5,
        menuCode: "game.Overview,android",
      };
      getSelectApps(params).then((res) => {
        console.log("创意素材组下的下拉列表", res);
        this.selectApps = res.result.data;
        console.log(this.selectApps);
      });
    },

    APIGetEnums() {
      getEnums().then((res) => {
        console.log(res);
        this.appCate = res.result.data.categorys;
      });
    },
    /* 获取文案列表*/
    APIgetBusinText() {
      let params = {
        appCategory: this.textBusinessCondition.appCategory,
        appId: this.appId,
        startDate: this.textBusinessCondition.startDate,
        endDate: this.textBusinessCondition.endDate,
        page: this.copyWriting.page,
        size: this.copyWriting.size,
      };
      getBusinText(params).then((res) => {
        console.log("文案库列表", res);
        this.newGetText = res.result.data.content;
        this.copyWriting.total = res.result.data.total;
      });
    },

    /* 添加文案*/
    addCopywriting(inText) {
      // this.newGetText.push()
      // 他的作用仅仅是在newGetText中的第一位给一个空值 这样就拿到了一个空的输入框
      this.newGetText.splice(0, 0, { text: "" });
      console.log(this.newGetText.text);
      const Addparams = {
        appCategory: 1,
        text: inText.text,
      };
      getBusinTextAdd(Addparams).then((res) => {
        console.log(res);
        if (res.status === 200) {
          this.$message({
            message: "添加成功",
            type: "success",
          });
          this.APIgetBusinText();
        }
      });
    },

    beforeSaveText(id, text) {
      console.log("保存文案：", id, text);
      if (id === "" || id === undefined) {
        this.dialogFormVisible = true;
      } else {
        this.addForm.id = id;
      }

      this.addForm.text = text;
    },

    addCopy(inText) {
      console.log(inText.text, this.newids[1]);

      if (inText.text != "") {
        let params = {
          id: this.addForm.id,
          appId: this.addForm.appId,
          text: this.addForm.text,
          appCategory: 1,
        };
        getBusinTextAdd(params).then((res) => {
          console.log("添加文案", res);
          if (res.status === 200) {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.APIgetBusinText();
            this.dialogFormVisible = false;
            this.inputValue2 = "";
          }
        });
      } else {
        this.$message({
          message: "请填写文案后保存",
          type: "warning",
        });
        this.APIgetBusinText();
      }
      console.log(0);
      // }else{
      //   this.$message({
      //     message: '请添加文案后再保存',
      //     type: 'warning'
      //   })
      // }
    },

    /* 选择当前文案 */
    handleCheckedCitiesChange(inText) {
      this.newids.push(inText.id, inText.text);
    },

    /* 全选按钮 */
    handleCheckAllChange(val) {
      console.log(val);
      if (this.checkAll) {
        this.newGetText.forEach((item) => {
          this.checkedCities.push(item.id);
          console.log(this.checkedCities);
        });
      } else {
        this.checkedCities = [];
      }
    },

    /* 删除 */
    Delete() {
      // let newIds = JSON.parse(this.checkedCities)
      // console.log(newIds)
      let params = {
        // ids: JSON.parse(this.checkedCities)
        ids: this.checkedCities.toString(),
      };
      getBusinTextDel(params).then((res) => {
        console.log(res);
        if (res.status === 200) {
          this.$confirm("是否删除?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.APIgetBusinText();
              console.log(this.checkedCities);
              this.checkedCities = [];
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除",
              });
            });
        } else {
          this.$message({
            message: "请选择要删除的文案",
            type: "warning",
          });
        }
      });
    },

    /* 修改文案 */
    editCopy(inText) {
      let params = {
        id: inText.id,
        text: inText.text,
      };
      getBusinTextEdit(params).then((res) => {
        console.log(res);
        if (res.status === 200) {
          this.$message({
            message: "修改成功",
            type: "success",
          });
          this.APIgetBusinText();
        }
      });
    },

    /* 分页*/
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`, this.val);
      this.copyWriting.page = val;
      this.APIgetBusinText();
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.copyWriting.size = val;
      this.APIgetBusinText();
    },

    /* 添加文案 */
    addText(text, id) {
      if (id === "" || id == null) {
        this.dialogFormVisible = true;
      } else {
        let params = {
          appId: id,
          text,
        };
        getBusinTextAdd(params).then((res) => {
          console.log(res);
          if (res.status === 200) {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.APIgetBusinText();
            this.inputValue2 = "";
          }
        });
      }
    },
  },
};
</script>

<style scoped>
.el-input-group__prepend {
  background-color: #fff;
}
</style>
