<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"
          :operation="operation()"
          :exportList="exportList"
          :operationColumnWidth="80"
        >
        </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" :styleSwitch="false">
          <zj-form-module
            title=""
            label-width="120px"
            :showPackUp="false"
            :form-data="formData"
            :form-items="formItems"
          >
          </zj-form-module>
        </zj-form-container>
        <div slot="footer" class="dialog-footer" style="text-align: right">
          <el-button size="mini" @click="data.removeTab()">取 消</el-button>
          <el-button size="mini" @click="formConfirm(data.removeTab)" type="primary">确 定</el-button>
        </div>
      </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 { required, mobileRequired, mobile } from '@/components/template/rules_verify.js'
import {
  websitGoodsmImport,
  materialNormList,
  materialNormListExport,
  materialNormAdd,
  materialNormEdit,
  materialNormDetail,
  materialNormBatchUpdateStatus
} from '@/api/auxiliaryPriceManagement'
import { materialCategoryTree } from '@/api/auxiliaryMaterialClass'
import { getTypeList } from '@/api/auxiliaryFittings/attachmentProfile'
import { commonTemplateDownload } from '@/api/common.js'
import operation_mixin from '@/components/template/operation_mixin.js'
export default {
  components: { TemplatePage },
  mixins: [import_mixin, operation_mixin],
  data() {
    return {
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      // 勾选选中行
      recordSelected: [],
      /** 表单变量 */
      formDialogType: 0,
      formDialogTitles: ['新增', '编辑'],
      formDialog: false,
      formData: {
        companyWechatName: JSON.parse(localStorage.getItem('greemall_user')).companyName,
        convertBitScale: '',
        cost: '',
        createBy: '',
        createTime: '',
        goodsBarcodeId: '',
        goodsCategoryId: '',
        goodsCode: '',
        goodsId: '',
        goodsImage: '',
        goodsName: '',
        goodsSpecification: '',
        goodsSpell: '',
        goodsStockUnit: '',
        goodsType: 'M',
        marketPrice: '',
        manageWorkerStock: 'YES',
        goodsSalesConvertQty: 1,
        goodsSalesUnit: '',
        normAmount: '',
        normType: '',
        outWebsitAmount: '',
        outWorkerAmount: '',
        parentCategoryId: '',
        remark: '',
        selfWebsitAmount: '',
        selfWorkerAmount: '',
        status: 'ON',
        costRangeMini: 0,
        costRangeMax: 0,
        limitPriceMultiples: 1
      },
      partsUnitList: [],
      materialCategoryTree: [],
      formType: 'add',
      formVisible: false
    }
  },
  computed: {
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth('add', {
              click: () => {
                this.openForm('add')
              }
            })
          ],
          [
            this.optionsEvensAuth(['imp', 'template'], {
              name: '导入辅材',
              click: () => {}
            }),
            this.optionsEvensAuth('imp', ({ moduleName }) => {
              return {
                name: moduleName,
                render: () => {
                  return this.importButton(websitGoodsmImport, moduleName)
                }
              }
            }),
            this.optionsEvensAuth('template', {
              click: () => {
                commonTemplateDownload({ name: '辅材模板.xlsx' }, `辅材模板`)
                  .then(res => {
                    this.$message({
                      message: '下载成功',
                      type: 'success'
                    })
                  })
                  .catch(err => {
                    this.$message.error('下载失败')
                  })
              }
            })
          ]
        ],
        [
          [
            this.optionsEvensAuth('batchLaunch', {
              click: () => {
                if (this.recordSelected.length) {
                  this.setRowStatus('ON')
                } else {
                  this.$message({
                    type: 'warning',
                    message: `请先勾选需要设置的数据！`
                  })
                }
              }
            })
          ],
          [
            this.optionsEvensAuth('batchRemoval', {
              click: () => {
                if (this.recordSelected.length) {
                  this.setRowStatus('OFF')
                } else {
                  this.$message({
                    type: 'warning',
                    message: `请先勾选需要设置的数据！`
                  })
                }
              }
            })
          ]
        ]
      ]
    },
    // 更多参数
    moreParameters() {
      return []
    },
    formItems() {
      return [
        {
          md: 6,
          isShow: true,
          name: 'el-radio',
          options: [
            { label: '上架', value: 'ON' },
            { label: '下架', value: 'OFF' }
          ],
          attributes: {},
          formItemAttributes: {
            label: '状态',
            prop: 'status',
            rules: [...required]
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-cascader',
          attributes: {
            style: 'width:100%',
            placeholder: '请输入',
            options: this.materialCategoryTree,
            'show-all-levels': false,
            props: { value: 'categoryId', label: 'categoryName', children: 'child', emitPath: false },
            clearable: true
          },
          formItemAttributes: {
            label: '选择分类',
            prop: 'goodsCategoryId',
            rules: [...required]
          },
          events: {
            change: val => {
              this.$refs.formRef.validateField(['goodsCategoryId'], (valid, invalidFields, errLabels) => {})
            }
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入' },
          formItemAttributes: {
            label: '辅材名称',
            prop: 'goodsName',
            rules: [...required]
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-select-add',
          labelKey: 'dictValue',
          valueKey: 'dictValue',
          options: this.partsUnitList,
          attributes: { placeholder: '请选择单位', filterable: true, clearable: true },
          formItemAttributes: {
            label: '单位',
            prop: 'goodsStockUnit',
            rules: [...required]
          },
          events: {
            change: val => {
              this.$refs.formRef.validateField(['goodsStockUnit'], (valid, invalidFields, errLabels) => {})
            }
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入' },
          formItemAttributes: {
            label: '辅材代码',
            prop: 'goodsCode',
            rules: []
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入' },
          formItemAttributes: {
            label: '规格型号',
            prop: 'goodsSpecification',
            rules: []
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入', type: 'number' },
          formItemAttributes: {
            label: '采购价格',
            prop: 'cost',
            rules: []
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入', type: 'number' },
          formItemAttributes: {
            label: '销售价格',
            prop: 'marketPrice',
            rules: [...required]
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'slot-component',
          attributes: { placeholder: '请输入' },
          formItemAttributes: {
            label: '',
            prop: '',
            'label-width': '0px'
          },
          render: (h, { props, onInput }) => {
            var { value } = props
            return <div style="color:red">注：销售价格即网点销售给师傅的辅材价格</div>
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-radio',
          options: [
            { label: '记', value: 'YES' },
            { label: '不记', value: 'NO' }
          ],
          attributes: {},
          formItemAttributes: {
            label: '师傅库存',
            prop: 'manageWorkerStock',
            rules: [...required]
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入', type: 'number' },
          formItemAttributes: {
            label: '单位转换系数',
            prop: 'goodsSalesConvertQty',
            rules: [...required]
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入' },
          formItemAttributes: {
            label: '销售单位',
            prop: 'goodsSalesUnit',
            rules: [...required]
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入', type: 'number' },
          formItemAttributes: {
            label: '进价范围最小值',
            prop: 'costRangeMini',
            rules: [...required]
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入', type: 'number' },
          formItemAttributes: {
            label: '进价范围最大值',
            prop: 'costRangeMax',
            rules: [...required]
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入', type: 'number' },
          formItemAttributes: {
            label: '进价售价倍数',
            prop: 'limitPriceMultiples',
            rules: [...required]
          },
          events: {
            input: value => {
              if (Number(value) < 1) {
                this.formData.limitPriceMultiples = 1
              }
            }
          }
        },
        {
          md: 24,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入', type: 'textarea' },
          formItemAttributes: {
            label: '备注',
            prop: 'remark',
            rules: []
          }
        }
      ]
    }
  },
  methods: {
    // 列表请求函数
    getList: materialNormList,
    // 列表导出函数
    exportList: materialNormListExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },

    operation() {
      return this.operationBtn({
        edit: {
          click: ({ row, index, column }) => {
            this.openForm('edit', row.goodsId)
          }
        }
      })
    },
    openForm(type, id) {
      this.$refs.tabPage.addTab({
        // 对应显示的模块
        activeKey: type,
        // 唯一标识
        key: type,
        // 页签名称
        label: { edit: '编辑', add: '新增' }[type],
        // 打开时事件
        triggerEvent: () => {
          this.formCancel()
          this.$nextTick(() => {
            this.formType = type
            this.formVisible = true
            Promise.all([
              getTypeList({
                pageNum: 1,
                pageSize: -1,
                params: [
                  { param: 'a.dict_type', compare: '=', value: `ASSIST_UNIT` },
                  { param: 'a.status', compare: '=', value: 'ON' }
                ]
              }),
              materialCategoryTree({ state: 'ON' })
            ]).then(([res1, res2]) => {
              this.partsUnitList = res1.data.records
              this.materialCategoryTree = res2.data.filter(item => item.child && item.child.length > 0)
              this.formDialog = true
            })
            if (type == 'add') {
              this.formDialogType = 0
            } else if (type == 'edit') {
              this.formDialogType = 1
              materialNormDetail({ id }).then(res => {
                Object.assign(this.formData, res.data)
              })
            }
          })
        },
        // 关闭时事件
        closeEvent: () => {
          this.formCancel()
        }
      })
    },
    formCancel() {
      this.formVisible = false
      this.$refs?.formRef?.resetFields()
      this.$data.formData = this.$options.data().formData
    },
    formConfirm(cancel) {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          ;[materialNormAdd, materialNormEdit][this.formDialogType]({ ...this.formData, goodsType: 'M' }).then(res => {
            this.$message({ type: 'success', message: `${this.formDialogTitles[this.formDialogType]}成功!` })
            cancel('list')
            this.$refs.pageRef.refreshList()
          })
        }
      })
    },
    setRowStatus(type) {
      materialNormBatchUpdateStatus({
        ids: this.recordSelected.map(item => item.goodsId).join(','),
        stateEnum: type
      }).then(res => {
        this.$message({ type: 'success', message: `设置成功!` })
        this.$refs.pageRef.refreshList()
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
