<template>
  <a-modal
    centered
    class="productInfoModal-modal"
    :footer="null"
    :maskClosable="false"
    title="新增产品信息"
    v-model="isShow"
    @cancel="isShow=false"
    width="60%">
    <a-spin :spinning="spinning" tip="Loading...">
      <div>
        <a-descriptions v-if="baseData">
          <a-descriptions-item label="记账类型">
            {{ baseData.accountTypeDictValue }}
          </a-descriptions-item>
          <a-descriptions-item label="记账名称">
            {{ baseData.accountName }}
          </a-descriptions-item>
          <a-descriptions-item label="记账费用">
            ￥{{ baseData.expense }}
          </a-descriptions-item>
        </a-descriptions>
        <div class="productInfoModal-con">
          <!-- 列表 -->
          <a-table
            class="sTable fixPagination"
            ref="table"
            :scroll="{ y: 300 }"
            size="small"
            :rowKey="(record,index) => 'productTable-'+index"
            :columns="columns"
            :data-source="dataList"
            :pagination="false"
            bordered>
            <div slot="customTitle"><span style="color: red;">*</span>费用金额</div>
            <template slot="action" slot-scope="text,record,index">
              <a-button
                :id="'del-'+index"
                size="small"
                type="link"
                class="button-error"
                @click="handleDelRow(record,index)"
              >删除</a-button>
            </template>
            <!-- 产品品牌 -->
            <template slot="productBrand" slot-scope="text,record,index">
              <span v-if="!!record.productCode">{{ record.productBrandName }}</span>
              <ProductBrand style="width: 100%;" v-else :id="'productBrand-'+index" @change="productBrandChange" v-model="record.productBrandSn"></ProductBrand>
            </template>
            <!-- 产品分类 -->
            <template slot="productType" slot-scope="text,record,index">
              <span v-if="!!record.productCode">
                {{ record.productTypeName1 }}>{{ record.productTypeName2 }}>{{ record.productTypeName3 }}
              </span>
              <ProductTypeAll
                v-else
                style="width: 100%;"
                :ref="'productType-'+record.no"
                :id="'productType-'+index"
                v-model="record.productType"
                @change="changeProductType"></ProductTypeAll>
            </template>
            <!-- 产品编码 -->
            <template slot="productCode" slot-scope="text,record,index">
              <productCodeList :ref="'productCode-'+record.no" :key="'productCode-'+index" :id="'productCode-'+index" @change="productCodeChange" />
            </template>
            <!-- 费用金额 -->
            <template slot="expense" slot-scope="text,record,index">
              <a-input-number
                :id="'expense-'+index"
                style="width: 100%;"
                v-model="record.expense"
                :precision="2"
                :min="0"
                :max="99999999"
                placeholder="请输入"
              />
            </template>
            <template slot="footer">
              <a-button
                id="productInfoModal-add-0"
                type="link"
                class="button-info"
                v-if="dataList.length==0"
                block
                @click="handleAddRow()"
              >+ 新增产品信息</a-button>
            </template>
          </a-table>
        </div>
        <div class="btn-cont">
          <a-button id="productInfoModal-back" @click="isShow = false" style="margin-right: 15px;">取消</a-button>
          <a-button type="primary" id="productInfoModal-save" @click="handleSave">确定</a-button>
        </div>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import { VSelect, STable } from '@/components'
import ProductTypeAll from '@/views/common/productTypeAll.js'
import ProductBrand from '@/views/common/productBrand.js'
import productCodeList from '@/views/common/productCodeList.vue'
import { expenseAcctDetailSaveProducts, expenseAcctDetailFindProductsBySn } from '@/api/expenseManagement.js'
export default {
  components: { VSelect, STable, ProductTypeAll, ProductBrand, productCodeList },
  name: 'ProductInfoModal',
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    expenseAccountSn: { // 报销单sn
      type: String,
      default: ''
    },
    expenseAccountNo: { // 报销单号
      type: String,
      default: ''
    },
    expenseAccountDetailSn: { // 费用单sn
      type: String,
      default: ''
    }
  },
  data () {
    return {
      spinning: false,
      isShow: this.openModal, //  是否打开弹框
      dataList: [],
      baseData: null, // 详细信息
      columns: [
        { title: '产品品牌', scopedSlots: { customRender: 'productBrand' }, align: 'center', width: '20%' },
        { title: '产品分类', scopedSlots: { customRender: 'productType' }, align: 'center', width: '40%' },
        { title: '产品编码', scopedSlots: { customRender: 'productCode' }, align: 'center', width: '20%' },
        // { slots: { title: 'customTitle' }, scopedSlots: { customRender: 'expense' }, align: 'center', width: '20%' }
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
    }
  },
  methods: {
    // 产品编码
    productCodeChange (val, id) {
      const index = id.split('-')[1]
      const row = this.dataList[index]
      row.productSn = val.key || undefined
      row.productCode = val.row && val.row.code ? val.row.code : undefined
      row.productName = val.row && val.row.name ? val.row.name : undefined
      row.productBrandSn = val.row && val.row.productBrandSn ? val.row.productBrandSn : undefined
      row.productBrandName = val.row && val.row.productBrandName ? val.row.productBrandName : undefined
      row.productTypeSn1 = val.row && val.row.productTypeSn1 ? val.row.productTypeSn1 : undefined
      row.productTypeSn2 = val.row && val.row.productTypeSn2 ? val.row.productTypeSn2 : undefined
      row.productTypeSn3 = val.row && val.row.productTypeSn3 ? val.row.productTypeSn3 : undefined
      row.productTypeName1 = val.row && val.row.productTypeName1 ? val.row.productTypeName1 : undefined
      row.productTypeName2 = val.row && val.row.productTypeName2 ? val.row.productTypeName2 : undefined
      row.productTypeName3 = val.row && val.row.productTypeName3 ? val.row.productTypeName3 : undefined
      // 设置默认值
      const defval = row.productTypeSn1 || row.productTypeSn2 || row.productTypeSn3 ? [row.productTypeSn1, row.productTypeSn2, row.productTypeSn3] : []
      row.productType = defval
      console.log(row)
      this.$nextTick(() => {
        this.$refs['productType-' + row.no].setDefValue(defval, row)
      })
    },
    // 产品品牌
    productBrandChange (val, id, option) {
      const index = id.split('-')[1]
      const row = this.dataList[index]
      row.productBrandName = option && option.brandName ? option.brandName : undefined
    },
    //  产品分类  change
    changeProductType (val, id, options) {
      console.log(val, id, options)
      const index = id.split('-')[1]
      const row = this.dataList[index]
      if (val.length > 1) {
        row.productTypeSn1 = val[0] ? val[0] : ''
        row.productTypeSn2 = val[1] ? val[1] : ''
        row.productTypeSn3 = val[2] ? val[2] : ''
        if (options) {
          row.productTypeName1 = options[0] ? options[0].productTypeName : ''
          row.productTypeName2 = options[1] ? options[1].productTypeName : ''
          row.productTypeName3 = options[2] ? options[2].productTypeName : ''
        }
      } else if (val.length == 1) {
        this.$set(row, 'productType', [])
        this.$nextTick(() => {
          this.$refs['productType-' + row.no].setDefValue([], row)
        })
        this.$message.info('不能只选择一级分类')
      } else {
        row.productTypeSn1 = undefined
        row.productTypeSn2 = undefined
        row.productTypeSn3 = undefined
        row.productTypeName1 = undefined
        row.productTypeName2 = undefined
        row.productTypeName3 = undefined
      }
    },
    // 添加
    handleAddRow () {
      this.dataList.push({
        'no': new Date().getTime(),
        'expense': 0,
        'expenseAccountDetailSn': this.expenseAccountDetailSn,
        'expenseAccountSn': this.expenseAccountSn,
        'productBrandName': '',
        'productBrandSn': undefined,
        'productCode': undefined,
        'productName': '',
        'productSn': '',
        'productType': [],
        'productTypeName1': '',
        'productTypeName2': '',
        'productTypeName3': '',
        'productTypeSn1': '',
        'productTypeSn2': '',
        'productTypeSn3': ''
      })
    },
    // 删除
    handleDelRow (record, index) {
      console.log(record, this.$refs)
      this.dataList.splice(index, 1)
      this.dataList.map(item => {
        this.$nextTick(() => {
          const refDom = this.$refs['productCode-' + item.no]
          if (refDom) {
            refDom.dealerName = ''
            refDom.setDufaultVal(item.productCode || '')
          }
        })
      })
    },
    // 确定
    handleSave () {
      // 校验数据
      const retList = JSON.parse(JSON.stringify(this.dataList))
      console.log(retList)
      let hasError = 0
      retList.map(item => {
        if (!item.expense) {
          hasError = 1
        }
        if (!(item.productTypeSn1 || item.productCode || item.productBrandSn)) {
          hasError = 2
        }
        delete item.productType
        delete item.no
      })
      if (hasError == 2) {
        this.$message.info('产品品牌、产品分类、产品编码，三个至少填一个')
        return
      }
      this.spinning = true
      expenseAcctDetailSaveProducts({
        'expenseAccountDetailSn': this.expenseAccountDetailSn,
        'detailProductsList': retList
      }).then(res => {
        this.spinning = false
        if (res.status == 200) {
          this.$message.success(res.message)
          this.$emit('ok', res.data)
          this.isShow = false
        }
      })
    },
    // 设置基础数据
    setBaseData (data) {
      this.baseData = data
    },
    // 查询详情
    getDetail () {
      this.spinning = true
      expenseAcctDetailFindProductsBySn({ detailSn: this.expenseAccountDetailSn }).then(res => {
        if (res.data && res.data.length) {
          this.dataList = res.data
          console.log(res.data, '------')
          this.dataList.map(item => {
            item.no = item.id
            this.$nextTick(() => {
              if (item.productCode) {
                this.$refs['productCode-' + item.no].setDufaultVal(item.productCode)
              } else {
                if (item.productTypeSn1 || item.productTypeSn2 || item.productTypeSn3) {
                  item.productType = [item.productTypeSn1, item.productTypeSn2, item.productTypeSn3]
                  this.$refs['productType-' + item.no].setDefValue(
                    [item.productTypeSn1, item.productTypeSn2, item.productTypeSn3],
                    [{ productTypeSn: item.productTypeSn1, productTypeName: item.productTypeName1 },
                      { productTypeSn: item.productTypeSn2, productTypeName: item.productTypeName2 },
                      { productTypeSn: item.productTypeSn3, productTypeName: item.productTypeName3 }]
                  )
                }
              }
            })
          })
        } else {
          this.dataList = [{
            'no': new Date().getTime(),
            'expense': 0,
            'expenseAccountDetailSn': this.expenseAccountDetailSn,
            'expenseAccountSn': this.expenseAccountSn,
            'productBrandName': '',
            'productBrandSn': undefined,
            'productCode': '',
            'productName': '',
            'productSn': '',
            'productType': [],
            'productTypeName1': '',
            'productTypeName2': '',
            'productTypeName3': '',
            'productTypeSn1': '',
            'productTypeSn2': '',
            'productTypeSn3': ''
          }]
        }
        this.spinning = false
      })
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.dataList = []
        this.baseData = null
        this.$emit('close')
      } else {
        this.getDetail()
      }
    }
  }
}
</script>

<style lang="less">
  .productInfoModal-modal{
    .ant-modal-body {
      padding: 30px 40px 24px;
    }
    .productInfoModal-con{
      text-align: center;
      h3{
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 25px;
      }
    }
    .btn-cont {
      text-align: center;
      margin: 35px 0 10px;
    }
  }
</style>
