<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="产品类别" prop="itemTypeName">
        <el-input
          v-model="queryParams.itemTypeName"
          placeholder="请输入产品类别"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模板名称" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入模板名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人名称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入创建人名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人工号" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入创建人工号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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="['pro:scheduleSetupRule: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="['pro:scheduleSetupRule: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="['pro:scheduleSetupRule: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="['pro:scheduleSetupRule:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="scheduleSetupRuleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="客户名称"
        align="center"
        width="120"
        prop="customerName"
      />
      <el-table-column
        label="品牌"
        align="center"
        width="120"
        prop="brandName"
      />
      <el-table-column
        label="产品类别"
        align="center"
        width="120"
        prop="itemTypeName"
      />
      <el-table-column label="产品名称" align="center" prop="itemName" />
      <!-- <el-table-column label="模" align="center" prop="mould" />
      <el-table-column label="版" align="center" prop="plate" /> -->
      <el-table-column label="模板名称" align="center" prop="templateName" />
      <el-table-column label="创建人名称" align="center" prop="nickName" />
      <el-table-column label="创建人工号" align="center" prop="createBy" />
      <el-table-column
        label="操作"
        width="200"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pro:scheduleSetupRule:edit']"
            >查看</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="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="客户名称" prop="customerCode">
              <el-select
                filterable
                v-model="form.customerCode"
                style="width: 100%"
                placeholder="请选择客户名称"
              >
                <el-option
                  v-for="item in customerOptions"
                  :key="item.KUNNR"
                  :label="item.NAME"
                  :value="item.KUNNR"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="品牌" prop="brandCode">
              <el-select v-model="form.brandCode" placeholder="请选择品牌" style="width: 100%" filterable>
                <el-option
                  v-for="item in brandOptions"
                  :key="item.brandCode"
                  :label="item.brandName"
                  :value="item.brandCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="产品类别" prop="itemTypeName">
              <el-input
                v-model="form.itemTypeName"
                disabled
                placeholder="请选择产品类别"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="handleitemType"
                ></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="产品" prop="itemName">
              <el-input v-model="form.itemName" placeholder="请选择产品" disabled>
                <el-button
                  slot="append"
                  @click="handleSelectProduct"
                  icon="el-icon-search"
                ></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="模板" prop="templateId">
              <el-select v-model="form.templateId" placeholder="请选择模板" style="width: 100%" @change="templateChange">
                <el-option
                  v-for="item in templateOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                <el-popover trigger="hover" placement="right">
                  <el-image style="width: 100px; height: 100px" :src="item.filePath" :preview-src-list="[item.filePath]"/>
                  <div slot="reference">{{item.name + '(' +(item.remark || '') + ')'}}</div>
                </el-popover>
              </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitForm">确 定</el-button> -->
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <itemType ref="brSelect" v-if="open" @onSelected="onitemTypeed"></itemType>
    <ItemSelect ref="itemSelect" :isSap="true" @onSelected="onItemSelected"> </ItemSelect>
  </div>
</template>

<script>
import {
  listCustomerLabel,
  updateCustomerLabel,
  delcustomerLabel,
  addCustomerLabel,
  getMmPlnrPlnr,
  getBrand,
} from '@/api/mes/pro/ItemTemplateMapping'
import itemType from '@/components/itemType/single.vue'
import ItemSelect from '@/components/itemSelect/single.vue'
import { listReport } from '@/api/mes/report/ureport'

export default {
  name: 'ItemTemplateMapping',
  components: { itemType, ItemSelect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户产品标签模板对照表表格数据
      scheduleSetupRuleList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemTypeName: null,
        itemName: null,
        customerName: null,
        templateName: null,
        nickName: null,
        createBy: null,
      },
      customerOptions: [],
      brandOptions: [],
      templateOptions: [],
      selectedRows: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        templateId: [
          {
            required: true,
            message: '请选择模板',
            trigger: ['blur', 'change'],
          },
        ]
      },
    }
  },
  created() {
    this.getOptions()
    this.getList()
  },
  methods: {
    templateChange(){
      const item = this.templateOptions.find(v => v.id === this.form.templateId)
      console.log('item', item)
      if (item) {
        this.form.filePath = item.filePath || ''
      } else {
        this.form.filePath = ''
      }
    },
    onItemSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.itemId = obj.itemId
        this.form.itemCode = obj.itemCode
        this.form.itemName = obj.itemName
      }
    },
    getOptions() {
      getMmPlnrPlnr().then((res) => {
        if (res.code === 200) {
          this.customerOptions = res.data
        }
      })
      getBrand().then((res) => {
        if (res.code === 200) {
          this.brandOptions = res.data
        }
      })
      listReport({
        pageNum: 1,
        pageSize: 999999,
        isPrintTemplate: 1,
        reportType: 'package_label',
      }).then((res) => {
        if (res.code === 200) {
          // if (res.rows && res.rows.length > 0) {
          //   res.rows.forEach(element => {
          //     element['name'] = `${element.name}(${element.remark || ''})`
          //   });
          // }
          this.templateOptions = res.rows
        }
      })
    },
    /** 查询客户产品标签模板对照表列表 */
    getList() {
      this.loading = true
      listCustomerLabel(this.queryParams).then((response) => {
        this.scheduleSetupRuleList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        itemCode: null,
        customerName: null,
        brandName: null,
        brandCode: null,
        brandId: null,
        itemId: null,
        itemName: null,
        itemTypeCode: null,
        itemTypeId: null,
        itemTypeName: null,
        sapItemCode: null,
        templateName: null,
        templateType: null,
        templateCode: null,
        templateId: null,
        createBy: null,
        filePath: ''
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    handleSelectProduct() {
      this.$refs.itemSelect.showFlag = true
    },
    handleitemType() {
      this.$refs.brSelect.showFlag = true
    },
    onitemTypeed(row) {
      if (Object.values(row).length > 0) {
        this.form.itemTypeId = row.itemTypeId
        this.form.sapTypeCode = row.sapTypeCode
        this.form.itemTypeCode = row.itemTypeCode
        this.form.itemTypeName = row.itemTypeName
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.selectedRows = selection
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加客户产品标签模板对照表'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if(!row || !row.id) row = this.selectedRows[0]
      this.reset()
      this.form = row
      this.$nextTick(() => {
        this.templateChange()
      })
      this.open = true
      this.title = '查看客户产品标签模板对照表'
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.customerCode) {
            this.form.customerName = this.customerOptions.find(
              (v) => this.form.customerCode === v.KUNNR
            ).NAME
          }
          if (this.form.brandCode) {
            this.form.brandName = this.brandOptions.find(
              (v) => this.form.brandCode === v.brandCode
            ).brandName
          }
          if (this.form.templateId) {
            const template = this.templateOptions.find(
              (v) => this.form.templateId === v.id
            )
            this.form.templateName = template.name
            this.form.templateType = template.reportType
            this.form.templateCode = template.id + ''
          }
          if (this.form.id != null) {
            updateCustomerLabel(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addCustomerLabel(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 delcustomerLabel(Ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'pro/scheduleSetupRule/export',
        {
          ...this.queryParams,
        },
        `scheduleSetupRule_${new Date().getTime()}.xlsx`
      )
    },
  },
}
</script>
