<template>
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    :bodyStyle="bodyStyle"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    :footer="null">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item label="标识" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="[ 'title', validatorRules.title]" :maxlength="100" placeholder="请输入标识，100字以内"></a-input>
        </a-form-item>
          
        <a-form-item label="版本号" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="[ 'version', validatorRules.version]" :maxlength="100" placeholder="请输入版本号，100字以内"></a-input>
        </a-form-item>
          
        <a-form-item label="版本内容" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-editor v-decorator="['description', validatorRules.description]" triggerChange rows="4" placeholder="请输入版本内容"/>
          <!--<a-textarea  v-decorator="['description', validatorRules.description]" rows="4" placeholder="请输入版本内容"/>-->
        </a-form-item>

        <a-form-item label="app系统" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-dict-select-tag  v-decorator="['appSystem', validatorRules.appSystem]"  :type="'radio'" @change="selectAppSystem" :triggerChange="true" dictCode="app_system"/>
        </a-form-item>

        <template v-if="model.appSystem==0">
        <a-form-item label="下载地址" :labelCol="labelCol" :wrapperCol="wrapperCol" :required="true">
          <a-upload
            name="file"
            :multiple="true"
            :action="uploadAction"
            :headers="headers"
            :data="{'isup':1,'bizPath':bizPath}"
            :fileList="fileList"
            :beforeUpload="beforeUpload"
            @change="handleChange">
            <a-button>
              <a-icon type="upload"/>
              {{ text }}
            </a-button>
            <span style="margin-left: 10px">请上传文件</span>
          </a-upload>
        </a-form-item>
        </template>
          
        <a-form-item label="是否强制更新" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-dict-select-tag  v-decorator="['isForceUpdate', validatorRules.isForceUpdate]"  :type="'radio'" @change="selectIsForceUpdate" :triggerChange="true" dictCode="is_force_update"/>
        </a-form-item>

        
      </a-form>
    </a-spin>
    <div class="drawer-bootom-button">
      <a-button class="ant-btn"  @click="handleCancel">取消</a-button>
      <a-button class="ant-btn ant-btn-primary" style="margin-left: 8px"  @click="handleOk">确定</a-button>
    </div>
  </a-modal>
</template>

<script>

  import { httpAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import JDate from '@/components/jeecg/JDate'
  import JEditor from '@/components/jeecg/JEditor'
  import Vue from 'vue'
  import { ACCESS_TOKEN } from '@/store/mutation-types'

  const FILE_TYPE_ALL = "all"
  const FILE_TYPE_PDF = 'pdf'
  const uidGenerator = () => {
    return '-' + parseInt(Math.random() * 10000 + 1, 10)
  }
  const getFileName = (path) => {
    if (path.lastIndexOf('\\') >= 0) {
      let reg = new RegExp('\\\\', 'g')
      path = path.replace(reg, '/')
    }
    return path.substring(path.lastIndexOf('/') + 1)
  }

  export default {
    name: "HwVersionModal",
    components: { 
      JDate,
      JEditor
    },
    data () {
      return {
        disableSubmit:false,
        uploadAction: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
        urlDownload: window._CONFIG['domianURL'] + '/hpSys/common/ossDownload',
        headers: {},
        fileList: [],
        form: this.$form.createForm(this),
        title:"操作",
        width:800,
        bodyStyle: {
          paddingTop: '20px',
          paddingBottom:'50px',
          height: (window.innerHeight * 0.62) + 'px',
          'overflow-y': 'auto'
        },
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        validatorRules:{
        title:{ rules: [{ required: true, message: '请输入标识!' }] },
        version:{ rules: [{ required: true, message: '请输入版本号!' }] },
        description:{ rules: [{ required: true, message: '请输入版本内容!' }] },
        downUrl:{ rules: [{ required: true, message: '请输入!' }] },
        isForceUpdate:{ rules: [{ required: true, message: '请选择是否强制更新!' }] },
        appSystem:{ rules: [{ required: true, message: '请选择app系统!' }] },
        createTime:{},
        createBy:{},
        updateTime:{},
        updateBy:{},
        delFlag:{},
        remarks:{},
        },
        url: {
          add: "/hwversion/hwVersion/add",
          edit: "/hwversion/hwVersion/edit",
        }
     
      }
    },
    props: {
      text: {
        type: String,
        required: false,
        default: '点击上传'
      },
      fileType: {
        type: String,
        required: false,
        default: FILE_TYPE_ALL
      },
      /*这个属性用于控制文件上传的业务路径*/
      bizPath: {
        type: String,
        required: false,
        default: '/hpwork/hwVersion'
      },
      value: {
        type: String,
        required: false
      },
      //此属性被废弃了
      triggerChange: {
        type: Boolean,
        required: false,
        default: false
      }
    },
    created () {
      const token = Vue.ls.get(ACCESS_TOKEN)
      this.headers = { 'X-Access-Token': token }
    },
    methods: {
      add () {
        this.model.downUrl=null
        this.fileList=[]
        this.edit({});
      },
      edit (record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'title','version','description','downUrl','isForceUpdate','appSystem','createTime','createBy','updateTime','updateBy','delFlag','remarks'))
          this.form.setFieldsValue({ appSystem:this.model.appSystem!=null?String(this.model.appSystem):''})
          this.form.setFieldsValue({ isForceUpdate:this.model.isForceUpdate!=null?String(this.model.isForceUpdate):''})
        })
        //回显文件
        this.editFileList(this.model.downUrl)
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
       if(this.model.appSystem==0){
         if(!this.model.downUrl || this.fileList.length==0){
           this.$message.warning('请上传下载文件')
           return
         }
       }
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            console.log("表单提交数据",formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
         
        })
      },
      handleCancel () {
        this.close()
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'title','version','description','downUrl','isForceUpdate','appSystem','createTime','createBy','updateTime','updateBy','delFlag','remarks'))
      },
      selectAppSystem(e){
        if(e!=null && e!=''){
          this.form.setFieldsValue({ appSystem:e})
        }
        var appSystem = this.form.getFieldValue('appSystem');
        this.model.appSystem=appSystem
      },
      selectIsForceUpdate(e){
        if(e!=null && e!=''){
          this.form.setFieldsValue({ isForceUpdate:e})
        }
        var isForceUpdate = this.form.getFieldValue('isForceUpdate');
        this.model.isForceUpdate=isForceUpdate
      },
      handleCancel() {
        this.close()
      },


      //回显文件所用
      editFileList(paths) {
        console.log(11111111,fileList)
        if (!paths || paths.length == 0) {
          //return [];
          // update-begin- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
          this.fileList = []
          return
          // update-end- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
        }
        let fileList = []
        let arr = paths.split(',')
        for (var a = 0; a < arr.length; a++) {
          fileList.push({
            uid: uidGenerator(),
            name: getFileName(arr[a]),
            status: 'done',
            url: this.urlDownload + '?fileName=' + arr[a],
          })
        }
        this.fileList = fileList
        console.log(11111111,fileList)
      },
      //上传文件所用
      initFileList(paths) {
        if (!paths || paths.length == 0) {
          //return [];
          // update-begin- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
          this.fileList = []
          return
          // update-end- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
        }
        let fileList = []
        let arr = paths.split(',')
        for (var a = 0; a < arr.length; a++) {
          fileList.push({
            uid: uidGenerator(),
            name: getFileName(arr[a]),
            status: 'done',
            url: this.urlDownload + arr[a],
            response: {
              status: 'history',
              message: arr[a]
            }
          })
        }
        this.fileList = fileList
      },
      handlePathChange() {
        let uploadFiles = this.fileList
        let path = ''
        if (!uploadFiles || uploadFiles.length == 0) {
          path = ''
        }
        let arr = []

        for (var a = 0; a < uploadFiles.length; a++) {
          arr.push(uploadFiles[a].response.message)
        }
        if (arr.length > 0) {
          path = arr.join(',')
        }
        this.$emit('change', path)
      },
      beforeUpload(file) {
        var fileType = file.type

        if (this.fileList.length>=1) {
          this.$message.warning('只能上传一个文件')
          return false
        }
      },
      handleChange(info) {

        if (info.fileList.length>1) {
          return false
        }
        console.log('--文件列表改变--')
        let fileList = info.fileList
        if (info.file.status === 'done') {
          if (info.file.response.success) {
            fileList = fileList.map((file) => {
              if (file.response) {
                // file.url = this.urlDownload+file.response.message;
                this.model.downUrl = file.response.message
              }
              return file
            })
          }
          this.$message.success(`${info.file.name} 上传成功!`)
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败.`)
        } else if (info.file.status === 'removed') {
          this.handleDelete(info.file)
        }
        this.fileList = fileList
        if (info.file.status === 'done' || info.file.status === 'removed') {
          this.handlePathChange()
        }
      },
      handleDelete(file) {
        //如有需要新增 删除逻辑
        console.log(file)
        this.fileList = [];
      }

    }
  }
</script>
<style>
  .drawer-bootom-button {
    position: absolute;
    bottom: -8px;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
  }
</style>