<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" @submit.native.prevent>
      <el-form-item label="活动标题" prop="title">
        <el-input v-model="queryParams.title"
                  placeholder="请输入活动标题"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="cyan" 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"
                   icon="el-icon-plus"
                   size="mini"
                   @click="handleAdd"
                   v-has-permi="['his:promotionalActive:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success"
                   icon="el-icon-edit"
                   size="mini"
                   :disabled="single"
                   @click="handleUpdate"
                   v-has-permi="['his:promotionalActive:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger"
                   icon="el-icon-delete"
                   size="mini"
                   :disabled="multiple"
                   @click="handleDelete"
                   v-has-permi="['his:promotionalActive:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="活动标题" align="center" prop="title" width="200" />
      <el-table-column label="活动主题" align="center" prop="theme" width="250" >
        <template slot-scope="scope">
          <el-popover
            placement="right"
            title=""
            trigger="hover"
          >
            <img slot="reference" :src="scope.row.theme" style="max-height: 80px; width: auto;">
            <img :src="scope.row.theme" style="max-width: 150px; max-height: 150px; width: auto;">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="活动内容" align="center" prop="content">
        <template slot-scope="scope">
          <div v-if="scope.row.content">
            <el-image
              v-for="(img, index) in parseImages(scope.row.content)"
              :key="index"
              style="width: 50px; height: 50px; margin-right: 5px; margin-bottom: 5px;"
              :src="img"
              :preview-src-list="parseImages(scope.row.content)"
              fit="cover">
            </el-image>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="100" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleUpdate(scope.row)"
                     v-has-permi="['his:promotionalActive:edit']">修改</el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-delete"
                     @click="handleDelete(scope.row)"
                     v-has-permi="['his:promotionalActive:remove']">删除</el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-view"
                     v-has-permi="['his:promotionalActive:view']"
                     @click="handleView(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="1200px" append-to-body>
      <el-form v-loading="formLoading" :model="form" ref="form" :rules="rules" label-width="110px">
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入活动标题" clearable size="small" />
        </el-form-item>
        <el-form-item label="活动主题" prop="theme">
          <ImageUpload v-model="form.theme" type="image" :limit="1" :width="150" :height="150"/>
        </el-form-item>
        <el-form-item label="活动内容" prop="content">
          <ImageUpload v-model="form.content" type="image" :limit="3" :width="150" :height="150"/>
        </el-form-item>
        <el-form-item label="视频区" prop="videoList">
          <el-button size="small" type="primary" @click="chooseCourseVideo">选取课程小节</el-button>
          <el-table border width="100%" style="margin-top:5px;" :data="form.videoList">
            <el-table-column label="所属课程" align="center" prop="courseName" />
            <el-table-column label="小节名称" align="center" prop="courseVideoName"/>
            <el-table-column label="视频文件名称" align="center" prop="videoName"/>
            <el-table-column label="时长" align="center" prop="duration"/>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="mini"
                           type="text"
                           icon="el-icon-delete"
                           @click="handleCourseVideoDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="问诊区" prop="doctorList">
          <el-button size="small" type="primary" @click="chooseDoctor">选取问诊医生</el-button>
          <el-table border width="100%" style="margin-top:5px;" :data="form.doctorList">
            <el-table-column label="医生姓名" align="center" prop="doctorName" />
            <el-table-column label="所属医院" align="center" prop="hospitalName"/>
            <el-table-column label="所属科室" align="center" prop="deptName"/>
            <el-table-column label="职称" align="center" prop="position"/>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="mini"
                           type="text"
                           icon="el-icon-delete"
                           @click="handleDoctorDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="积分商品" prop="goodsList">
          <el-button size="small" type="primary" @click="chooseGoods">选取商品</el-button>
          <el-table border width="100%" style="margin-top:5px;" :data="form.goodsList">
            <el-table-column label="商品名称" align="center" prop="goodsName" />
            <el-table-column label="封面图片" align="center" prop="goodsImg">
              <template slot-scope="scope">
                <el-popover
                  placement="right"
                  title=""
                  trigger="hover"
                >
                  <img slot="reference" :src="scope.row.goodsImg" width="100">
                  <img :src="scope.row.goodsImg" style="max-width: 150px;">
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="商品分类" align="center" prop="goodsTypeName"/>
            <el-table-column label="商品价格" align="center" prop="cash"/>
            <el-table-column label="所需积分" align="center" prop="integral"/>
            <el-table-column label="库存" align="center" prop="stock"/>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="mini"
                           type="text"
                           icon="el-icon-delete"
                           @click="handleGoodsDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="疗法包" prop="packageList">
          <el-button size="small" type="primary" @click="choosePackage">选取疗法包</el-button>
          <el-table border width="100%" style="margin-top:5px;" :data="form.packageList">
            <el-table-column label="封面图片" width="120" align="center">
              <template slot-scope="scope">
                <el-popover
                  placement="right"
                  title=""
                  trigger="hover"
                >
                  <img slot="reference" :src="scope.row.packageImg" width="100">
                  <img :src="scope.row.packageImg" style="max-width: 150px;">
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="疗法名称" align="center" prop="packageName" />
            <el-table-column label="疗法别名" align="center" prop="secondName"/>
            <el-table-column label="类型" align="center" prop="packageTypeName"/>
            <el-table-column label="子类型" align="center" prop="packageSubTypeName"/>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="mini"
                           type="text"
                           icon="el-icon-delete"
                           @click="handlePackageDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary"
                   @click="submitForm"
                   :loading="addOrUpdating"
                   :disabled="addOrUpdating">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="videoDialog.title" :visible.sync="videoDialog.open" width="1200px" append-to-body>
      <choose-course-video-component :videoIds="this.form.videoList.map(item => item.videoId)"
                                     @closeChoose="closeChooseCourseVideo"
                                     @selectConfirm="selectConfirmCourseVideo"/>
    </el-dialog>

    <el-dialog :title="doctorDialog.title" :visible.sync="doctorDialog.open" width="1200px" append-to-body>
      <choose-doctor-component :doctorIds="this.form.doctorList.map(item => item.doctorId)"
                              @closeChoose="closeChooseDoctor"
                              @selectConfirm="selectConfirmDoctor"/>
    </el-dialog>

    <el-dialog :title="goodsDialog.title" :visible.sync="goodsDialog.open" width="1200px" append-to-body>
      <choose-integral-goods-component :goodsIds="this.form.goodsList.map(item => item.goodsId)"
                                      @closeChoose="closeChooseGoods"
                                      @selectConfirm="selectConfirmGoods"/>
    </el-dialog>

    <el-dialog :title="packageDialog.title" :visible.sync="packageDialog.open" width="1200px" append-to-body>
      <choose-package-component :packageIds="this.form.packageList.map(item => item.packageId)"
                              @closeChoose="closeChoosePackage"
                              @selectConfirm="selectConfirmPackage"/>
    </el-dialog>

    <el-drawer
      :with-header="false"
      size="75%"
      :title="show.title"
      :visible.sync="show.open" append-to-body>
      <div v-if="show.data" v-loading="formLoading" class="detail-container">
        <div class="detail-header">
          <div class="detail-title">
            {{ show.data.title || '查看详情' }}
          </div>
          <el-button type="text" icon="el-icon-close" @click="show.open=false"></el-button>
        </div>

        <el-card shadow="never" class="block-card">
          <div slot="header" class="card-header">基本信息</div>
          <el-descriptions :column="1" border size="small">
            <el-descriptions-item label="活动标题">{{ show.data.title || '-' }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ show.data.createTime || '-' }}</el-descriptions-item>
            <el-descriptions-item label="活动主题">
              <div class="theme-wrapper">
                <img v-if="show.data.theme" :src="show.data.theme" class="theme-image" />
                <span v-else>-</span>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="活动内容">
              <div v-if="show.data.content" class="image-gallery">
                <el-image
                  v-for="(img, index) in parseImages(show.data.content)"
                  :key="index"
                  :src="img"
                  :preview-src-list="parseImages(show.data.content)"
                  fit="cover"
                  class="gallery-item"
                />
              </div>
              <span v-else>-</span>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card shadow="never" class="block-card">
          <div slot="header" class="card-header">视频区</div>
          <el-table v-if="(show.data.videoList || []).length" :data="show.data.videoList" border size="small">
            <el-table-column label="所属课程" align="center" prop="courseName" />
            <el-table-column label="小节名称" align="center" prop="courseVideoName"/>
            <el-table-column label="视频文件名称" align="center" prop="videoName"/>
            <el-table-column label="时长" align="center" prop="duration"/>
          </el-table>
          <span v-else>-</span>
        </el-card>

        <el-card shadow="never" class="block-card">
          <div slot="header" class="card-header">问诊区</div>
          <el-table v-if="(show.data.doctorList || []).length" :data="show.data.doctorList" border size="small">
            <el-table-column label="医生姓名" align="center" prop="doctorName" />
            <el-table-column label="所属医院" align="center" prop="hospitalName"/>
            <el-table-column label="所属科室" align="center" prop="deptName"/>
            <el-table-column label="职称" align="center" prop="position"/>
          </el-table>
          <span v-else>-</span>
        </el-card>

        <el-card shadow="never" class="block-card">
          <div slot="header" class="card-header">积分商品</div>
          <el-table v-if="(show.data.goodsList || []).length" :data="show.data.goodsList" border size="small">
            <el-table-column label="商品名称" align="center" prop="goodsName" />
            <el-table-column label="封面图片" align="center" prop="goodsImg">
              <template slot-scope="scope">
                <el-popover placement="right" title="" trigger="hover">
                  <img slot="reference" :src="scope.row.goodsImg" class="thumb" />
                  <img :src="scope.row.goodsImg" class="popover-img" />
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="商品分类" align="center" prop="goodsTypeName"/>
            <el-table-column label="商品价格" align="center" prop="cash"/>
            <el-table-column label="所需积分" align="center" prop="integral"/>
            <el-table-column label="库存" align="center" prop="stock"/>
          </el-table>
          <span v-else>-</span>
        </el-card>

        <el-card shadow="never" class="block-card">
          <div slot="header" class="card-header">疗法包</div>
          <el-table v-if="(show.data.packageList || []).length" :data="show.data.packageList" border size="small">
            <el-table-column label="封面图片" width="120" align="center">
              <template slot-scope="scope">
                <el-popover placement="right" title="" trigger="hover">
                  <img slot="reference" :src="scope.row.packageImg" class="thumb" />
                  <img :src="scope.row.packageImg" class="popover-img" />
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="疗法名称" align="center" prop="packageName" />
            <el-table-column label="疗法别名" align="center" prop="secondName"/>
            <el-table-column label="类型" align="center" prop="packageTypeName"/>
            <el-table-column label="子类型" align="center" prop="packageSubTypeName"/>
          </el-table>
          <span v-else>-</span>
        </el-card>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import ChooseCourseVideoComponent from '@/views/his/promotionalActive/ChooseCourseVideoComponent.vue'
import ChooseDoctorComponent from '@/views/his/promotionalActive/ChooseDoctorComponent.vue'
import ChooseIntegralGoodsComponent from '@/views/his/promotionalActive/ChooseIntegralGoodsComponent.vue'
import ChoosePackageComponent from '@/views/his/promotionalActive/ChoosePackageComponent.vue'
import { add, update, list, get, del } from '@/api/his/promotionalActive'

export default {
  name: 'promotionalActive',
  components: {
    ChooseCourseVideoComponent,
    ChooseDoctorComponent,
    ChooseIntegralGoodsComponent,
    ChoosePackageComponent
  },
  data() {
    return {
      loading: false,
      single: true,
      multiple: true,
      ids: [],
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
      },
      total: 0,
      list: [],
      title: '新增',
      open: false,
      form: {
        id: null,
        title: null,
        theme: null,
        content: null,
        goodsList: [],
        packageList: [],
        doctorList: [],
        videoList: [],
      },
      formLoading: false,
      rules: {
        title: [
          { required: true, message: '请输入活动标题', trigger: 'blur' }
        ],
        theme: [
          { required: true, message: '请上传活动主题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请上传活动内容', trigger: 'blur' }
        ]
      },
      videoDialog: {
        open: false,
        title: '课程小节选择',
      },
      doctorDialog: {
        open: false,
        title: '问诊医生选择',
      },
      goodsDialog: {
        open: false,
        title: '积分商品选择',
      },
      packageDialog: {
        open: false,
        title: '疗法包选择',
      },
      addOrUpdating: false,
      show: {
        open: false,
        title: '查看详情',
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 解析逗号分隔的图片URL字符串
    parseImages(images) {
      if (!images) return [];
      return images.split(',').filter(img => img.trim() !== '');
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        title: null,
      };
      this.getList();
    },
    getList() {
      this.loading = true
      list(this.queryParams).then(response => {
        this.list = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.addOrUpdating = false
      this.title = '添加活动'
    },
    reset() {
      this.form = {
        id: null,
        title: null,
        theme: null,
        content: null,
        goodsList: [],
        packageList: [],
        doctorList: [],
        videoList: [],
      }
      this.resetForm("form");
    },
    handleUpdate(row) {
      const id = row.id || this.ids
      this.reset()
      this.formLoading = true
      get(id).then(response => {
        this.form = {
          ...response.data,
          goodsList: response.data.goodsList || [],
          packageList: response.data.packageList || [],
          doctorList: response.data.doctorList || [],
          videoList: response.data.videoList || []
        }
        this.formLoading = false
      })
      this.open = true
      this.addOrUpdating = false
      this.title = '修改活动'
    },
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除积分商品编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return del(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
      this.single = selection.length !== 1
    },
    handleView(row) {
      this.formLoading = true
      this.show.open = true
      get(row.id).then(response => {
        this.show.data = {
          ...response.data,
          goodsList: response.data.goodsList || [],
          packageList: response.data.packageList || [],
          doctorList: response.data.doctorList || [],
          videoList: response.data.videoList || []
        }
        this.formLoading = false
      })
    },
    chooseCourseVideo() {
      this.videoDialog.open = true
    },
    closeChooseCourseVideo() {
      this.videoDialog.open = false
    },
    selectConfirmCourseVideo(data) {
      this.form.videoList = []
      data.forEach(item => {
        this.form.videoList.push(item)
      })
      this.videoDialog.open = false
    },
    handleCourseVideoDelete(row) {
      this.form.videoList.splice(this.form.videoList.indexOf(row), 1)
    },
    chooseDoctor() {
      this.doctorDialog.open = true
    },
    closeChooseDoctor() {
      this.doctorDialog.open = false
    },
    selectConfirmDoctor(data) {
      this.form.doctorList = []
      data.forEach(item => {
        this.form.doctorList.push(item)
      })
      this.doctorDialog.open = false
    },
    handleDoctorDelete(row) {
      this.form.doctorList.splice(this.form.doctorList.indexOf(row), 1)
    },
    chooseGoods() {
      this.goodsDialog.open = true
    },
    closeChooseGoods() {
      this.goodsDialog.open = false
    },
    selectConfirmGoods(data) {
      this.form.goodsList = []
      data.forEach(item => {
        this.form.goodsList.push(item)
      })
      this.goodsDialog.open = false
    },
    handleGoodsDelete(row) {
      this.form.goodsList.splice(this.form.goodsList.indexOf(row), 1)
    },
    choosePackage() {
      this.packageDialog.open = true
    },
    closeChoosePackage() {
      this.packageDialog.open = false
    },
    selectConfirmPackage(data) {
      this.form.packageList = []
      data.forEach(item => {
        this.form.packageList.push(item)
      })
      this.packageDialog.open = false
    },
    handlePackageDelete(row) {
      this.form.packageList.splice(this.form.packageList.indexOf(row), 1)
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const params = {
            id: this.form.id,
            title: this.form.title,
            theme: this.form.theme,
            content: this.form.content,
            goodsIds: this.form.goodsList.map(item => item.goodsId),
            packageIds: this.form.packageList.map(item => item.packageId),
            doctorIds: this.form.doctorList.map(item => item.doctorId),
            videoIds: this.form.videoList.map(item => item.videoId),
          }

          this.addOrUpdating = true
          if (this.form.id) {
            update(params).then(res => {
              this.msgSuccess("修改成功");
              this.open = false
              this.getList()
            })
            return
          }

          add(params).then(res => {
            this.msgSuccess("新增成功");
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.open = false
      this.reset()
    }
  }
}
</script>

<style scoped>
.detail-container {
  padding: 12px 16px 20px;
}

.detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 4px 0 8px;
  margin-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.detail-title {
  font-size: 16px;
  font-weight: 600;
}

.block-card {
  margin-bottom: 12px;
}

.card-header {
  font-weight: 600;
}

.theme-wrapper {
  display: flex;
  align-items: center;
  min-height: 120px;
}

.theme-image {
  max-width: 100%;
  max-height: 240px;
  width: auto;
  display: block;
}

.image-gallery {
  display: flex;
  flex-wrap: wrap;
}

.gallery-item {
  width: 100px;
  height: 100px;
  margin-right: 8px;
  margin-bottom: 8px;
}

.thumb {
  max-height: 80px;
  width: auto;
}

.popover-img {
  max-width: 150px;
  max-height: 150px;
  width: auto;
}
</style>
