<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
        <el-form-item label="日期">
            <el-date-picker
                v-model="dateRange"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy-MM-dd" style="width: 220px"
                :picker-options="pickerOptions" >
            </el-date-picker>
        </el-form-item>
        <el-form-item label="文章标题">
            <el-input v-model="queryParams.articleTitle" placeholder="请输入文章标题" maxlength="20" clearable style="width: 220px"/>
        </el-form-item>

        <el-form-item label="适用慢性病">
            <el-select v-model="queryParams.chronicList" multiple style="width: 220px" clearable collapse-tags>
                <el-option v-for="item in chronicOptions"
                    :key="item.chronicId"
                    :label="item.chronicName"
                    :value="item.chronicId"
                ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="文章类型">
            <el-select v-model="queryParams.articleType"  style="width: 220px" clearable collapse-tags>
                <el-option label="原创" value="1"></el-option>
                <el-option label="转载" value="2"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                >新增</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="tableListData" height="800" ref="multipleTable">
            <el-table-column label="序号" align="center" width="80" type="index" fixed="left">
                    <template slot-scope="scope">
                        <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
                    </template>
            </el-table-column>
            <el-table-column label="封面照片" align="center" prop="coverPhoto" :show-overflow-tooltip="true" >
                <template slot-scope="scope">
                    <img :src="scope.row.coverPhoto" v-if="scope.row.coverPhoto" alt="" style="width: 80px;height: 40px;" @click="openImg(scope.row)">
                    <span v-else>无</span>
                </template>
            </el-table-column>
            <el-table-column label="文章标题" align="center" prop="articleTitle" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column label="适用慢性病" align="center" prop="chronicNames" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column label="文章类型" align="center" prop="articleType" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span v-if="scope.row.articleType==1">原创</span>
                    <span v-if="scope.row.articleType==2">转载</span>
                </template>
            </el-table-column>
            <el-table-column label="发布时间" align="center" prop="pushTime" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column label="可见状态" align="center" prop="ifVisible" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <span>{{ '否' }}</span>
                  <el-switch
                    v-model="scope.row.ifPushed=='2'?false:true"
                    @change="handleIfPushedChange(scope.row)">
                  </el-switch>
                  <span>{{ '是' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width" fixed="right">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                    >修改</el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                    >删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
        />

        <!-- 对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="980px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="90px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="文章标题" prop="articleTitle">
                            <el-input v-model="form.articleTitle" placeholder="请输入文章标题" maxlength="20"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="文章摘要" prop="summary">
                            <el-input v-model="form.summary" placeholder="请输入文章摘要" maxlength="30"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="适用慢性病" prop="chronicIdList">
                            <el-select v-model="form.chronicIdList" multiple style="width: 100%" @change="$forceUpdate()" clearable collapse-tags>
                                <el-option v-for="item in chronicOptions"
                                    :key="item.chronicId"
                                    :label="item.chronicName"
                                    :value="item.chronicId"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="文章封面" prop="coverPhoto">
                            <el-upload
                                :http-request="
                                    (obj) => imgUpLoad(obj, 'fileUrl')
                                "
                                action="#"
                                :limit="1"
                                :file-list="fileList"
                                :show-file-list="true"
                                list-type="picture-card"
                                accept=".png, .jpg, .jpeg"
                                :on-success="handleAvatarSuccess"
                                :class="{ disabled: uploadDisabled }"
                                :on-preview="handlePictureCardPreview"
                                :on-remove="handleRemove"
                            >
                                <i
                                    class="el-icon-plus avatar-uploader-icon"
                                ></i>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="内容"  prop="articleContent">
                            <editor v-model="form.articleContent" :min-height="192"/>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog :visible.sync="dialogVisible" width="700px">
            <img style="width: 100%;height: 100%;" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>

<script>
import { dictHealthChronicApi,getHealthSciencePageApi,addHealthScienceApi,editHealthScienceApi,delHealthScienceApi,editHealthScienceStateApi  } from "@/api/healthCenter/index";
import { imgUpLoadTwo } from '@/api/system/upload'

export default {
    name: "",
    dicts: [],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            //表格数据
            tableListData: [],
            title:"",
            // 是否显示弹出层
            open: false,
            dateRange:[new Date(),new Date()],
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                    const start = new Date();
                    const end = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
                    picker.$emit('pick', [start, end]);
                    }
                },{
                    text: '最近一个月',
                    onClick(picker) {
                    const start = new Date();
                    const end = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                    picker.$emit('pick', [start, end]);
                    }
                },{
                    text: '最近三个月',
                    onClick(picker) {
                    const start = new Date();
                    const end = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 91);
                    picker.$emit('pick', [start, end]);
                    }
                }]
            },
            chronicOptions:[],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                articleTitle: undefined,//标题
                chronicList:[],  //慢性病
                articleType:null //类型
            },
            form: {
                articleTitle:null,
                summary:null,
                chronicIdList:[],
                coverPhoto:null,
                articleType:1,
                articleContent:null,
            },//详情
            rules: {
                articleTitle: [
                    { required: true, message: "文章标题不能为空", trigger: "blur" }
                ],
                articleContent: [
                    { required: true, message: "文章内容不能为空", trigger: "blur" }
                ]
            },
            fileList: [],//图片
            checkUrlList: [],//图片
            checkUrlNameList: [],//食堂图片
            dialogVisible:false,//图片弹窗
            dialogImageUrl:"",//图片弹窗
        };
    },
    created() {
        this.getList()
        this.getChronicList()
    },
    computed: {
        //图片上传1张后，隐藏上传框
        uploadDisabled() {
            return this.checkUrlList.length > 0
        },
    },
    methods: {
        //慢性病类型
        getChronicList() {
            dictHealthChronicApi({}).then((response) => {
                this.chronicOptions = response.data;
            });
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [new Date(),new Date()]
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                articleTitle: undefined,//标题
                chronicList:[],  //慢性病
                articleType:null //类型
            }
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 查询列表 */
        getList() {
            this.loading = true;
            let param = {
                "pageNum":this.queryParams.pageNum,
                "pageSize":this.queryParams.pageSize,
                "articleTitle":this.queryParams.articleTitle,
                "articleType":this.queryParams.articleType,
                "chronicIds":this.queryParams.chronicList.join(",")||"",
                "startDate":this.formatDate(this.dateRange[0]),
                "endDate":this.formatDate(this.dateRange[1])
            }
            // if(this.queryParams.chronicList.length>0){
            //     this.queryParams.chronicIds = this.queryParams.chronicList.join(",")
            // }else{
            //     this.queryParams.chronicIds = ""
            // }
            getHealthSciencePageApi(param).then(response => {
                this.tableListData = response.rows;
                this.total = Number(response.total);
            this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.fileList=[]
            this.checkUrlList=[]
            this.checkUrlNameList=[]
            this.form = {
                articleTitle:null,
                summary:null,
                chronicIdList:[],
                coverPhoto:null,
                articleType:1,
                articleContent: null,
            };
            this.resetForm("form");
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "新增";
        },
        handleUpdate(row) {
            this.form = Object.assign({}, row);
            if(this.form.coverPhoto){
                this.fileList=[{url:this.form.coverPhoto}]
                this.checkUrlList=[this.form.coverPhoto]
            }else{
                this.fileList=[]
                this.checkUrlList=[]
            }
            if(this.form.chronicIds!=null&&this.form.chronicIds.length>0){
              this.form.chronicIdList=this.form.chronicIds.split(",");
            }
            console.log("this.form.articleContent",this.form.articleContent);
            this.open = true;
            this.title = "修改";
        },
        /** 提交按钮 */
        submitForm: function() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if(this.form.chronicIdList.length>0){
                        this.form.chronicIds = this.form.chronicIdList.join(",")
                    }else{
                        this.form.chronicIds = ""
                    }
                    this.form.coverPhoto = this.checkUrlList[0];
                    console.log("this.form.articleContent",this.form.articleContent);
                    if (this.form.articleId != undefined) {
                        editHealthScienceApi(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addHealthScienceApi(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        handleDelete(row) {
            this.$modal.confirm('是否确认删除数据项？').then(function() {
                console.log("row",row)
                return delHealthScienceApi(row.articleId);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {});
        },
        openImg(row) {
          this.dialogImageUrl = row.coverPhoto;
          this.dialogVisible = true;
        },
        // 图片上传
        imgUpLoad(param, name, index) {
            // console.log(param,'image')
            param.type = 'canteen'
            imgUpLoadTwo(param).then((res) => {
                if (res.code == 200) {
                    this.checkUrlList.push(res.data.url)
                    this.checkUrlNameList.push(res.data.name)
                } else {
                    this.$modal.msgError(res.msg)
                }
            })
            .catch((error) => {
                this.$modal.msgError(error)
            })
        },
        handleAvatarSuccess(res, file) {
            console.log('success')
        },
        handleRemove(file, fileList) {
            let sum = 0
            this.checkUrlNameList.forEach((item, index) => {
                if (item == file.name) {
                    sum = index
                }
            })
            this.checkUrlNameList.splice(sum, 1)
            this.checkUrlList.splice(sum, 1)
        },
        //图片点击查看
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url
            this.dialogVisible = true
        },
        //日期
        formatDate(date) {
            // 格式化为 YYYY-MM-DD
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },
        handleIfPushedChange(row){
           let pws=row.ifPushed;
           let param={}
           if(pws=="1"){
             param={
               articleId:row.articleId,
               ifPushed:"2"
             }
           }else if(pws=="2"){
             param={
               articleId:row.articleId,
               ifPushed:"1"
             }
           }
           editHealthScienceStateApi(param).then(response => {
             this.getList();
           });
        },
    }
};
</script>
<style lang="scss" scoped>
    .remind-question{
        width: 100%;
        height: 50px;
        font-size: 22px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .remind-title{
        width: 100%;
        height: 40px;
        font-size: 16px;
        font-weight: bold;
        color: #000;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    //隐藏图片上传框的css
    ::v-deep.disabled {
        .el-upload--picture-card {
            display: none;
        }
    }
</style>
