<template>
  <div style="padding: 20px">
    <el-form ref="dataForm" :model="dataForm" :rules="dataFormRules" label-position="left" label-width="120px">
      <el-form-item v-if="!(inputParam.openType === 'add')" label="单据编号" prop="sheetId">
        <el-input autocomplete="off" placeholder="单据编号" :disabled="true" :value="dataForm.sheetId" />
      </el-form-item>
      <el-form-item label="供应商" prop="venderId">
        <el-select
          v-model="dataForm.venderId"
          :disabled="inputParam.openType === 'view'"
          placeholder="请选择供应商"
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="(item, index) in venderList"
            :key="index"
            :label="item.venderName"
            :value="item.venderId"
            :disabled="item.status !== 'ON'"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="notes">
        <el-input
          v-model="dataForm.notes"
          autocomplete="off"
          placeholder="备注"
          :disabled="inputParam.openType === 'view'"
        />
      </el-form-item>
      <el-row>
        <el-col>
          <el-button size="small" :disabled="inputParam.openType === 'view'" @click="innerVisible = true"
            >添加商品</el-button
          >
        </el-col>
        <el-col>
          <el-table
            ref="goodsTable"
            :data="dataForm.items"
            height="300"
            size="mini"
            border
            header-cell-class-name="headerRowColor"
            style="width: 100%; margin: 15px 0"
          >
            <el-table-column prop="goodsId" label="辅材编号" width="80" />
            <el-table-column prop="goodsName" label="辅材名称" width="180" />
            <el-table-column prop="goodsSpecification" label="规格" />
            <el-table-column prop="cost" label="进价">
              <template slot-scope="scope">
                <el-input v-model="scope.row.cost" :disabled="inputParam.openType === 'view'" />
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.status"
                  placeholder="请选择状态"
                  style="width: 100%"
                  :disabled="inputParam.openType === 'view'"
                >
                  <el-option
                    v-for="(item, index) in select_item_flag"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column v-if="!(inputParam.openType === 'view')" align="center" label="" min-width="50">
              <template slot-scope="scope">
                <el-button type="text" @click="delItem(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-row>
            <el-col :span="24"
              ><div>共 {{ goodsTotalCount }} 条记录</div></el-col
            >
          </el-row>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog
      width="60%"
      title="商品列表"
      :visible.sync="innerVisible"
      append-to-body
      :close-on-click-modal="false"
      @close="
        $refs.goodsTable.clearSelection()
        searchGoods = ''
      "
    >
      <el-input
        v-model="searchGoods"
        size="mini"
        placeholder="输入关键字搜索"
        style="margin-bottom: 5px"
        :clearable="true"
      />
      <el-table
        ref="goodsTable"
        :data="
          goodsList.filter(
            data =>
              !searchGoods ||
              data.goodsName.toLowerCase().includes(searchGoods.toLowerCase()) ||
              data.categoryName.toLowerCase().includes(searchGoods.toLowerCase())
          )
        "
        :row-key="getRowKeys"
        height="400"
        size="mini"
        border
        header-cell-class-name="headerRowColor"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" :reserve-selection="true" />
        <el-table-column prop="goodsId" label="辅材编号" width="80" />
        <el-table-column prop="goodsName" label="辅材名称" width="280" />
        <el-table-column prop="goodsCode" label="辅材代码" />
        <el-table-column prop="categoryName" label="小类名称" />
        <el-table-column prop="goodsSpecification" label="规格" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="selGoods">确 定</el-button>
      </div>
    </el-dialog>
    <div style="text-align: right">
      <el-button @click="cancelForm">取 消</el-button>
      <el-button v-if="!(inputParam.openType === 'view')" type="primary" @click="submitForm">保 存</el-button>
    </div>
  </div>
</template>

<script>
import { addVenderGoodsSheet, editVenderGoodsSheet, getVenderGoodsSheet } from '@/api/material-system/vender'
import { listPageV2 } from '@/api/auxiliaryFittings/supplier'
import { materialNormList } from '@/api/auxiliaryPriceManagement'
export default {
  name: 'VenderGoodsArea',
  props: {
    inputParam: {
      type: Object,
      default: function () {
        return {
          openType: 'add',
          sheetId: ''
        }
      }
    }
  },
  data() {
    return {
      loading: true,
      dataForm: {
        sheetId: '', // 单据ID
        venderId: '', // 供应商ID
        venderName: '',
        notes: '', // 备注
        items: [] // 关系辅材列表
      },
      goodsList: [], // 商品列表
      venderList: [], // 供应商列表
      select_item_flag: [
        { label: '有效', value: 'ON' },
        { label: '无效', value: 'OFF' }
      ],
      dataFormRules: {
        venderId: [{ required: true, message: '请选择供应商', trigger: 'change' }]
      },
      innerVisible: false,
      searchGoods: ''
    }
  },
  computed: {
    goodsTotalCount: function () {
      return this.dataForm && this.dataForm.items ? this.dataForm.items.length : 0
    }
  },
  mounted() {
    this.getDetail()
    this.getVenderList()
    if (this.inputParam.openType === 'add') {
      this.getMaterialList()
    }
  },
  methods: {
    getDetail(id) {
      this.loading = true
      const openType = this.inputParam.openType
      if (openType !== 'add') {
        getVenderGoodsSheet({ id: id || this.inputParam.sheetId }).then(res => {
          this.setDataForm(res.data)
          this.loading = false
        })
      } else {
        this.loading = false
      }
    },
    setDataForm(data) {
      this.dataForm = {
        sheetId: data.sheetId, // 单据编号
        venderId: data.venderId, // 供应商Id
        notes: data.notes, // 备注
        items: data.items // 关系商品列表
      }
    },
    cancelForm() {
      this.$emit('getList')
      this.$emit('update:isOpen', false)
    },
    // 获取辅材列表
    getMaterialList() {
      materialNormList({
        pageNum: 1,
        pageSize: -1,
        params: [{ param: 'a.status', compare: '=', value: 'ON' }]
      }).then(res => {
        this.goodsList = res.data.records
        console.log(res.data.records)
      })
    },
    // 获取供应商列表
    getVenderList() {
      listPageV2({
        pageNum: 1,
        pageSize: -1,
        params: [
          { param: 'a.status', compare: '=', value: 'ON' },
          { param: 'a.vender_type', compare: 'like', value: '辅材' }
        ]
      }).then(res => {
        this.venderList = res.data.records
      })
    },
    // 提交 新增编辑 供应商关系商品维护单
    submitForm() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.dataForm.venderName = this.venderList?.find(item => item.venderId === this.dataForm.venderId)?.venderName
          if (this.inputParam.openType === 'edit') {
            editVenderGoodsSheet(this.dataForm).then(() => {
              this.cancelForm()
              this.$successMsg('编辑成功')
            })
          } else {
            addVenderGoodsSheet(this.dataForm).then(() => {
              this.cancelForm()
              this.$successMsg('新增成功')
            })
          }
        }
      })
    },
    // 选中辅材添加到表单中
    selGoods() {
      this.$refs.goodsTable.selection.forEach(value => {
        const index = this.dataForm.items.findIndex(item => {
          return item.goodsId === value.goodsId
        })
        // 添加不在列表的商品
        if (index < 0) {
          this.dataForm.items.push({
            goodsId: value.goodsId,
            goodsName: value.goodsName,
            goodsSpecification: value.goodsSpecification,
            cost: 0,
            status: 'ON'
          })
        }
      })
      this.$refs.goodsTable.clearSelection()
      this.innerVisible = false
    },
    // 删除明细
    delItem(index) {
      this.dataForm.items.splice(index, 1)
    },
    getRowKeys(row) {
      return row.id
    }
  }
}
</script>

<style scoped></style>
