import { getClassifyList } from '@/api/goods'
import { getDataDictionary } from '@/api/dataDictionary.js'
import { required, mobileRequired, mobile, httpUrl, email } from '@/components/template/rules_verify.js'
import {
  orderBaseProductList,
  orderBaseProductAdd,
  orderBaseProductUpdate,
  orderBaseProductDelete
} from '@/api/workOrderPool.js'
export default {
  data() {
    return {
      isEditIndex: -1,
      orderBrands: [],
      classifyList: [],
      classifyListLv2: []
    }
  },
  computed: {
    productColumns() {
      return [
        {
          columnAttributes: {
            label: '产品品牌',
            prop: 'brandId'
          },
          render: (h, { row, column, index }) => {
            return this.isEditIndex == index ? (
              <div class="redbordererr">
                <el-form-item
                  label=""
                  label-width="0px"
                  prop={`orderProducts.${index}.${column.columnAttributes.prop}`}
                  rules={this.orderInfo.isCj ? [] : []}
                >
                  <el-select
                    disabled={!this.formOptions.orderProducts.isEdit}
                    value={row[column.columnAttributes.prop]}
                    onInput={val => {
                      row[column.columnAttributes.prop] = val
                    }}
                    onChange={val => {
                      if (val) {
                        var data = this.orderBrands.find(item => item.value == val)
                        row.brandName = data.label
                      } else {
                        row.brandName = ''
                      }
                    }}
                    placeholder="请选择"
                  >
                    {this.orderBrands.map((item, index_) => (
                      <el-option key={index_} label={item.label} value={item.value}></el-option>
                    ))}
                  </el-select>
                </el-form-item>
              </div>
            ) : (
              <div style="padding-left:10px">{row.brandName}</div>
            )
          }
        },
        {
          columnAttributes: {
            label: '产品大类',
            prop: 'mainId'
          },
          render: (h, { row, column, index }) => {
            return this.isEditIndex == index ? (
              <div class="redbordererr">
                <el-form-item
                  label=""
                  label-width="0px"
                  prop={`orderProducts.${index}.${column.columnAttributes.prop}`}
                  rules={this.orderInfo.isCj ? [] : required}
                >
                  <el-select
                    disabled={!this.formOptions.orderProducts.isEdit}
                    value={row[column.columnAttributes.prop]}
                    onInput={val => {
                      row[column.columnAttributes.prop] = val
                    }}
                    onChange={val => {
                      row.smallId = ''
                      row.smallName = ''
                      if (val) {
                        var data = this.classifyList.find(item => item.categoryId == val)
                        row.mainName = data.name
                        row.imgUrl = data.imgUrl
                      } else {
                        row.mainName = ''
                        row.imgUrl = ''
                      }
                      this.getWebsitFun(true)
                    }}
                    placeholder="请选择"
                  >
                    {this.classifyList
                      .filter(val_ => {
                        var v_ =
                          this.orderInfo?.orderProducts?.length > 1
                            ? this.orderInfo?.orderProducts?.find(item => item[column.columnAttributes.prop])?.[
                                column.columnAttributes.prop
                              ]
                            : false
                        return v_ ? val_.categoryId === v_ : true
                      })
                      .map((item, index_) => (
                        <el-option key={index_} label={item.name} value={item.categoryId}></el-option>
                      ))}
                  </el-select>
                </el-form-item>
              </div>
            ) : (
              <div style="padding-left:10px">{row.mainName}</div>
            )
          }
        },
        {
          columnAttributes: {
            label: '产品小类',
            prop: 'smallId'
          },
          render: (h, { row, column, index }) => {
            return this.isEditIndex == index ? (
              <div class="redbordererr">
                <el-form-item
                  label=""
                  label-width="0px"
                  prop={`orderProducts.${index}.${column.columnAttributes.prop}`}
                  rules={this.orderInfo.isCj ? [] : []}
                >
                  <el-select
                    disabled={!this.formOptions.orderProducts.isEdit}
                    value={row[column.columnAttributes.prop]}
                    onInput={val => {
                      row[column.columnAttributes.prop] = val
                    }}
                    onChange={val => {
                      if (val) {
                        var data = this.classifyListLv2.find(item => item.categoryId == val)
                        row.smallName = data.name
                      } else {
                        row.smallName = ''
                      }
                    }}
                    placeholder="请选择"
                  >
                    {this.classifyListLv2
                      .filter(item => item.parentId === row.mainId)
                      .map((item, index_) => (
                        <el-option key={index_} label={item.name} value={item.categoryId}></el-option>
                      ))}
                  </el-select>
                </el-form-item>
              </div>
            ) : (
              <div style="padding-left:10px">{row.smallName}</div>
            )
          }
        },
        {
          columnAttributes: {
            label: '产品机型',
            prop: 'productName'
          },
          render: (h, { row, column, index }) => {
            return this.isEditIndex == index ? (
              <div class="redbordererr">
                <el-form-item
                  label=""
                  label-width="0px"
                  prop={`orderProducts.${index}.${column.columnAttributes.prop}`}
                >
                  <el-input
                    disabled={!this.formOptions.orderProducts.isEdit}
                    value={row[column.columnAttributes.prop]}
                    onInput={val => {
                      row[column.columnAttributes.prop] = val
                    }}
                    placeholder="请输入内容"
                  ></el-input>
                </el-form-item>
              </div>
            ) : (
              <div style="padding-left:10px">{row[column.columnAttributes.prop]}</div>
            )
          }
        },
        {
          columnAttributes: {
            label: '内机条码',
            prop: 'insideCode'
          },
          render: (h, { row, column, index }) => {
            return this.isEditIndex == index ? (
              <div class="redbordererr">
                <el-form-item label="" label-width="0px">
                  <el-input
                    disabled={!this.formOptions.orderProducts.isEdit}
                    value={row[column.columnAttributes.prop]}
                    onInput={val => {
                      row[column.columnAttributes.prop] = val
                    }}
                    placeholder="请输入内容"
                  ></el-input>
                </el-form-item>
              </div>
            ) : (
              <div style="padding-left:10px">{row[column.columnAttributes.prop]}</div>
            )
          }
        },
        {
          columnAttributes: {
            label: '数量',
            prop: 'num'
          },
          render: (h, { row, column, index }) => {
            return this.isEditIndex == index ? (
              <div class="redbordererr">
                <el-form-item
                  label=""
                  label-width="0px"
                  prop={`orderProducts.${index}.${column.columnAttributes.prop}`}
                  rules={this.orderInfo.isCj ? [] : required}
                >
                  <el-input
                    disabled={!this.formOptions.orderProducts.isEdit}
                    value={row[column.columnAttributes.prop]}
                    onInput={val => {
                      row[column.columnAttributes.prop] = val
                    }}
                    placeholder="请输入内容"
                  ></el-input>
                </el-form-item>
              </div>
            ) : (
              <div style="padding-left:10px">{row[column.columnAttributes.prop]}</div>
            )
          }
        },
        {
          columnAttributes: {
            label: '备注',
            prop: 'remark'
          },
          render: (h, { row, column, index }) => {
            return this.isEditIndex == index ? (
              <div class="redbordererr">
                <el-form-item label="" label-width="0px">
                  <el-input
                    disabled={!this.formOptions.orderProducts.isEdit}
                    value={row[column.columnAttributes.prop]}
                    onInput={val => {
                      row[column.columnAttributes.prop] = val
                    }}
                    placeholder="请输入内容"
                  ></el-input>
                </el-form-item>
              </div>
            ) : (
              <div style="padding-left:10px">{row[column.columnAttributes.prop]}</div>
            )
          }
        },
        ...(() => {
          if (this.formOptions.orderProducts.isEdit) {
            return [
              {
                columnAttributes: {
                  label: '操作'
                },
                render: (h, { row, column, index }) => {
                  return (
                    <div style="padding-left:10px">
                      <el-button
                        type="text"
                        onClick={() => {
                          this.delProduct(row, index)
                        }}
                      >
                        删除
                      </el-button>
                      {this.isEditIndex == index && (
                        <el-button
                          type="text"
                          onClick={() => {
                            this.eidtProduct(row, index)
                          }}
                        >
                          确定
                        </el-button>
                      )}
                      {this.isEditIndex == -1 && (
                        <el-button
                          type="text"
                          onClick={() => {
                            this.isEditIndex = index
                          }}
                        >
                          编辑
                        </el-button>
                      )}
                    </div>
                  )
                }
              }
            ]
          }
          return []
        })()
      ]
    },
    product() {
      return [
        {
          isShow: this.formOptions.orderProducts.isShow,
          name: 'slot-component',
          md: 24,
          formItemAttributes: {
            label: '',
            'label-width': '0px',
            prop: 'orderProducts',
            errLabel: '产品信息',
            rules: this.formOptions.orderProducts.isRules
          },
          render: (h, { props }) => {
            return (
              <div>
                {this.formOptions.orderProducts.isEdit ? (
                  <div>
                    <el-button
                      size="mini"
                      type="primary"
                      onClick={() => {
                        this.appointVerify(this.getVfyKey(this.isEditIndex, false), v => {
                          if (v) {
                            try {
                              this.orderInfo.orderProducts.map((item, index_) => {
                                var row = this.orderInfo.orderProducts[index_ + 1]
                                if (row) {
                                  if (
                                    `${row.brandId}_${row.mainId}_${row.smallId}_${row.productName}` ==
                                    `${item.brandId}_${item.mainId}_${item.smallId}_${item.productName}`
                                  ) {
                                    throw new Error('')
                                  }
                                }
                              })
                            } catch (error) {
                              this.$message.warning('产品机型重复')
                              return
                            }
                            this.isEditIndex = 0
                            this.orderInfo.orderProducts.unshift({
                              brandId: '',
                              brandName: '',
                              createBy: '',
                              createTime: '',
                              mainId: '',
                              mainName: '',
                              num: '',
                              insideCode: '',
                              orderBaseId: this.id || '',
                              productId: '',
                              productName: '',
                              remark: '',
                              smallId: '',
                              smallName: '',
                              imgUrl: ''
                            })
                          }
                        })
                      }}
                    >
                      新增
                    </el-button>
                  </div>
                ) : null}
                <zj-table columns={this.productColumns} table-data={this.orderInfo.orderProducts} />
              </div>
            )
          }
        }
      ]
    }
  },
  created() {
    // 获取品牌
    getDataDictionary({
      pageNum: 1,
      pageSize: -1,
      params: [
        { param: 'a.status', compare: '=', value: 'ON' },
        { param: 'a.dict_type', compare: '=', value: 'BRAND' }
      ]
    }).then(res => {
      this.orderBrands = res.data.records.map(item => ({
        value: item.dictCode,
        label: item.dictValue
      }))
    })
    // 获取产品大类小类
    getClassifyList({ type: 2, status: true }).then(res => {
      var classifyListLv2 = []
      this.classifyList = res.data.map(item => {
        var { children, ...data } = item
        classifyListLv2.push(...(children || []))
        return {
          ...data
        }
      })
      this.classifyListLv2 = classifyListLv2
    })
  },
  methods: {
    getVfyKey(index, bool = true) {
      return [
        ...(() => {
          if (bool) {
            return [`orderProducts`]
          }
          return []
        })(),
        ...(() => {
          if (index > -1) {
            return [
              // `orderProducts.${index}.brandId`,
              `orderProducts.${index}.mainId`,
              // `orderProducts.${index}.smallId`,
              `orderProducts.${index}.productName`,
              `orderProducts.${index}.num`,
              `orderProducts.${index}.remark`
            ]
          }
          return []
        })()
      ]
    },
    // 重新获取赋值
    getOrderBaseProduct() {
      if (this.id) {
        orderBaseProductList({
          orderBaseId: this.id
        }).then(res => {
          this.orderInfo.orderProducts = res.data || []
        })
      }
    },
    eidtProduct(row, index) {
      try {
        this.orderInfo.orderProducts.map((item, index_) => {
          if (
            `${row.brandId}_${row.mainId}_${row.smallId}_${row.productName}` ==
              `${item.brandId}_${item.mainId}_${item.smallId}_${item.productName}` &&
            index_ != index
          ) {
            throw new Error('')
          }
        })
      } catch (error) {
        this.$message.warning('产品机型重复')
        return
      }
      this.appointVerify(this.getVfyKey(this.isEditIndex), v => {
        if (v) {
          if (this.id) {
            ;[orderBaseProductAdd, orderBaseProductUpdate][row.id ? 1 : 0](row).then(res => {
              this.isEditIndex = -1
              this.getOrderBaseProduct()
              this.getOrderBaseLogList()
            })
          } else {
            this.isEditIndex = -1
          }
        }
      })
    },
    delProduct(row, index) {
      this.appointVerify(this.getVfyKey(this.isEditIndex), v => {
        if (v && this.id && row.id) {
          orderBaseProductDelete({
            orderProductId: row.id
          }).then(res => {
            this.getOrderBaseProduct()
            this.getOrderBaseLogList()
          })
        } else {
          this.orderInfo.orderProducts.splice(index, 1)
        }
      })
    }
  }
}
