import { required } from '@/components/template/rules_verify.js'
import { getBrandList } from '@/api/miniapp'
import { getClassifyList } from '@/api/goods'
import { goodsMaterialList } from '@/api/commercialMaterial.js'
import { goodsPurchaseItemImportCode, goodsPurchaseDetail } from '@/api/goodsPurchasedStored.js'

export default {
  data() {
    return {
      brandList: [],
      ClassifyList: [],
      goodsMaterialList: []
    }
  },
  computed: {
    storage_goods() {
      return [
        {
          columnAttributes: {
            label: '品牌',
            prop: 'brandId',
            propName: 'brandName',
            width: 160
          },
          render: (h, { row, column, index }) => {
            return this.isEditIndex == index ? (
              <div class="redbordererr">
                <el-form-item
                  label=""
                  lebel-width="0px"
                  prop={`items.${index}.${column.columnAttributes.prop}`}
                  rules={required}
                >
                  <el-select
                    value={row[column.columnAttributes.prop]}
                    onInput={val => {
                      row[column.columnAttributes.prop] = val
                    }}
                    onChange={val => {
                      this.shanchujichu(row, 0)
                      if (val) {
                        row[column.columnAttributes.propName] = this.brandList.find(item => item.id == val).brandName
                      } else {
                        row[column.columnAttributes.propName] = ''
                      }
                    }}
                    placeholder="请选择"
                  >
                    {this.brandList.map((item, index_) => (
                      <el-option key={index_} label={item.brandName} value={item.id}></el-option>
                    ))}
                  </el-select>
                </el-form-item>
              </div>
            ) : (
              <div style="padding:0 6px">{row[column.columnAttributes.propName]}</div>
            )
          }
        },
        {
          columnAttributes: {
            label: '商品大类',
            prop: 'mainId',
            propName: 'mainName',
            width: 160
          },
          render: (h, { row, column, index }) => {
            return this.isEditIndex == index ? (
              <div class="redbordererr">
                <el-form-item
                  label=""
                  lebel-width="0px"
                  prop={`items.${index}.${column.columnAttributes.prop}`}
                  rules={required}
                >
                  <el-select
                    value={row[column.columnAttributes.prop]}
                    onInput={val => {
                      row[column.columnAttributes.prop] = val
                    }}
                    onChange={val => {
                      this.shanchujichu(row, 1)
                      if (val) {
                        row[column.columnAttributes.propName] = this.ClassifyList.find(
                          item => item.categoryId == val
                        ).name
                      } else {
                        row[column.columnAttributes.propName] = ''
                      }
                    }}
                    placeholder="请选择"
                  >
                    {this.ClassifyList.map((item, index_) => (
                      <el-option key={index_} label={item.name} value={item.categoryId}></el-option>
                    ))}
                  </el-select>
                </el-form-item>
              </div>
            ) : (
              <div style="padding:0 6px">{row[column.columnAttributes.propName]}</div>
            )
          }
        },
        {
          columnAttributes: {
            label: '商品小类',
            prop: 'smallId',
            propName: 'smallName',
            width: 160
          },
          render: (h, { row, column, index }) => {
            return this.isEditIndex == index ? (
              <div class="redbordererr">
                <el-form-item
                  label=""
                  lebel-width="0px"
                  prop={`items.${index}.${column.columnAttributes.prop}`}
                  rules={required}
                >
                  <el-select
                    value={row[column.columnAttributes.prop]}
                    onInput={val => {
                      row[column.columnAttributes.prop] = val
                    }}
                    onChange={val => {
                      this.shanchujichu(row, 2)
                      if (val) {
                        row[column.columnAttributes.propName] = (
                          this.ClassifyList.find(item => item.categoryId == row.mainId)?.children || []
                        ).find(item => item.categoryId == val).name
                      } else {
                        row[column.columnAttributes.propName] = ''
                      }
                    }}
                    placeholder="请选择"
                  >
                    {(this.ClassifyList.find(item => item.categoryId == row.mainId)?.children || []).map(
                      (item, index_) => (
                        <el-option key={index_} label={item.name} value={item.categoryId}></el-option>
                      )
                    )}
                  </el-select>
                </el-form-item>
              </div>
            ) : (
              <div style="padding:0 6px">{row[column.columnAttributes.propName]}</div>
            )
          }
        },
        {
          columnAttributes: {
            label: '商品名称',
            prop: 'goodsMaterialId',
            propName: 'goodsMaterialName',
            width: 160
          },
          render: (h, { row, column, index }) => {
            return this.isEditIndex == index ? (
              <div class="redbordererr">
                <el-form-item
                  label=""
                  lebel-width="0px"
                  prop={`items.${index}.${column.columnAttributes.prop}`}
                  rules={required}
                >
                  <el-select
                    value={row[column.columnAttributes.prop]}
                    onInput={val => {
                      row[column.columnAttributes.prop] = val
                    }}
                    onChange={val => {
                      this.shanchujichu(row, 3)
                      if (val) {
                        var data = this.goodsMaterialList
                          .filter(
                            item =>
                              item.brandId === row.brandId && item.mainId === row.mainId && item.smallId === row.smallId
                          )
                          .find(item => item.id == val)
                        row[column.columnAttributes.propName] = data?.goodsName
                        this.getGoodsDetl(data, res => {
                          if (this.formDialogType == 0) {
                            row['specsName'] = res?.specsName
                            row['unit'] = res?.unit
                            row['stockQty'] = res?.stockQty
                            row['factoryNo'] = res?.factoryNo
                            row['insideQty'] =
                              res.items
                                .filter(item => item.type === 'INSIDE')
                                .map(item => item.qty)
                                .reduce((accumulator, currentValue) => accumulator + currentValue, 0) * Number(row?.qty)
                            row['outQty'] =
                              res.items
                                .filter(item => item.type === 'OUT')
                                .map(item => item.qty)
                                .reduce((accumulator, currentValue) => accumulator + currentValue, 0) * Number(row?.qty)
                            row['partsQty'] =
                              res.items
                                .filter(item => item.type === 'PARTS')
                                .map(item => item.qty)
                                .reduce((accumulator, currentValue) => accumulator + currentValue, 0) * Number(row?.qty)
                          }
                        })
                      } else {
                        row[column.columnAttributes.propName] = ''
                        row['specsName'] = ''
                        row['unit'] = ''
                        row['insideQty'] = ''
                        row['outQty'] = ''
                        row['partsQty'] = ''
                        row['stockQty'] = ''
                        row['factoryNo'] = ''
                      }
                    }}
                    filterable={true}
                    placeholder="请选择"
                  >
                    {this.goodsMaterialList
                      .filter(
                        item =>
                          item.brandId === row.brandId && item.mainId === row.mainId && item.smallId === row.smallId
                      )
                      .map((item, index_) => (
                        <el-option key={index_} label={item.goodsName} value={item.id}></el-option>
                      ))}
                  </el-select>
                </el-form-item>
              </div>
            ) : (
              <div style="padding:0 6px">{row[column.columnAttributes.propName]}</div>
            )
          }
        },
        {
          columnAttributes: {
            label: '厂物料编码',
            prop: 'factoryNo',
            width: 120
          }
        },
        {
          columnAttributes: {
            label: '规格型号',
            prop: 'specsName',
            width: 120
          }
        },
        {
          columnAttributes: {
            label: '单位',
            prop: 'unit'
          },
          render: (h, { row, column, index }) => {
            return <div style="padding:0 6px">{{ C: '整套', I: '单个' }[row[column.columnAttributes.prop]] || ''}</div>
          }
        },
        {
          columnAttributes: {
            label: '采购数量',
            prop: 'qty',
            width: 160
          },
          render: (h, { row, column, index }) => {
            return this.isEditIndex == index ? (
              <div class="redbordererr">
                <el-form-item
                  label=""
                  lebel-width="0px"
                  prop={`items.${index}.${column.columnAttributes.prop}`}
                  rules={required}
                >
                  <el-input
                    value={row[column.columnAttributes.prop]}
                    onInput={val => {
                      row[column.columnAttributes.prop] = val <= 0 ? 0 : Number(val)
                      this.getGoodsDetl(
                        this.goodsMaterialList
                          .filter(
                            item =>
                              item.brandId === row.brandId && item.mainId === row.mainId && item.smallId === row.smallId
                          )
                          .find(item => item.id == row.goodsMaterialId),
                        res => {
                          if (this.formDialogType == 0) {
                            row['insideQty'] =
                              res.items
                                .filter(item => item.type === 'INSIDE')
                                .map(item => item.qty)
                                .reduce((accumulator, currentValue) => accumulator + currentValue, 0) *
                              row[column.columnAttributes.prop]
                            row['outQty'] =
                              res.items
                                .filter(item => item.type === 'OUT')
                                .map(item => item.qty)
                                .reduce((accumulator, currentValue) => accumulator + currentValue, 0) *
                              row[column.columnAttributes.prop]
                            row['partsQty'] =
                              res.items
                                .filter(item => item.type === 'PARTS')
                                .map(item => item.qty)
                                .reduce((accumulator, currentValue) => accumulator + currentValue, 0) *
                              row[column.columnAttributes.prop]
                          }
                        }
                      )
                    }}
                    type="number"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </div>
            ) : (
              <div style="padding:0 6px">{row[column.columnAttributes.prop]}</div>
            )
          }
        },
        {
          columnAttributes: {
            label: '内机数量',
            prop: 'insideQty'
          }
        },
        {
          columnAttributes: {
            label: '外机数量',
            prop: 'outQty'
          }
        },
        {
          columnAttributes: {
            label: '配件数量',
            prop: 'partsQty'
          }
        },
        {
          columnAttributes: {
            label: '导入内机条码数量',
            prop: 'insideCodeQty',
            width: 120
          }
        },
        {
          columnAttributes: {
            label: '导入外机条码数量',
            prop: 'outCodeQty',
            width: 120
          }
        },
        {
          columnAttributes: {
            label: '导入配件条码数量',
            prop: 'partsCodeQty',
            width: 120
          }
        },
        {
          columnAttributes: {
            label: '采购价格',
            prop: 'price',
            width: 160
          },
          render: (h, { row, column, index }) => {
            return this.isEditIndex == index ? (
              <div class="redbordererr">
                <el-form-item
                  label=""
                  lebel-width="0px"
                  prop={`items.${index}.${column.columnAttributes.prop}`}
                  rules={required}
                >
                  <el-input
                    value={row[column.columnAttributes.prop]}
                    onInput={val => {
                      row[column.columnAttributes.prop] = val
                    }}
                    type="number"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </div>
            ) : (
              <div style="padding:0 6px">{row[column.columnAttributes.prop]}</div>
            )
          }
        },
        {
          columnAttributes: {
            label: '采购金额',
            prop: 'amount',
            width: 160
          },
          render: (h, { row, column, index }) => {
            return <div style="padding:0 6px">{Number(row['qty']) * Number(row['price'])}</div>
          }
        },
        {
          columnAttributes: {
            label: '库存数量',
            prop: 'stockQty'
          }
        },
        ...(() => {

          if (this.formDialogType < 2 && !~['SAVE', 'WAIT', 'OK', 'FAIL'].indexOf(this.formData.status)) {
            return [
              {
                columnAttributes: {
                  label: '操作',
                  fixed: 'right',
                  width: 140
                },
                render: (h, { row, column, index }) => {
                  return (
                    <div style="padding:0 6px" class="operation-btns">
                      {[
                        this.isEditIndex == index ? (
                          <el-button
                            type="text"
                            onClick={() => {
                              this.$refs.formRef.validateField(
                                this.getVfyKey(this.isEditIndex),
                                (valid, invalidFields, errLabels) => {
                                  if (valid && this.eidtItems()) {
                                    this.isEditIndex = -1
                                  }
                                }
                              )
                            }}
                          >
                            保存
                          </el-button>
                        ) : null,
                        this.isEditIndex == -1 ? (
                          <el-button
                            type="text"
                            onClick={() => {
                              this.isEditIndex = index
                            }}
                          >
                            编辑
                          </el-button>
                        ) : null,
                        <el-button
                          type="text"
                          onClick={() => {
                            this.delGoodsInfo(row, index)
                          }}
                        >
                          删除
                        </el-button>
                      ]}
                    </div>
                  )
                }
              }
            ]
          } else if (this.formDialogType < 2 && !!~['SAVE'].indexOf(this.formData.status) && this.joinCode) {
            return [
              {
                columnAttributes: {
                  label: '操作',
                  fixed: 'right',
                  width: 140
                },
                render: (h, { row, column, index }) => {
                  return (
                    <div style="padding:0 6px" class="operation-btns">
                      {this.importButton(goodsPurchaseItemImportCode, '导入条码', { purchaseItemId: row.id }, () => { }, () => {
                        if (this.formData.id) {
                          // 更新表单信息
                          goodsPurchaseDetail({ id: this.formData.id }).then(res => {
                            Object.assign(this.formData, res.data, {
                              fileUrl: res.data.fileUrl ? [{ url: res.data.fileUrl }] : [],
                              items: res.data.items.map(item => ({ ...item, details: {} }))
                            })
                          })
                        }
                      })}
                    </div>
                  )
                }
              }
            ]
          }
          return []
        })()
      ]
    }
  },
  methods: {
    getBaseList() {
      getBrandList({
        status: true
      }).then(res => {
        this.brandList = res.data
      })
      getClassifyList({
        type: 2,
        status: true
      }).then(res => {
        this.ClassifyList = res.data
      })
      goodsMaterialList({
        pageNum: 1,
        pageSize: -1,
        params: []
      }).then(res => {
        this.goodsMaterialList = res.data.records
          .filter(item => item.isVirtyual !== 'YES' && item.state == 'ON')
          .map(item => ({ ...item, details: {} }))
      })
    },
    shanchujichu(row, num) {
      if (num <= 0) {
      }
      if (num <= 1) {
        row.smallId = ''
        row.smallName = ''
      }
      if (num <= 2) {
        row.goodsMaterialId = ''
        row.goodsMaterialName = ''
        row.specsName = ''
        row.unit = ''
        row.insideQty = ''
        row.outQty = ''
        row.partsQty = ''
        row.stockQty = ''
        row.factoryNo = ''
      }
    },
    getVfyKey(index, bool = true) {
      return [
        ...(() => {
          if (bool) {
            return [`items`]
          }
          return []
        })(),
        ...(() => {
          if (index > -1) {
            return [
              `items.${index}.brandId`,
              `items.${index}.mainId`,
              `items.${index}.smallId`,
              `items.${index}.goodsMaterialId`,
              `items.${index}.qty`,
              `items.${index}.price`
            ]
          }
          return []
        })()
      ]
    },
    eidtItems() {
      try {
        this.formData.items.map((item, index) => {
          this.formData.items.map((item2, index2) => {
            if (
              index !== index2 &&
              `${item.brandId}_${item.mainId}_${item.smallId}_${item.goodsMaterialId}` ==
              `${item2.brandId}_${item2.mainId}_${item2.smallId}_${item2.goodsMaterialId}`
            ) {
              throw new Error('')
            }
          })
        })
      } catch (error) {
        this.$message.warning('重复')
        return false
      }
      return true
    },
    // 添加商品信息
    addGoodsInfo() {
      if (this.isEditIndex > -1) {
        this.$refs.formRef.validateField(this.getVfyKey(this.isEditIndex), (valid, invalidFields, errLabels) => {
          if (valid && this.eidtItems()) {
            this.formData.items.unshift({
              brandId: '',
              brandName: '',
              mainId: '',
              mainName: '',
              smallId: '',
              smallName: '',
              goodsMaterialId: '',
              goodsMaterialName: '',
              specsName: '',
              unit: '',
              qty: '',
              insideQty: '',
              outQty: '',
              partsQty: '',
              insideCodeQty: '',
              outCodeQty: '',
              partsCodeQty: '',
              price: '',
              amount: '',
              stockQty: '',
              factoryNo: "",
            })
            this.isEditIndex = 0
          }
        })
      } else if (this.eidtItems()) {
        this.formData.items.unshift({
          brandId: '',
          brandName: '',
          mainId: '',
          mainName: '',
          smallId: '',
          smallName: '',
          goodsMaterialId: '',
          goodsMaterialName: '',
          specsName: '',
          unit: '',
          qty: '',
          insideQty: '',
          outQty: '',
          partsQty: '',
          insideCodeQty: '',
          outCodeQty: '',
          partsCodeQty: '',
          price: '',
          amount: '',
          stockQty: '',
          factoryNo: ''
        })
        this.isEditIndex = 0
      }
    },
    delGoodsInfo(row, index) {
      if (index > this.isEditIndex) {
        this.formData?.items?.splice(index, 1)
      } else if (index == this.isEditIndex) {
        this.formData?.items?.splice(index, 1)
        this.isEditIndex = -1
      }
    }
  }
}
