<template>
  <div class="app-container">

    <div class="head-container" style="margin: 10px 0 10px 0;">
      <!-- 搜索 -->
      <el-input
        v-model="query.value"
        clearable
        placeholder="请输入标题"
        style="width: 200px;"
        size="small"
        class="filter-item"
      />
      <el-button class="filter-item" size="small" type="primary" icon="el-icon-search" @click="handleFind" plain>搜索</el-button>
      <el-button
        class="filter-item"
        size="small"
        type="primary"
        icon="el-icon-plus"
        @click="handleAdd"
      >发布新标
      </el-button>
    </div>
    <!--表格渲染-->
    <el-table v-loading="loading" :data="data"  style="width: 100%;">

      <el-table-column prop="title" label="标题" :show-overflow-tooltip="true"  width="250" align="center" />

      <el-table-column label="状态"  align="center" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status ==1">进行中</el-tag>
          <el-tag type="info" v-if="scope.row.status ==2">已结束</el-tag>
          <el-tag type="danger" v-if="scope.row.status ==3">已作废</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="description" :show-overflow-tooltip="true" label="报价方式" width="100" align="center" >
        <template slot-scope="scope">
            <el-tag  color="#5783E6" style="border-color:#5783E6" effect="dark" v-if="scope.row.priceQuotes == 1">总价</el-tag>
            <el-tag effect="dark" color="#82C497" style="border-color:#82C497" v-if="scope.row.priceQuotes == 2">单价</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="备注" :show-overflow-tooltip="true" align="center" />
      <el-table-column prop="appendix" label="附件" align="center" width="100" >
        <template slot-scope="scope">
            <el-button type="text" @click="onLoad(scope.row.appendix)">下载</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="开始时间" align="center" width="160"/>
      <el-table-column prop="endTime" label="截止时间" align="center" width="160"/>

      <el-table-column label="操作" width="150"  fixed="right" align="center">
        <template slot-scope="scope">
          <el-button slot="reference" type="text" icon="el-icon-edit" v-if="scope.row.status == 1" @click="handleEdit(scope.row)">编辑</el-button>
          <el-popover
            :ref="scope.row.id"
            placement="bottom"
            width="180"
          >
            <p>此操作将作废该标，确定要作废吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini"  @click="$refs[scope.row.id].doClose()">取消</el-button>
              <el-button :loading="delLoading" type="primary" size="mini" @click="subDelete(scope.row.id)">确定
              </el-button>
            </div>
            <el-button slot="reference" icon="el-icon-delete" type="text" v-if="scope.row.status == 1">作废</el-button>
          </el-popover>
            <el-button slot="reference" icon="el-icon-view" type="text" v-if="scope.row.status != 1" @click="handleView(scope.row)">投标详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div class="pagination">
      <el-pagination
         @size-change="handleSizeChange"
         :current-page.sync="currentPage"
          :page-sizes="[1,10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
        @current-change="handleCurrentChange"
      />
    </div>

    <!--新增-->
    <el-dialog :append-to-body="true" :close-on-click-modal="false" :visible.sync="dialog" :title="isAdd ? '发布新标' : '修改新标'" width="40%">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" style="width: 370px;" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks" >
          <el-input
            type="textarea"
            style="width: 370px;"
            :autosize="{ minRows: 2, maxRows: 10}"
            placeholder="请输入内容"
            v-model="form.remarks">
          </el-input>
        </el-form-item>
        <el-form-item label="附件" prop="appendix" class="is-required">
          <el-upload
            class="upload-demo"
            drag
            :limit="1"
            :on-preview="handlePreview"
            :on-change="handleChange"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-exceed="handleExceed"
            action="/tender/upload"
            list-type="text"
            :file-list="fileList"
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
          </el-upload>
        </el-form-item>
        <el-form-item label="报价方式" prop="priceQuotes">
            <el-radio v-model="form.priceQuotes" :label="1">总价</el-radio>
            <el-radio v-model="form.priceQuotes" :label="2">单价</el-radio>
        </el-form-item>
        <el-form-item label="发布时间" prop="startTime">
            <!-- <el-date-picker
            v-model="form.startTime"
            type="datetime"
            @change="oncustom"
            size="mini"
            value-format="yyyy-MM-dd HH:mm:ss"
            default-time="00:00:00"
            placeholder="开始日期"
             >
            </el-date-picker>
            <span> ~ </span>
            <el-date-picker
            v-model="form.endTime"
            type="datetime"
            size="mini"
            value-format="yyyy-MM-dd HH:mm:ss"
            default-time="15:00:00"
            placeholder="截止日期"
             >
            </el-date-picker> -->
            <el-date-picker
            v-model="bidDate"
            type="datetimerange"
            size="mini"
            range-separator="~"
            @change="oncustom"
             @clear="onClear"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '15:00:00']"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
            </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button  @click="dialog = false">取消</el-button>
        <el-button :loading="buton" type="primary" @click="doSubmit">确认</el-button>
      </div>
    </el-dialog>

  <!-- 详情 -->
  <el-dialog :append-to-body="true" :visible.sync="viewDialog" title="投标详情" width="90%" center>
     <el-table  center :data="Paramdata"  style="width: 100%;">

      <el-table-column prop="customerName" label="客户名称" show-overflow-tooltip="true"  align="center"/>

      <el-table-column label="报价方式"  align="center">
        <template slot-scope="scope">
           <el-tag  color="#5783E6" style="border-color:#5783E6" effect="dark" v-if="scope.row.priceQuotes == 1">总价</el-tag>
            <el-tag effect="dark" color="#82C497" style="border-color:#82C497" v-if="scope.row.priceQuotes == 2">单价</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="price" :show-overflow-tooltip="true" label="报价金额" align="center" >
         <template slot-scope="scope">
           <div>
             {{scope.row.price | toThousandFilter}}
           </div>
         </template>
      </el-table-column>
      <el-table-column prop="remarks" label="备注" :show-overflow-tooltip="true" align="center" />
      <el-table-column prop="appendix" label="附件" align="center" width="100" >
        <template slot-scope="scope">
            <!-- <el-link type="primary" :href="scope.row.appendix">查看</el-link> -->
            <el-button type="text" @click="onLoad(scope.row.appendix)">下载</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="投标时间" align="center"/>
      <el-table-column prop="userName" label=" 投标帐号" align="center"/>
      <el-table-column prop="status" label=" 投标结果" align="center" >
         <template slot-scope="scope">
           <el-tag type="success" v-if="scope.row.status == 0">已提交</el-tag>
          <el-tag type="success" v-if="scope.row.status == 2">已中标</el-tag>
          <el-tag type="danger" v-if="scope.row.status == 3">未中标</el-tag>
        </template>
      </el-table-column>

    </el-table>
     <div class="pagination">
      <el-pagination
        :current-page.sync="param.page"
        :page-size="param.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total1"
        :page-sizes="[10, 20, 30, 50]"
        background
        @size-change="handleSizeChangeParam"
        @current-change="handleCurrentChangeParam"
      />
    </div>
      <div slot="footer" class="dialog-footer">
        <el-button  @click="viewDialog = false">取消</el-button>
        <el-button :loading="loading" type="primary" @click="viewDialog = false">确认</el-button>
      </div>
  </el-dialog>
  </div>

</template>

<script>
import { getTableList,getQueryId,getQueryAdd,getQueryEdit,getQueryDelete,loadCustomer } from '@/api/bid'

export default {
  data() {
    const checkTel = (rule, value, callback)=>{
     console.log(this.form.appendix)
     console.log(value,"value")
     if(this.form.appendix == null || this.form.appendix == ""){
       callback(new Error("请选择附件"))
       console.log("没过")
     }else{
       callback()
       console.log("过")
     }
    }
    return {
      form: {
      },
      data:[],
      fileList:[],
      dialog:false,
      delLoading:false,
      viewDialog:false,
      loading:false,
      isAdd:false,
      currentPage: 1,
      pageSize: 10,
      total: 0, // 总数量
      rules: {
        title: [
          { required: true, message: '标题不为空', trigger: 'blur' }
        ],
        priceQuotes: [
          { required: true, message: "请选择报价方式", trigger: 'blur' }
        ],
         appendix: [
           { validator: checkTel, trigger: 'change' }
        ]
        // startTime: [
        //   { type:"array",required: true, message: '发布时间不为空', trigger: 'blur' }
        // ]
      },
      queryTypeOptions: [
        { key: 'name', display_name: '字典名称' },
        { key: 'remark', display_name: '描述' }
      ],
      query: {
        type: '',
        value: ''
      },
      param:{
        page:1,
        size:10
      },
      total1:0,
      Paramdata:[],
      bidDate:[],
      buton:false,
    }
  },
  created() {
    this.getDictData()
  },
  methods: {
    // 发布时间
    oncustom(){

console.log(this.bidDate)
      if (this.bidDate != null) {
          this.form.startTime = this.bidDate[0]
            this.form.endTime = this.bidDate[1]
      }
    },
    onClear(){
      this.bidDate =[]
      console.log(this.form)
    },
    // 下载
    onLoad(row){
        // const params = new URLSearchParams()
      // params.append('path', row)
      let a =document.createElement('a')
      // a.href= /bidding/load
      let url = window.location.origin + "/bidding/load?path=" + encodeURIComponent(row)
       a.href = url
       a.click()
    },
    // 搜索
      handleFind: function() {
        this.currentPage = 1
      this.getDictData()
    },
    // 获取详情
    getDictData: function() {
      this.loading = true
      // const params = new URLSearchParams()
      // params.append('current', this.currentPage)
      // params.append('size', this.pageSize)
      const data = {
        page:this.currentPage,
        size:this.pageSize,
        title:this.query.value
      }
      getTableList(data).then(res => {
        console.log(res)
        this.data = res.data.data.records
        this.total = res.data.data.total
        this.loading = false
      })
    },
    // 文件移除的时候
     handleRemove(file, fileList) {
        this.form.appendix = ""
        console.log(file, fileList,this.fileList,"移出");
      },
      // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
      handleChange(file,fileList){
        console.log(file,fileList,"上传")
        if(file.response){
          console.log(file.response,"file")
          this.form.appendix=file.response.data
        }
      },
      // 点击文件列表中已上传的文件时的钩子
      handlePreview(file) {
        console.log(file,"file1");
        // window.location.href = file.url
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个附件，本次选择了 ${files.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },

    // 字典名称提交动作
    doSubmit() {
        console.log(this.form)
      this.$refs['form'].validate((valid) => {
        console.log(valid)
        if (valid) {
          if (this.isAdd) {
            // 新增字典
            this.buton = true
            getQueryAdd(this.form).then((res) => {

              if (res.data.code === 200) {
                  this.dialog = false
              this.getDictData()
              this.buton = false
                this.$message({ message: '操作成功', type: 'success' })
              } else {
                this.$message({ message: res.data.msg, type: 'error' })
              }
            
              this.$refs['form'].resetFields()
            }).catch(err=>{
              this.buton = false
            })
          } else {
            // 更新
            getQueryEdit(this.form).then((res) => {
              if (res.data.code === 200) {
                this.$message({ message: '操作成功', type: 'success' })
              } else {
                this.$message({ message: res.data.msg, type: 'error' })
              }
              this.dialog = false
              this.getDictData()
            })
          }
        }
      })
    },
    formatDate(date) {
      var myyear = date.getFullYear()
      var mymonth = date.getMonth() + 1
      var myweekday = date.getDate()

      if (mymonth < 10) {
        mymonth = '0' + mymonth
      }
      if (myweekday < 10) {
        myweekday = '0' + myweekday
      }
      return myyear + '-' + mymonth + '-' + myweekday
    },
    // 添加字典
    handleAdd: function() {
      this.isAdd = true
      this.form = {}
      const end = new Date()
      const start = new Date()
       end.setTime(start.getTime() + 3600 * 1000 * 24 * 1)
       console.log(this.formatDate(end))
      this.form.startTime = this.formatDate(start) + ' 00:00:00'
       this.form.endTime = this.formatDate(end) + ' 15:00:00'
      this.bidDate=[this.form.startTime,this.form.endTime]
      this.form.appendix = null
      this.fileList = []
      this.dialog = true
        if(this.$refs['form']){
        this.$refs["form"].resetFields();
      }

    },
    // 编辑字典
    handleEdit: function(row) {
      if(this.$refs['form']){
      this.$refs["form"].resetFields();
      }
      let data =JSON.parse(JSON.stringify(row)) 
      this.form = data
      this.bidDate = [data.createTime,data.endTime]
      // this.form.
      // let name = data.appendix.lastIndexOf('/') ;
      if(data.appendix){
          let name = data.appendix.split("\\") ;
          name = name.pop()
          // let name = data.appendix.replace(/(.*\/)*([^.]+).*/ig, "$2");
          this.fileList = [{name:name,url:data.appendix}]
      }
 
      this.dialog = true
      this.isAdd = false

      console.log(data)
    },
    // 详情
    handleView(row){
      this.param.tenderId = row.id
      this.param.page = 1
      this.getParam()
      this.viewDialog =true
    },
    getParam(){
      let data = this.param
      getQueryId(data).then((res)=>{
        console.log(res.data.data.records,"")
        this.Paramdata = res.data.data.records
        this.total1 = res.data.data.total
      })
    },
    // 删除操作
    subDelete(val) {
      let data ={
        id:val
      }
      getQueryDelete(data).then(res => {
        if (res.data.code === 200) {
          this.$message({ message: '已作废', type: 'success' })
          this.getDictData()
        }
      }).catch(err => {
        console.log(err.response.data.message)
      })
      this.$refs[val].doClose()

    },
    // 换页
    handleCurrentChange: function(val) {
      this.currentPage = val
      this.getDictData()
    },
    handleSizeChange(val){
      this.pageSize = val
      this.getDictData()
    },
    handleCurrentChangeParam(val){
      this.param.page = val
      this.getParam()
    },
    handleSizeChangeParam(val){
      this.param.size = val
      this.getParam()
    }
  }
}
</script>

<style scoped>
/* 去掉上传附件时候的过度效果 */
  ::v-deep .el-upload-list__item{transition: none !important;}
</style>
