<template>
  <div>
    <div class="searchBox">
      <div>
        <RadioGroup v-model="newsSearch.ltype" @on-change="searchList()">
          <Radio :label="1">中文</Radio>
          <Radio :label="2">英文</Radio>
        </RadioGroup>
        <Input
          v-model="newsSearch.newstitle"
          @on-search="searchList()"
          placeholder="请输入标题"
          style="margin: 0 16px; width: 200px"
          clearable
          search
        />
        <!-- <Button type="primary" @click="searchList()">搜索</Button> -->
      </div>
      <div>
        <Button type="primary" @click="toAdd()">添加</Button>
      </div>
    </div>
    <Table border :columns="newsColumns" :data="newsSearch.list">
      <template slot-scope="{ row }" slot="newspicSlot">
        <img v-viewer class="news_pic" :src="$api.showImageUrl + row.newspic" />
      </template>
      <template slot-scope="{ row }" slot="loginstateSlot">
        <span>{{ row.loginstate === 1 ? "成功" : "失败" }}</span>
      </template>
      <template slot-scope="{ row }" slot="createtimeSlot">
        <span>{{ dateFormat(row.createtime) }}</span>
      </template>
      <template slot-scope="{ row }" slot="actionSlot">
        <div>
          <span
            style="color: #2d8cf0; cursor: pointer"
            @click="toViewDetail(row)"
            >查看</span
          >
          <span style="margin: 0 10px; color: #2d8cf0">|</span>
          <span style="color: #2d8cf0; cursor: pointer" @click="toModify(row)"
            >修改</span
          >
          <span style="margin: 0 10px; color: #2d8cf0">|</span>
          <span
            style="color: #ff001e; cursor: pointer"
            @click="toDel(row.newsid)"
            >删除</span
          >
        </div>
      </template>
    </Table>
    <div class="foot_page" v-if="newsSearch.total > 0">
      <Page
        :total="newsSearch.total"
        @on-change="changePage"
        :current="newsSearch.page"
        show-total
      ></Page>
    </div>
    <Modal
      v-model="addForm.show"
      class="modal1"
      :mask-closable="false"
      title="添加新闻资讯"
    >
      <Form
        :label-width="60"
        label-position="right"
        ref="addForm"
        :rules="formRules"
        :model="addForm"
      >
        <FormItem label="语言" prop="ltype">
          <RadioGroup v-model="addForm.ltype">
            <Radio :label="1">中文</Radio>
            <Radio :label="2">英文</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="封面" prop="newspic">
          <div class="form_item_upload">
            <Upload
              :format="pictureFormat"
              action
              :before-upload="
                (file) => {
                  beforeUploadPicture(file, addForm);
                  return false;
                }
              "
              :accept="getPictureAccept()"
              :show-upload-list="false"
            >
              <img
                style="width: 200px"
                v-if="addForm.newspic"
                :src="$api.showImageUrl + addForm.newspic"
              />
              <!-- <Button v-else icon="ios-cloud-upload-outline">上传封面</Button> -->
              <div class="upload_img" v-else>
                <Icon
                  type="ivu-icon ivu-icon- iconfont icon-shangchuan"
                  size="42"
                  color="#e6e6e6"
                />
                <p class="shangchuan_btn">上传图片</p>
              </div>
            </Upload>
            <div class="uptype">
              <p>支持上传格式（10MB以内）:</p>
              <p>jpg、jpeg、png、bmp、jfif、webp.</p>
            </div>
          </div>
        </FormItem>
        <FormItem label="置顶" prop="newsup">
          <RadioGroup v-model="addForm.newsup">
            <Radio :label="1">置顶</Radio>
            <Radio :label="2">不置顶</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="排序" prop="newsorder">
          <InputNumber :min="1" v-model="addForm.newsorder" />
        </FormItem>
        <FormItem label="标题" prop="newstitle">
          <Input
            :maxlength="255"
            show-word-limit
            v-model="addForm.newstitle"
            placeholder="请输入标题"
          />
        </FormItem>
        <FormItem label="摘要" prop="newssummary">
          <Input
            type="textarea"
            :rows="2"
            v-model="addForm.newssummary"
            :maxlength="255"
            show-word-limit
            placeholder="请输入摘要"
          />
        </FormItem>
        <FormItem label="内容" prop="newscontent">
          <NewsEditor
            :height="300"
            @change="getNewsContent($event, addForm)"
            :content="addForm.newscontent"
          ></NewsEditor>
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: right">
        <Button @click="addForm.show = false">取消</Button>
        <Button @click="toSaveAdd()" type="primary">保存</Button>
      </div>
    </Modal>
    <Modal
      v-model="modifyForm.show"
      class="modal1"
      :mask-closable="false"
      title="修改新闻资讯"
    >
      <Form
        :label-width="60"
        label-position="right"
        ref="modifyForm"
        :rules="formRules"
        :model="modifyForm"
      >
        <FormItem label="封面" prop="newspic">
          <div class="form_item_upload">
            <Upload
              :format="pictureFormat"
              action
              :before-upload="
                (file) => {
                  beforeUploadPicture(file, modifyForm);
                  return false;
                }
              "
              :accept="getPictureAccept()"
              :show-upload-list="false"
            >
              <img
                style="width: 200px"
                v-if="modifyForm.newspic"
                :src="$api.showImageUrl + modifyForm.newspic"
              />
              <!-- <Button v-else icon="ios-cloud-upload-outline">上传封面</Button> -->
              <div class="upload_img" v-else>
                <Icon
                  type="ivu-icon ivu-icon- iconfont icon-shangchuan"
                  size="42"
                  color="#e6e6e6"
                />
                <p class="shangchuan_btn">上传图片</p>
              </div>
            </Upload>
            <div class="uptype">
              <p>支持上传格式（10MB以内）:</p>
              <p>jpg、jpeg、png、bmp、jfif、webp.</p>
            </div>
          </div>
        </FormItem>
        <FormItem label="置顶" prop="newsup">
          <RadioGroup v-model="modifyForm.newsup">
            <Radio :label="1">置顶</Radio>
            <Radio :label="2">不置顶</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="排序" prop="newsorder">
          <InputNumber :min="1" v-model="modifyForm.newsorder" />
        </FormItem>
        <FormItem label="标题" prop="newstitle">
          <Input
            :maxlength="255"
            show-word-limit
            v-model="modifyForm.newstitle"
            placeholder="请输入标题"
          />
        </FormItem>
        <FormItem label="摘要" prop="newssummary">
          <Input
            type="textarea"
            :rows="2"
            v-model="modifyForm.newssummary"
            :maxlength="255"
            show-word-limit
            placeholder="请输入摘要"
          />
        </FormItem>
        <FormItem label="内容" prop="newscontent">
          <NewsEditor
            :height="400"
            @change="getNewsContent($event, modifyForm)"
            :content="modifyForm.newscontent"
          ></NewsEditor>
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: right">
        <Button @click="modifyForm.show = false">取消</Button>
        <Button @click="toSaveModify()" type="primary">保存</Button>
      </div>
    </Modal>
    <Modal
      v-model="detailInfo.show"
      class="modal_detail"
      :mask-closable="false"
      title="查看新闻资讯"
    >
      <Form :label-width="60" label-position="right" :model="detailInfo">
        <FormItem label="语言">{{
          detailInfo.ltype === 1 ? "中文" : "英文"
        }}</FormItem>
        <FormItem label="封面" prop="newspic">
          <img
            style="width: 200px"
            v-viewer
            v-if="detailInfo.newspic"
            :src="$api.showImageUrl + detailInfo.newspic"
          />
        </FormItem>
        <FormItem label="置顶" prop="newsup">{{
          detailInfo.newsup === 1 ? "置顶" : "不置顶"
        }}</FormItem>
        <FormItem label="排序" prop="newsorder">{{
          detailInfo.newsorder
        }}</FormItem>
        <FormItem label="标题" prop="newstitle">{{
          detailInfo.newstitle
        }}</FormItem>
        <FormItem label="摘要" prop="newssummary">{{
          detailInfo.newssummary
        }}</FormItem>
        <FormItem label="内容" prop="newscontent">
          <div class="news_content" v-html="detailInfo.newscontent"></div>
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: center">
        <Button @click="detailInfo.show = false">关闭</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import axios from "axios";
import NewsEditor from "./newsEditor.vue";
import { n_list, n_save, n_update, n_remove } from "@/api";
import { dateFormat } from "@/utils";
import { pictureFormat } from "@/utils/fileConfig";
export default {
  components: {
    NewsEditor
  },
  data() {
    return {
      dateFormat,
      pictureFormat,
      newsSearch: {
        ltype: 1,
        newstitle: "",
        page: 1,
        size: 10,
        total: 0,
        list: []
      },
      newsColumns: [
        {
          title: "序号",
          width: 70,
          render: (h, params) => {
            return h(
              "span",
              params.index +
                (this.newsSearch.page - 1) * this.newsSearch.size +
                1
            );
          }
        },
        {
          title: "封面",
          slot: "newspicSlot",
          width: 100
        },
        {
          title: "置顶",
          key: "newsup",
          width: 70
        },
        {
          title: "排序",
          key: "newsorder",
          width: 70
        },
        {
          title: "标题",
          key: "newstitle"
        },
        // {
        //   title: "摘要",
        //   key: "newssummary"
        // },
        {
          title: "创建人",
          key: "createname",
          width: 100
        },
        {
          title: "创建时间",
          slot: "createtimeSlot",
          width: 180
        },
        {
          title: "操作",
          slot: "actionSlot",
          width: 180
        }
      ],
      userInfo: {},
      searchOption: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        }
      },
      addForm: {
        show: false,
        ltype: 1,
        newspic: "",
        newstitle: "",
        newssummary: "",
        newsup: 2,
        newsorder: 1,
        newscontent: ""
      },
      formRules: {
        ltype: [
          {
            required: true,
            type: "number",
            message: "请选择语言",
            trigger: "change"
          }
        ],
        newsup: [
          {
            required: true,
            message: "请选择是否置顶",
            type: "number",
            trigger: "change"
          }
        ],
        newspic: [
          {
            required: true,
            message: "请上传图片",
            trigger: "change"
          }
        ],
        newstitle: [
          {
            required: true,
            message: "请输入标题",
            trigger: "blur"
          }
        ],
        newscontent: [
          {
            required: true,
            message: "请输入内容",
            trigger: "change"
          }
        ],
        newssummary: [
          {
            required: true,
            message: "请输入摘要",
            trigger: "blur"
          }
        ],
        newsorder: [
          {
            required: true,
            message: "请输入排序",
            type: "number",
            trigger: "blur"
          }
        ]
      },
      modifyForm: {
        show: false,
        newsid: null,
        newspic: "",
        newstitle: "",
        newssummary: "",
        newsup: 2,
        newsorder: 1,
        newscontent: ""
      },
      detailInfo: {
        show: false,
        ltype: 1,
        newspic: "",
        newstitle: "",
        newssummary: "",
        newsup: 2,
        newsorder: 1,
        newscontent: ""
      }
    };
  },
  created() {
    this.userInfo = JSON.parse(localStorage.getItem("xhWebAdminUser"));
    this.getNewsList();
  },
  methods: {
    getNewsContent(html, formObj) {
      formObj.newscontent = html;
    },
    beforeUploadPicture(file, formObj) {
      let size = file.size / 1024 / 1024;
      if (size > 2) {
        this.$Message.error("图片太大，不能超过2M!");
        return false;
      }
      let formData = new FormData();
      formData.append("file", file);
      formData.append("savefolder", "news");
      axios
        .post(this.$api.baseUrl + "file/upload", formData, {
          timeout: 1000 * window._config.axiosFileTimeout
        })
        .then((res) => {
          if (res.data.code === 0) {
            formObj.newspic = res.data.obj;
          } else {
            this.$Message.error(res.data.msg);
          }
        })
        .catch(() => {});
    },
    getPictureAccept() {
      return this.pictureFormat
        .map((v) => {
          return `.${v}`;
        })
        .join(",");
    },
    searchList() {
      this.newsSearch.page = 1;
      this.getNewsList();
    },
    getNewsList() {
      n_list({
        ltype: this.newsSearch.ltype,
        newstitle: this.newsSearch.newstitle,
        page: this.newsSearch.page,
        size: this.newsSearch.size
      })
        .then((data) => {
          if (data.code === 0) {
            this.newsSearch.total = data.obj.total;
            this.newsSearch.list = data.obj.list;
          } else {
            this.newsSearch.total = 0;
            this.newsSearch.list = [];
            this.$Message.error(data.msg);
          }
        })
        .catch(() => {});
    },
    changePage(page) {
      this.newsSearch.page = page;
      this.getNewsList();
    },
    toAdd() {
      this.addForm = {
        show: true,
        ltype: this.newsSearch.ltype,
        newspic: "",
        newstitle: "",
        newssummary: "",
        newsup: 2,
        newsorder: 1,
        newscontent: ""
      };
    },
    toSaveAdd() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          n_save({
            newstitle: this.addForm.newstitle,
            newscontent: this.addForm.newscontent,
            newssummary: this.addForm.newssummary,
            newspic: this.addForm.newspic,
            ltype: this.addForm.ltype,
            newsorder: this.addForm.newsorder,
            newsup: this.addForm.newsup,
            createid: this.userInfo.userid
          }).then((res) => {
            this.addForm.show = false;
            if (res.code === 0) {
              this.$Message.success(res.msg);
              this.searchList();
            } else {
              this.$Message.error(res.msg);
            }
          });
        }
      });
    },
    toModify(row) {
      this.modifyForm = {
        show: true,
        newsid: row.newsid,
        newspic: row.newspic,
        newstitle: row.newstitle,
        newssummary: row.newssummary,
        newsup: row.newsup,
        newsorder: row.newsorder,
        newscontent: row.newscontent
      };
    },
    toSaveModify() {
      this.$refs.modifyForm.validate((valid) => {
        if (valid) {
          n_update({
            newstitle: this.modifyForm.newstitle,
            newscontent: this.modifyForm.newscontent,
            newssummary: this.modifyForm.newssummary,
            newspic: this.modifyForm.newspic,
            newsorder: this.modifyForm.newsorder,
            newsup: this.modifyForm.newsup,
            newsid: this.modifyForm.newsid
          }).then((res) => {
            this.modifyForm.show = false;
            if (res.code === 0) {
              this.$Message.success(res.msg);
              this.searchList();
            } else {
              this.$Message.error(res.msg);
            }
          });
        }
      });
    },
    toDel(newsid) {
      this.$Modal.confirm({
        title: "提示",
        content: "您确定删除选中数据吗?",
        onOk: () => {
          n_remove({ newsid }).then((res) => {
            if (res.code == 0) {
              this.$Message.success(res.msg);
              this.searchList();
            } else {
              this.$Message.error(res.msg);
            }
          });
        },
        onCancel: () => {}
      });
    },
    toViewDetail(row) {
      this.detailInfo = {
        show: true,
        ltype: row.ltype,
        newspic: row.newspic,
        newstitle: row.newstitle,
        newssummary: row.newssummary,
        newsup: row.newsup,
        newsorder: row.newsorder,
        newscontent: row.newscontent
      };
    }
  }
};
</script>

<style scoped lang="less">
.searchBox {
  display: flex;
  justify-content: space-between;
  padding: 16px 0;
}
.news_pic {
  display: block;
  margin: 10px auto;
  width: 60px;
  object-fit: cover;
}
.foot_page {
  padding: 16px 0;
  text-align: right;
}
.form_item_upload {
  display: flex;
  justify-content: flex-start;
  .uptype {
    padding-left: 10px;
  }
}
.upload_img {
  padding-top: 10px;
  width: 198px;
  height: 98px;
  text-align: center;
  object-fit: cover;
  border: 1px solid #dcdee2;
  .shangchuan_btn {
    margin-top: 10px;
    font-size: 14px;
    line-height: 21px;
    text-align: center;
  }
}
.upload_img:hover {
  color: #2d8cf0;
  border: 1px solid #2d8cf0;
  .icon-shangchuan {
    color: #2d8cf0 !important;
  }
}
.news_content /deep/ img {
  max-width: 100%;
}
</style>
