<template>
  <zj-tab-page ref="tabPage" :defaultActives="[{ key: 'list', label: $route.meta.title + '-列表', essential: true }]">
    <template slot-scope="{ activeKey, data }">
      <div
        :style="{
          width: '100%',
          height: activeKey == 'list' ? '100%' : '0px',
          overflow: 'hidden'
        }"
      >
        <template-page
          ref="pageRef"
          :get-list="getList"
          :table-attributes="tableAttributes"
          :table-events="tableEvents"
          :options-evens-group="optionsEvensGroup"
          :moreParameters="moreParameters"
          :column-parsing="columnParsing"
          :exportList="exportList"
          :operation="operation()"
        >
        </template-page>
      </div>
      <div v-if="~['add', 'edit'].indexOf(activeKey)" style="box-sizing: border-box; padding: 16px">
        <zj-form-container ref="formRef" :form-data="formData" :form-attributes="{ size: 'mini' }">
          <zj-form-module title="" label-width="100px" :form-data="formData" :form-items="formItems">
            <div
              slot="internal-bottom"
              style="text-align: right; margin-bottom: 20px; box-sizing: border-box; padding-right: 10px"
            >
              <el-button size="mini" @click="data.removeTab()">取消</el-button>
              <el-button size="mini" type="primary" @click="queding(data.removeTab)">确定</el-button>
            </div>
          </zj-form-module>
        </zj-form-container>
      </div>
    </template>
  </zj-tab-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import operation_mixin from '@/components/template/operation_mixin.js'
import { required, mobileRequired, mobile, httpUrl, email } from '@/components/template/rules_verify.js'
import { getBrandList } from '@/api/miniapp'
import { getClassifyList } from '@/api/goods'
import {
  goodsMaterialList,
  goodsMaterialListExport,
  goodsMaterialAdd,
  goodsMaterialUpdate,
  goodsMaterialBatchUpdateStatus,
  goodsMaterialItemCount,
  goodsMaterialDetail
} from '@/api/commercialMaterial.js'
export default {
  components: { TemplatePage },
  mixins: [import_mixin, operation_mixin],
  data() {
    return {
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: false
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      // 勾选选中行
      recordSelected: [],
      formData: {
        companyWechatId: '',
        brandId: '',
        mainId: '',
        smallId: '',
        seriesName: '',
        goodsName: '',
        specsName: '',
        state: '',
        unit: '',
        isVirtyual: '',
        remark: '',
        factoryNo: '',
        items: []
      },
      isEditIndex: -1,
      brandList: [],
      ClassifyList: []
    }
  },
  computed: {
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth('add', {
              click: () => {
                this.$refs.tabPage.addTab({
                  activeKey: 'add',
                  key: 'add',
                  label: '新增',
                  triggerEvent: () => {
                    this.openForm()
                  }
                })
              }
            })
          ]
          // [
          // 	this.optionsEvensAuth("pilqy", {
          // 		click: () => {

          // 		}
          // 	})
          // ],
          // [
          // 	this.optionsEvensAuth("piljy", {
          // 		click: () => {

          // 		}
          // 	})
          // ]
        ]
      ]
    },
    // 更多参数
    moreParameters() {
      return []
    },
    formItems() {
      return [
        {
          name: 'el-select',
          md: 6,
          options: this.brandList,
          attributes: {
            disabled: false,
            placeholder: '请选择',
            clearable: true,
            filterable: true
          },
          formItemAttributes: {
            label: '选择品牌',
            prop: 'brandId',
            rules: [...required]
          },
          events: {
            change: val => {
              this.formData.brandName = this.brandList.find(item => item.value === val)?.label || ''
            }
          }
        },
        {
          name: 'el-select',
          md: 6,
          options: this.ClassifyList.map(item => ({ label: item.name, value: item.categoryId })),
          attributes: {
            disabled: false,
            placeholder: '请选择',
            clearable: true,
            filterable: true
          },
          formItemAttributes: {
            label: '选择大类',
            prop: 'mainId',
            rules: [...required]
          },
          events: {
            change: val => {
              this.formData.mainName =
                this.ClassifyList.map(item => ({ label: item.name, value: item.categoryId })).find(
                  item => item.value === val
                )?.label || ''
              this.formData.smallId = ''
            }
          }
        },
        {
          name: 'el-select',
          md: 6,
          options: (this.ClassifyList.find(item => item.categoryId === this.formData.mainId)?.children || [])?.map(
            item => ({ label: item.name, value: item.categoryId })
          ),
          attributes: {
            disabled: false,
            placeholder: '请选择',
            clearable: true,
            filterable: true
          },
          formItemAttributes: {
            label: '选择小类',
            prop: 'smallId',
            rules: [...required]
          },
          events: {
            change: val => {
              this.formData.smallName =
                (this.ClassifyList.find(item => item.categoryId === this.formData.mainId)?.children || [])
                  ?.map(item => ({ label: item.name, value: item.categoryId }))
                  .find(item => item.value === val)?.label || ''
            }
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: false,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '系列名称',
            prop: 'seriesName'
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: false,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '商品名称',
            prop: 'goodsName',
            rules: [...required]
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: false,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '规格型号',
            prop: 'specsName',
            rules: [...required]
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: false,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '厂物料编码',
            prop: 'factoryNo',
            rules: []
          }
        },
        {
          md: 6,
          name: 'el-radio',
          options: [
            { label: '有效', value: 'ON' },
            { label: '无效', value: 'OFF' }
          ],
          attributes: {},
          formItemAttributes: {
            label: '状态',
            prop: 'state',
            rules: [...required]
          }
        },
        {
          md: 6,
          name: 'el-radio',
          options: [
            { label: '整套', value: 'C' },
            { label: '单个', value: 'I' }
          ],
          attributes: {},
          formItemAttributes: {
            label: '单位',
            prop: 'unit',
            rules: [...required]
          }
        },
        {
          md: 6,
          name: 'el-radio',
          options: [
            { label: '是', value: 'YES' },
            { label: '否', value: 'NO' }
          ],
          attributes: {},
          formItemAttributes: {
            label: '虚拟商品',
            prop: 'isVirtyual',
            rules: [...required]
          }
        },
        ...(() => {
          if (this.formData.isVirtyual === 'NO') {
            this.isEditIndex = -1
            return [
              {
                name: 'slot-component',
                md: 24,
                formItemAttributes: {
                  label: '子物料',
                  prop: 'items',
                  rules: [...required]
                },
                render: (h, { props }) => {
                  return (
                    <div>
                      <el-button
                        size="mini"
                        type="primary"
                        onClick={() => {
                          if (this.isEditIndex > -1) {
                            this.$refs.formRef.validateField(
                              this.getVfyKey(this.isEditIndex),
                              (valid, invalidFields, errLabels) => {
                                if (valid && this.eidtItems()) {
                                  this.formData.items.unshift({
                                    name: '',
                                    qty: '',
                                    type: '',
                                    uniqueCode: '',
                                    unit: ''
                                  })
                                  this.isEditIndex = 0
                                }
                              }
                            )
                          } else if (this.eidtItems()) {
                            this.formData.items.unshift({
                              name: '',
                              qty: '',
                              type: '',
                              uniqueCode: '',
                              unit: ''
                            })
                            this.isEditIndex = 0
                          }
                        }}
                      >
                        新增
                      </el-button>
                      <zj-table columns={this.productColumns} table-data={this.formData.items} />
                    </div>
                  )
                }
              }
            ]
          }
          return []
        })(),
        {
          name: 'el-input',
          md: 24,
          attributes: {
            disabled: false,
            type: 'textarea',
            rows: 3,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '备注',
            prop: 'remark',
            rules: []
          }
        }
      ]
    },
    productColumns() {
      return [
        {
          columnAttributes: {
            label: '物料类型',
            prop: 'type'
          },
          render: (h, { row, column, index }) => {
            return (
              <div class="redbordererr">
                <el-form-item
                  label=""
                  label-width="0px"
                  prop={`items.${index}.${column.columnAttributes.prop}`}
                  rules={required}
                >
                  <el-select
                    disabled={this.isEditIndex !== index}
                    value={row[column.columnAttributes.prop]}
                    onInput={val => {
                      row[column.columnAttributes.prop] = val
                    }}
                    placeholder="请选择"
                  >
                    {[
                      { value: 'INSIDE', label: '内机' },
                      { value: 'OUT', label: '外机' },
                      { value: 'PARTS', label: '配件' }
                    ].map((item, index_) => (
                      <el-option key={index_} label={item.label} value={item.value}></el-option>
                    ))}
                  </el-select>
                </el-form-item>
              </div>
            )
          }
        },
        {
          columnAttributes: {
            label: '名称',
            prop: 'name'
          },
          render: (h, { row, column, index }) => {
            return (
              <div class="redbordererr">
                <el-form-item
                  label=""
                  label-width="0px"
                  prop={`items.${index}.${column.columnAttributes.prop}`}
                  rules={required}
                >
                  <el-input
                    disabled={this.isEditIndex !== index}
                    value={row[column.columnAttributes.prop]}
                    onInput={val => {
                      row[column.columnAttributes.prop] = val
                    }}
                    placeholder="请输入内容"
                  ></el-input>
                </el-form-item>
              </div>
            )
          }
        },
        {
          columnAttributes: {
            label: '是否一物一码',
            prop: 'uniqueCode'
          },
          render: (h, { row, column, index }) => {
            return (
              <div class="redbordererr">
                <el-form-item
                  label=""
                  label-width="0px"
                  prop={`items.${index}.${column.columnAttributes.prop}`}
                  rules={required}
                >
                  <el-select
                    disabled={this.isEditIndex !== index}
                    value={row[column.columnAttributes.prop]}
                    onInput={val => {
                      row[column.columnAttributes.prop] = val
                    }}
                    placeholder="请选择"
                  >
                    {[
                      { label: '是', value: 'YES' },
                      { label: '否', value: 'NO' }
                    ].map((item, index_) => (
                      <el-option key={index_} label={item.label} value={item.value}></el-option>
                    ))}
                  </el-select>
                </el-form-item>
              </div>
            )
          }
        },
        {
          columnAttributes: {
            label: '数量',
            prop: 'qty'
          },
          render: (h, { row, column, index }) => {
            return (
              <div class="redbordererr">
                <el-form-item
                  label=""
                  label-width="0px"
                  prop={`items.${index}.${column.columnAttributes.prop}`}
                  rules={required}
                >
                  <el-input
                    disabled={this.isEditIndex !== index}
                    value={row[column.columnAttributes.prop]}
                    onInput={val => {
                      row[column.columnAttributes.prop] = val
                    }}
                    placeholder="请输入内容"
                  ></el-input>
                </el-form-item>
              </div>
            )
          }
        },
        {
          columnAttributes: {
            label: '单位',
            prop: 'unit'
          },
          render: (h, { row, column, index }) => {
            return (
              <div class="redbordererr">
                <el-form-item
                  label=""
                  label-width="0px"
                  prop={`items.${index}.${column.columnAttributes.prop}`}
                  rules={required}
                >
                  <el-input
                    disabled={this.isEditIndex !== index}
                    value={row[column.columnAttributes.prop]}
                    onInput={val => {
                      row[column.columnAttributes.prop] = val
                    }}
                    placeholder="请输入内容"
                  ></el-input>
                </el-form-item>
              </div>
            )
          }
        },
        {
          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.$refs.formRef.validateField(
                        this.getVfyKey(this.isEditIndex),
                        (valid, invalidFields, errLabels) => {
                          if (valid && this.eidtItems()) {
                            this.isEditIndex = -1
                          }
                        }
                      )
                    }}
                  >
                    确定
                  </el-button>
                )}
                {this.isEditIndex == -1 && (
                  <el-button
                    type="text"
                    onClick={() => {
                      this.isEditIndex = index
                    }}
                  >
                    编辑
                  </el-button>
                )}
              </div>
            )
          }
        }
      ]
    }
  },
  methods: {
    // 列表请求函数
    getList: goodsMaterialList,
    // 列表导出函数
    exportList: goodsMaterialListExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    getVfyKey(index, bool = true) {
      return [
        ...(() => {
          if (bool) {
            return [`items`]
          }
          return []
        })(),
        ...(() => {
          if (index > -1) {
            return [
              `items.${index}.name`,
              `items.${index}.type`,
              `items.${index}.uniqueCode`,
              `items.${index}.qty`,
              `items.${index}.unit`
            ]
          }
          return []
        })()
      ]
    },
    eidtItems() {
      try {
        this.formData.items.map((item, index) => {
          this.formData.items.map((item2, index2) => {
            if (index !== index2 && `${item.type}_${item.name}` == `${item2.type}_${item2.name}`) {
              throw new Error('')
            }
          })
        })
      } catch (error) {
        this.$message.warning('子物料重复')
        return false
      }
      return true
    },
    operation() {
      return this.operationBtn({
        edit: {
          click: ({ row, index, column }) => {
            this.$refs.tabPage.addTab({
              activeKey: 'edit',
              key: 'edit',
              label: '编辑',
              triggerEvent: () => {
                this.openForm()
                goodsMaterialDetail({ id: row.id }).then(res => {
                  this.formData = res.data
                })
              }
            })
          }
        },
        qiyjiny: {
          name: ({ row, index, column }) => {
            return row.state == 'ON' ? '禁用' : '启用'
          },
          prompt: ({ row, index, column }) => {
            return `是否${row.state == 'ON' ? '禁用' : '启用'}?`
          },
          click: ({ row, index, column }) => {
            goodsMaterialBatchUpdateStatus({
              ids: row.id,
              stateEnum: row.state == 'ON' ? 'OFF' : 'ON'
            }).then(res => {
              this.$message({
                type: 'success',
                message: '设置成功'
              })
              this.$refs.pageRef.refreshList()
            })
          }
        }
      })
    },
    openForm() {
      this.formCancel()
      getBrandList({
        status: true
      }).then(res => {
        this.brandList = res.data.map(item => ({
          label: item.brandName,
          value: item.id
        }))
      })
      getClassifyList({
        type: 2,
        status: true
      }).then(res => {
        this.ClassifyList = res.data
      })
    },
    formCancel() {
      this.$refs?.formRef?.resetFields()
      this.$data.formData = this.$options.data().formData
    },
    queding(removeTab) {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid && this.eidtItems()) {
          ;[goodsMaterialAdd, goodsMaterialUpdate][this.formData.id ? 1 : 0](this.formData).then(res => {
            this.$message({
              type: 'success',
              message: '保存成功'
            })
            this.$refs.pageRef.refreshList()
            removeTab()
          })
        }
      })
    },
    delProduct(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
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.tab {
  padding: 20px 20px 0 20px;
}
</style>
