<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!-- <el-form-item label="家族" prop="familyId" v-if="familyId == 0">
        <el-select
          v-model="queryParams.familyId"
          placeholder="请选择家族"
          clearable
          size="small">
          <el-option
            v-for="item in familyOptions"
            :key="'f' + item.id"
            :label="item.fullName"
            :value="item.id"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="家族名称" prop="familyId">
        <span v-if="family">{{ family.fullName }}</span>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </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-hasPermi="['system:album: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-hasPermi="['system:album: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-hasPermi="['system:album:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:album:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="albumList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" v-if="false" />
      <el-table-column label="家族" align="center" prop="familyId">
        <template slot-scope="scope">
          <span v-if="scope.row.family">{{ scope.row.family.fullName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="相簿名称" align="center" prop="title">
        <template slot-scope="scope">
          <el-link type="primary" @click.native="goPhoto(scope.row)">{{
            scope.row.title
          }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="相簿描述" align="center" prop="contents" />
      <el-table-column label="封面图片" align="center" prop="url">
        <template slot-scope="scope">
          <el-image
            class="lsw_square"
            :fit="'contain'"
            style="max-width: 80px; border-radius: 20%"
            :src="baseUrl+scope.row.url"
            :preview-src-list="[baseUrl+scope.row.url]"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="图片数量" align="center" prop="photoCount"></el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="状态"
        align="center"
        prop="status"
        :formatter="statusFormat"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:album:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:album:remove']"
            >删除</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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- <el-form-item label="家族" prop="familyId">
          <el-select
            v-model="form.familyId"
            v-if="!family"
            @change="familySelect"
            placeholder="请选择家族"
          >
            <el-option
              v-for="item in familyOptions"
              :key="'f' + item.id"
              :label="item.fullName"
              :value="item.id"
            />
          </el-select>
          <el-tag v-else
            ><span v-if="family">{{ family.fullName }}</span></el-tag
          >
        </el-form-item> -->
         <el-form-item label="家族" prop="familyId">
          <el-tag v-model="form.familyId"><span v-if="family">{{ family.fullName }}</span></el-tag>
        </el-form-item>
        <el-form-item label="相簿名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="相簿描述" prop="contents">
          <el-input
            v-model="form.contents"
            type="textarea"
            placeholder="请输入相簿描述"
          />
        </el-form-item>
        <el-form-item label="封面图片" prop="url">
          <!-- <el-input v-model="form.url" placeholder="请输入默认图片url(应该获取第一张图片作为默认)" /> -->
          <el-button icon="el-icon-scissors" @click="getImg()"
            >选取图片</el-button
          >
          <el-image
            v-if="form.url"
            :fit="'contain'"
            style="
              max-width: 50%;
              display: block;
              margin-top: 10px;
              border-radius: 20%;
            "
            :src="baseUrl+form.url"
            :preview-src-list="[baseUrl+form.url]"
          ></el-image>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
      </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>
    <!-- 剪裁图片对话框 -->
    <cropper
      v-if="showImg"
      ref="upload"
      @img="setImg"
      :fixed_number="fixedNumber"
      :mod-name="modName"
    ></cropper>
  </div>
</template>

<script>
import {
  listAlbum,
  getAlbum,
  delAlbum,
  addAlbum,
  updateAlbum,
  exportAlbum,
} from "@/api/system/family/album";
import { listFamily, getFamily } from "@/api/system/family";
import cropper from "@/components/cropper";
export default {
  name: "Album",
  components: {
    cropper,
  },
  data() {
    var validatefamilyId = (rule, value, callback) => {
        if (value == '' || value<=0 || value == null || value == undefined) {
          callback(new Error('家族不能为空'));
        } else{
          callback();
        }
      };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 家族相簿表格数据
      albumList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        familyId: null,
        title: null,
        status: null,
      },
      // 表单参数
      form: { id: undefined },
      // 表单校验
      rules: {
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        familyId: [{ validator:validatefamilyId, trigger: "blur" }],
      },
      familyId: undefined,
      family: undefined,
      familyOptions: [],
      // 图片裁剪比例
      fixedNumber: [1, 1],
      showImg: false,
      modName: "family",
      baseUrl:undefined,
    };
  },
  activated() {
    this.init();
  },
  mounted() {
    this.baseUrl = process.env.VUE_APP_BASE_API;
    this.init();
    this.getDicts("sys_show_hide").then((response) => {
      this.statusOptions = response.data;
    });
    this.getFamilyOptions();
  },
  methods: {
    init() {
      this.familyId = this.$route.query.fid;
      if (this.familyId) {
        this.queryParams.familyId = this.familyId;
        this.getFamilyById(this.familyId);
         this.getList();
      }else{
        this.loading = false;
      }
     
    },
    /**获取单个家族信息 */
    getFamilyById(_familyId) {
      getFamily(_familyId).then((res) => {
        this.family = res.data;
      });
    },

    //获取家族列表
    getFamilyOptions() {
      var _params = {
        pageNum: 1,
        pageSize: 10000000,
      };
      listFamily(_params).then((res) => {
        if (res.code == 200) {
          this.familyOptions = res.rows;
        }
      });
    },

    /** 查询家族相簿列表 */
    getList() {
      this.loading = true;
      const fid = this.$route.query.fid;
      this.queryParams.familyId = fid;
      listAlbum(this.queryParams).then((response) => {
        this.albumList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        familyId: null,
        title: null,
        contents: null,
        url: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        status: null,
        delFlag: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加家族相簿";
      this.$nextTick(() => {
        if (this.family) {
          this.form.familyId = this.family.id;
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getAlbum(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改家族相簿";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateAlbum(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addAlbum(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除家族相簿编号为"' + ids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delAlbum(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有家族相簿数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportAlbum(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        })
        .catch(function () {});
    },
    //选取图片
    getImg() {
      //设置模块id
      this.modName += "/" + this.family.code;

      this.showImg = true;
      this.$nextTick(() => {
        this.$refs.upload.editCropper();
      });
    },
    //设置图片
    setImg(img) {
      this.form.url = img;
    },
    //新增修改时选择家族后
    familySelect(nval) {
      this.familyOptions.forEach((item) => {
        if (item.id == nval) {
          this.family = item;
          return;
        }
      });
      console.log(this.family);
    },
    //跳转到相册内容
    goPhoto(item) {
      // console.log(item);
      this.$router.push({
        path: "/family/photo",
        query: {
          fid: item.familyId,
          albid: item.id,
        },
      });
    },
  },
};
</script>
