<!--
 * @Description: 添加展现标签集对话框组件
 * @Author: wenjing
 * @Date: 2023-05-15 11:30:56
-->
<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="950px" center
		:before-close="handleCloseDialog" :close-on-click-modal="false" @open="handleOpenDialog">
    <el-form :ref="formName" :model="tagSetForm" :rules="tagSetRules" size="small" label-width="100px">
      <div style="display:flex;">
        <!-- 表单左侧字段输入块 -->
        <div>
          <!-- key+版本行 -->
          <div style="display:flex;">
            <el-form-item label="key:" prop="key">
              <el-input style="width:180px;" v-model="tagSetForm.key" clearable
                placeholder="请输入唯一键名称" :disabled="mode == 'edit'"/>
            </el-form-item>
            <el-form-item style="margin-left:15px;" label="版本号:" prop="version">
              <el-select style="width:175px" v-model="tagSetForm.version" placeholder="请选择版本号" clearable>
                <el-option v-for="(item, index) in versionList" :key="index" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </div>
          <!-- 图片宽、高行 -->
          <div style="display:flex;">
            <el-form-item label="图片宽:" prop="width">
              <el-input style="width:180px;" v-model.number="tagSetForm.width" placeholder="请输入" clearable>
                <template slot="append">px</template>
              </el-input>
            </el-form-item>
            <el-form-item style="margin-left:15px;" label="图片高:" prop="height">
              <el-input style="width:175px;" v-model.number="tagSetForm.height" placeholder="请输入" clearable>
                <template slot="append">px</template>
              </el-input>
            </el-form-item>
          </div>
          <div style="display:flex;" v-for="(status, index) in tagSetForm.statusList" :key="index">
            <el-form-item :label="'状态' + (index + 1) + ':'">
              <el-checkbox v-model="status.selected" :disabled="index == 0" 
                @change="handleChgStatus($event, index)">启用</el-checkbox>
            </el-form-item>
            <el-form-item v-if="status.selected" label="名称:" 
              :prop="'statusList.' + index + '.name'" :rules="tagSetRules.statusList.name">
              <el-input style="width:95px;" v-model="status.name" placeholder="请输入" clearable/>
            </el-form-item>
            <div style="display:flex" v-if="status.selected">
              <el-form-item label="文本颜色:" 
                :prop="'statusList.' + index + '.color'" :rules="tagSetRules.statusList.color">
                <el-input v-show="false" v-model="status.color"></el-input>
                <div class="color-block">&ensp;{{tagColorStr(index)}}&ensp;</div>
              </el-form-item>
              <el-form-item label-width="0px">
                <el-color-picker v-model="status.color" />
              </el-form-item>
            </div>
          </div>
          <div style="display:flex;" v-for="(btn, index) in tagSetForm.btnList" :key="btn.action">
            <el-form-item :label="btn.actionName + ':'">
              <el-checkbox v-model="btn.selected">启用</el-checkbox>
            </el-form-item>
            <el-form-item v-if="btn.selected" label="名称:" :prop="'btnList.' + index + '.btnName'" :rules="tagSetRules.btnList.name">
              <el-input style="width:100px;" v-model="btn.btnName" placeholder="请输入" clearable/>
            </el-form-item>
          </div>
        </div>
        <!-- 表单右侧图片上传块 -->
        <el-form-item prop="imageFile" label-width="20px">
          <el-upload class="img-uploader" action="" accept="image/jpeg,image/png" 
            :auto-upload="false" :show-file-list="false" :on-change="handleChangeImg">
            <img v-if="tagSetForm.imageFile" class="image" :src="imageString" />
            <i v-else class="el-icon-plus img-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </div>
    </el-form>
    <div style="text-align: center; margin-top: 20px">
      <el-button size="small" @click="handleCloseDialog">取 消</el-button>
      <el-button type="primary" size="small" @click="handleSave">保 存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import aupUtil from '../../common/AupUtil.js';

export default {
  name: 'RenderTagSetDlg',
  props: ['dialogVisible', 'mode', 'tagSetKey'],
  
  data() {
    return {
      formName: 'tagSetForm',
      tagSetForm: {},
      imageString: '',              //存放画像图片路径或Base64串
      versionList: [],
      btnActionMap: null,

      tagSetRules: {
				key: [
          { required: true, message: '请输入唯一键名称', trigger: 'blur' },
          { type: 'string', pattern: aupUtil.keyPattern, message: aupUtil.keyErrMsg, trigger: 'blur' },
					{ min: 1, max: 30, message: '最大长度不超过30个字符', trigger: 'blur' },
				],
        version: [
          { required: true, message: '请选择版本号', trigger: 'blur' },
				],
        imageFile: [
          { required: true, message: '图片不能为空', trigger: 'blur' },
				],
        width: [
          { required: true, message: '图片宽度不能为空', trigger: 'blur' },
          { type: 'number', min: 200, max: 1000, message: '宽度必须在200-1000之间', trigger: 'blur' },
          { pattern: /^\+?[1-9]\d*$/, message: '数值须大于0', trigger: 'blur'},
				],
        height: [
          { required: true, message: '图片高度不能为空', trigger: 'blur' },
          { type: 'number', min: 200, max: 1000, message: '高度必须在200-1000之间', trigger: 'blur' },
          { pattern: /^\+?[1-9]\d*$/, message: '数值须大于0', trigger: 'blur'},
				],
        statusList: {
          name: [
            { required: true, message: '状态名不能为空', trigger: 'blur' },
				  ],
          color: [
            { required: true, message: '不能为空', trigger: 'blur' },
				  ]
        },
        btnList: {
          name: [
            { required: true, message: '状态名不能为空', trigger: 'blur' },
				  ],
        }
			}
    }
  },

  computed: {
    title() {
      return (this.mode =='add') ? '新增展现标签集' : '编辑展现标签集';
    },
    
    tagColorStr() {
      return function(index) {
        let color = this.tagSetForm.statusList[index].color;
        let text = (color) ? color : '未定义';
        return text;
      }
    },
  },
  
  methods:{
    getRenderTagSetDO() {
      let url =  (this.mode =='add') ? this.commonUrl.URL_GET_RENDER_TAG_SET_DO4_ADD
        : this.commonUtil.fillUrlArgments(this.commonUrl.URL_GET_RENDER_TAG_SET_DO4_UPDATE, this.tagSetKey);
      this.appAxios("GET", url).then(result => {
        if (result == null) return;
        
        this.tagSetForm = result.data.tagSet;
        if (this.tagSetForm.width === 0) {
          this.tagSetForm.width = '';
        }
        if (this.tagSetForm.height === 0) {
          this.tagSetForm.height = '';
        }

        this.versionList = result.data.versionList;
        this.btnActionMap = result.data.btnActionMap;
        
        this.imageString = (this.mode =='add') ? '' : 
          this.commonUtil.fillUrlArgments(this.commonUrl.URL_DOWNLOAD_AUP_IMAGE,
            this.tagSetForm.key, this.tagSetForm.imageFile);
      })
    },

    handleOpenDialog() {
      this.tagSetForm = {};
			this.getRenderTagSetDO();
		},
    
    handleChgStatus(event, curIndex) {
      if (!event) {
        for (let index = curIndex; index < this.tagSetForm.statusList.length; index++) {
          this.tagSetForm.statusList[index].selected = false;
        }
        this.tagSetForm.maxStatus = curIndex;
      } else {
        for (let index = 1; index <= curIndex; index++) {
          this.tagSetForm.statusList[index].selected = true;
        }
        this.tagSetForm.maxStatus = curIndex + 1;
      }
    },

    async handleChangeImg(file) {
      let result = this.imgUtil.validateFileAttrs(file, 600);
      if (result) {
        this.$message.error(result);
        return;
      } 

      this.imageString = await this.imgUtil.blobToBase64(file.raw);
      this.tagSetForm.imageFile = file;
      
      if (!this.tagSetForm.width || !this.tagSetForm.height) {
        const img = new Image();
        img.src = this.imageString;
        img.onload = () => {
          this.tagSetForm.width = img.width;
          this.tagSetForm.height = img.height;
        };
      }

      // let limitation = {
      //   maxSize: 1024,
      //   maxWidth: 100.0,
      //   maxHeight: 0,
      //   extLimit: {
      //     limitType: 1,
      //     minRatio: 0.4,
      //     minRatioText: "100:40",
      //     maxRatio: 1.5,
      //     maxRatioText: "100:150",
      //   },
      //   returnData: {},
      // };
      // this.imgUtil.validateAndCompressImg(file, limitation).then((data) => {
      //   if (data.errorText && data.errorText.length) {
      //     this.$message.error(data.errorText);
      //   } else {
      //     this.imageUrl = file;
      //   }
      // });
    },

    handleCloseDialog() {
      this.$refs[this.formName].clearValidate();
      this.$emit("close", false);
    },

    handleSave() {
      this.$refs[this.formName].validate((valid) => {
        if (!valid) return false;
        
        let url = (this.mode =='add') ? this.commonUrl.URL_SAVE_RENDER_TAG_SET
          : this.commonUrl.URL_UPDATE_RENDER_TAG_SET;
        let data = JSON.parse(JSON.stringify(this.tagSetForm));
        let fileMap = new Map();
        
        // 当新增标签集，或在修改标签集时改变了图片时，tagSetForm.imageFile为file对象，否则(编辑时未改变图片)为'string'
        if (typeof(this.tagSetForm.imageFile) === 'object') {
          fileMap.set("imageFile", this.tagSetForm.imageFile.raw);
          data.imageFile = '';
        } 
        
        let requestData = {
          url: url,
          method: (this.mode =='add') ? 'POST' : 'PUT',
          contentType: this.commonConst.CNTYPE_JSON,
          param: {name: 'tagSet', value: data},
          files: fileMap
        };
        this.vueRequest(requestData).then((result) => {
          if (result == null) return;
          this.$emit("close", true);
        });
      })
    },
  }
}
</script>

<style scoped>
.color-block {
  margin-right: 4px;
  padding: 5px 0 5px 5px;
  width: 80px; 
  height: 20px;
  line-height: 20px;
  text-align: left;
  font-size: 13px;
  
  color: lightgray;
  background: white;
  border-radius: 3px;
  border: solid lightgray 1px
}

.img-uploader {
  margin-right: 20px;
  width: 300px;
  height: 340px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.img-uploader:hover {
  border-color: #409EFF;
}
.image {
  width: 300px;
  height: 340px;
  display: block;
}
.img-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 340px;
  line-height: 340px;
  text-align: center;
}
</style>
