<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户名称" prop="clientId">
        <el-select v-model="queryParams.clientId" placeholder="请选择 客户" clearable filterable remote :remote-method="getClientList">
          <el-option v-for="item in clientList" :key="item.clientId" :value="item.clientId" :label="item.clientName"/>
        </el-select>
      </el-form-item>
      <el-form-item label="产品" prop="itemId">
        <el-select v-model="queryParams.itemId" placeholder="产品名称" clearable filterable remote :remote-method="getItemList">
          <el-option v-for="item in itemList" :key="item.itemId" :value="item.itemId" :label="item.itemName"/>
        </el-select>
      </el-form-item>
      <el-form-item label="有效期起" prop="validFrom">
        <el-date-picker clearable v-model="queryParams.validFrom" type="date" value-format="yyyy-MM-dd" placeholder="请选择有效期起" >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="有效期至" prop="validTo">
        <el-date-picker clearable v-model="queryParams.validTo" type="date" value-format="yyyy-MM-dd" placeholder="请选择有效期至" >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择状态">
          <el-option label="草稿" value="0" />
          <el-option label="审批中" value="1" />
          <el-option label="发布中" value="2" />
          <el-option label="已发布" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" 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"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['qt:factoryQuote:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['qt:factoryQuote:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['qt:factoryQuote:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['qt:factoryQuote:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="factoryQuoteList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column label="客户编号" width="120" prop="clientCode"/>
      <el-table-column label="客户名称" width="180" prop="clientName"/>
      <el-table-column label="产品编号" width="160" prop="itemCode"/>
      <el-table-column label="产品名称" min-width="200" show-overflow-tooltip prop="itemName"/>
      <el-table-column label="价格" width="100" prop="price"/>
      <el-table-column label="有效期起" prop="validFrom" width="140">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.validFrom, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效期至" prop="validTo" width="140">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.validTo, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="state" width="100">
        <template slot-scope="{row}">
          {{ row.state === '0' ? '草稿' : row.state === '1' ? '审批中' : row.state === '2' ? '发布中' : '已发布'}}
        </template>
      </el-table-column>
      <el-table-column width="120" fixed="right" label="操作" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.state === '0' || scope.row.state === '2'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['qt:factoryQuote:edit']"
          >修改
          </el-button>
          <el-button
            v-if="scope.row.state === '1'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="onAudit(scope.row)"
            v-hasPermi="['qt:factoryQuote:edit']"
          >审批
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['qt:factoryQuote: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="80px">
        <el-form-item label="客户名称" prop="clientId">
          <el-select v-model="form.clientId" placeholder="请选择 客户" clearable filterable remote :remote-method="getClientList" :disabled="form.state === '2'">
            <el-option v-for="item in clientList" :key="item.clientId" :value="item.clientId" :label="item.clientName"/>
          </el-select>
        </el-form-item>
        <el-form-item label="产品" prop="itemId">
          <el-input v-model="form.itemName" readonly placeholder="请选择产品" :disabled="form.state === '2'">
            <el-button slot="append" icon="el-icon-search" @click="$refs['ItemSelectRef'].showFlag = true" ></el-button>
          </el-input>
          <ItemSelect ref="ItemSelectRef" @onSelected="onItemSelect"/>
        </el-form-item>
        <el-form-item v-if="form.state === '2'" label="价格" prop="price">
          <el-input v-model.trim="form.price" type="number" placeholder="请输入价格"/>
        </el-form-item>
        <el-form-item label="有效期起" prop="validFrom" :disabled="form.state === '2'">
          <el-date-picker
            clearable
            v-model="form.validFrom"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择有效期起"
            :disabled="form.state === '2'"/>
        </el-form-item>
        <el-form-item label="有效期至" prop="validTo" :disabled="form.state === '2'">
          <el-date-picker
            clearable
            v-model="form.validTo"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择有效期至"
            :disabled="form.state === '2'"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="form.state == '0'" type="primary" @click="onSaveDraft">暂 存</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addFactoryQuote,
  delFactoryQuote,
  getFactoryQuote,
  listFactoryQuote,
  updateFactoryQuote
} from '@/api/mes/qt/factoryQuote'
import { listClient } from '@/api/mes/md/client'
import { listMdItem } from '@/api/mes/md/mdItem'
import ItemSelect from '@/components/itemSelect/single.vue'

export default {
  name: 'FactoryQuote',
  components: {
    ItemSelect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工厂报价表格数据
      factoryQuoteList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        clientId: null, itemId: null, price: null, validFrom: null, validTo: null, state: null
      },
      // 表单参数
      form: {
        id: null, itemId: null, itemName: null, clientId: null, price: null, validFrom: null, validTo: '9999-01-01', state: '0'
      },
      // 表单校验
      rules: {
        itemId: {required: true, message: '请选择产品', trigger: 'change'},
        clientId: {required: true, message: '请选择客户', trigger: 'change'},
        validFrom: {required: true, message: '请选择起止时间', trigger: 'change'},
        price: {required: true, message: '请输入价格', trigger: 'change'},
      },
      clientList: [],
      itemList: [],
    }
  },
  created() {
    this.getList()
    this.getClientList()
    this.getItemList()
  },
  methods: {
    /** 查询工厂报价列表 */
    getList() {
      this.loading = true
      listFactoryQuote(this.queryParams).then(response => {
        this.factoryQuoteList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    getClientList(clientName) {
      listClient({ clientName, pageNum: 1, pageSize: 100 }).then(res => this.clientList = res.rows)
    },
    getItemList(itemName) {
      listMdItem({itemName, pageNum: 1, pageSize: 100}).then(res => {
        this.itemList = res.rows;
      })
    },

    onItemSelect(row) {
      console.log(row)
      if (row != undefined) {
        this.form.itemId = row.itemId;
        this.form.itemName = row.itemName;
        this.$forceUpdate()
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        clientId: null,
        itemId: null,
        price: null,
        validFrom: null,
        validTo: '9999-01-01',
        state: '0',
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: 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 = '添加工厂报价'
    },
    onAudit(row) {
      this.$confirm('审批工厂报价', '', {
        confirmButtonText: '通过',
        cancelButtonText: '驳回',
        cancelButtonClass: 'cancel-red',
        distinguishCancelAndClose: 1
      }).then(() => {
        updateFactoryQuote({id: row.id, state: '2'}).then(() => {
          this.$message.success('操作成功')
          this.getList()
        })
      }).catch((action) => {
        if (action === 'cancel') {
          updateFactoryQuote({id: row.id, state: '0'}).then(() => {
            this.$message.success('操作成功')
            this.getList()
          })
        }
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getFactoryQuote({id}).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改工厂报价'
      })
    },

    onSaveDraft() {
      this.form.state = '0'
      let editQuote = this.form.id ? updateFactoryQuote : addFactoryQuote
      editQuote(this.form).then(() => {
        this.$modal.msgSuccess('修改成功')
        this.open = false
        this.getList()
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.state = +this.form.state + 1
          if (this.form.id != null) {
            updateFactoryQuote(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addFactoryQuote(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除工厂报价编号为"' + ids + '"的数据项？').then(function() {
        return delFactoryQuote(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('qt/factoryQuote/export', {
        ...this.queryParams
      }, `factoryQuote_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style>
.cancel-red {
  background: #F56C6C;
  color: #ffffff;
}
</style>
