<template>
  <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">
    <el-dialog title="" width="860px" custom-class="diy-dialog" append-to-body :modal="true" :visible.sync="formDialog"
      :show-close="true" :close-on-click-modal="false" :modal-append-to-body="false" :before-close="formCancel">
      <zj-form-container ref="formRef" :form-data="formData" :styleSwitch="false">
        <zj-form-module :title="formDialogTitles[formDialogType]" label-width="120px" :showPackUp="false"
          :form-data="formData" :form-items="formItems">
        </zj-form-module>
      </zj-form-container>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="formCancel">取 消</el-button>
        <el-button size="mini" @click="formConfirm" type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </template-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 { materialNormList, materialNormListExport, materialNormAdd, materialNormEdit, materialNormDetail, materialNormBatchUpdateStatus } from "@/api/auxiliaryChargeManagement";
import { materialCategoryTree } from "@/api/auxiliaryMaterialClass";
import { getTypeList } from "@/api/auxiliaryFittings/attachmentProfile";
export default {
  components: { TemplatePage },
  mixins: [import_mixin],
  data() {
    return {
      // 事件组合
      optionsEvensGroup: [
        [
          [
            {
              name: '新建',
              isRole: true,
              click: this.addData
            }
          ],
        ],
        [
          [
            {
              name: '批量上架',
              isRole: true,
              click: () => {
                if (this.recordSelected.length) {
                  this.setRowStatus("ON")
                } else {
                  this.$message({
                    type: 'warning',
                    message: `请先勾选需要设置的数据！`,
                  });
                }
              }
            }
          ],
          [
            {
              name: '批量下架',
              isRole: true,
              click: () => {
                if (this.recordSelected.length) {
                  this.setRowStatus("OFF")
                } else {
                  this.$message({
                    type: 'warning',
                    message: `请先勾选需要设置的数据！`,
                  });
                }
              }
            }
          ],
        ],
      ],
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      // 勾选选中行
      recordSelected: [],
      /** 表单变量 */
      formDialogType: 0,
      formDialogTitles: ["新增", "编辑"],
      formDialog: false,
      formData: {
        companyWechatName: JSON.parse(localStorage.getItem('greemall_user')).companyName,
        "categoryId": "",
        "companyWechatId": "",
        "createBy": "",
        "createTime": "",
        "normAmount": 0,
        "normCode": "",
        "normId": "",
        "normName": "",
        "normType": "",
        "outWebsitAmount": 0,
        "outWorkerAmount": 0,
        "parentCategoryId": "",
        "remark": "",
        "selfWebsitAmount": 0,
        "selfWorkerAmount": 0,
        "specification": "",
        "status": "ON",
        "unit": "",
      },
      partsUnitList: [],
      materialCategoryTree: []
    }
  },
  computed: {
    // 更多参数
    moreParameters() {
      return []
    },
    formItems() {
      return [{
        md: 12,
        isShow: true,
        name: 'el-input',
        attributes: { placeholder: '请输入', disabled: true },
        formItemAttributes: {
          label: '所属商户',
          prop: 'companyWechatName',
          rules: [...required]
        }
      }, {
        md: 12,
        isShow: true,
        name: 'el-radio',
        options: [{ label: "上架", value: "ON" }, { label: "下架", value: "OFF" }],
        attributes: {},
        formItemAttributes: {
          label: '状态',
          prop: 'status',
          rules: [...required]
        },
      }, {
        md: 12,
        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: 'categoryId',
          rules: [...required]
        }
      }, {
        md: 12,
        isShow: true,
        name: 'el-input',
        attributes: { placeholder: '请输入' },
        formItemAttributes: {
          label: '辅材名称',
          prop: 'normName',
          rules: [...required]
        }
      }, {
        md: 12,
        isShow: true,
        name: 'el-select-add',
        labelKey: 'dictValue',
        valueKey: 'dictValue',
        options: this.partsUnitList,
        attributes: { placeholder: '请选择单位', filterable: true, clearable: true },
        formItemAttributes: {
          label: '单位',
          prop: 'unit',
          rules: [...required]
        }
      }, {
        md: 12,
        isShow: true,
        name: 'el-input',
        attributes: { placeholder: '请输入' },
        formItemAttributes: {
          label: '商品代码',
          prop: 'normCode',
          rules: []
        }
      }, {
        md: 12,
        isShow: true,
        name: 'el-input',
        attributes: { placeholder: '请输入' },
        formItemAttributes: {
          label: '规格型号',
          prop: 'specification',
          rules: []
        }
      }, {
        md: 12,
        isShow: true,
        name: 'el-radio',
        options: [{ label: "物料收费", value: "M" }, { label: "服务收费", value: "S" }],
        attributes: {},
        formItemAttributes: {
          label: '收费类型',
          prop: 'normType',
          rules: [...required]
        },
      }, {
        md: 12,
        isShow: true,
        name: 'el-input',
        attributes: { placeholder: '请输入', type: "number" },
        formItemAttributes: {
          label: '收费标准',
          prop: 'normAmount',
          rules: [...required]
        },
        events: {
          input: (val) => {
            this.formData.selfWorkerAmount = ""
            this.formData.outWorkerAmount = ""
            this.$nextTick(() => {
              this.formData.selfWebsitAmount = this.setNumber(
                this.formData.normAmount - (this.formData.selfWorkerAmount || 0)
              )
              this.formData.outWebsitAmount = this.setNumber(
                this.formData.normAmount - (this.formData.outWorkerAmount || 0)
              )
            })
          }
        },
      }, {
        md: 12,
        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">注：分账金额需扣除手续费0.6%</div>
          )
        }
      }, {
        md: 12,
        isShow: true,
        name: 'el-input',
        attributes: { placeholder: '请输入', type: "number", disabled: !this.formData.normAmount, },
        formItemAttributes: {
          label: '自有库存师傅(分账金额)',
          prop: 'selfWorkerAmount',
          rules: [...required]
        },
        events: {
          input: (val) => {
            if (Number(val) > this.formData.normAmount) {
              this.formData.selfWorkerAmount = this.setNumber(
                this.formData.normAmount
              )
            }
            this.formData.selfWebsitAmount = this.setNumber(
              this.formData.normAmount - this.formData.selfWorkerAmount
            )
          }
        },
        slots: {
          append: (h, { props, onInput }) => {
            return <div>元</div>
          }
        }
      }, {
        md: 12,
        isShow: true,
        name: 'el-input',
        attributes: { placeholder: '请输入', type: "number", disabled: !this.formData.normAmount, },
        formItemAttributes: {
          label: '外购辅材师傅(分账金额)',
          prop: 'outWorkerAmount',
          rules: [...required]
        },
        events: {
          input: (val) => {
            if (Number(val) > this.formData.normAmount) {
              this.formData.outWorkerAmount = this.setNumber(
                this.formData.normAmount
              )
            }
            this.formData.outWebsitAmount = this.setNumber(
              this.formData.normAmount - this.formData.outWorkerAmount
            )
          }
        },
        slots: {
          append: (h, { props, onInput }) => {
            return <div>元</div>
          }
        }
      }, {
        md: 12,
        isShow: true,
        name: 'el-input',
        attributes: { placeholder: '请输入', disabled: true, type: "number", },
        formItemAttributes: {
          label: '自有库存网点(分账金额)',
          prop: 'selfWebsitAmount',
          rules: [...required]
        },
        slots: {
          append: (h, { props, onInput }) => {
            return <div>元</div>
          }
        }
      }, {
        md: 12,
        isShow: true,
        name: 'el-input',
        attributes: { placeholder: '请输入', disabled: true, type: "number", },
        formItemAttributes: {
          label: '外购辅材网点(分账金额)',
          prop: 'outWebsitAmount',
          rules: [...required]
        },
        slots: {
          append: (h, { props, onInput }) => {
            return <div>元</div>
          }
        }
      }, {
        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(h, { row, index, column }) {
      return (
        <div class='operation-btns'>
          <el-button type="text" onClick={() => {
            materialNormDetail({ id: row.normId }).then(res => {
              Object.assign(this.formData, res.data)
              this.formDialogType = 1
              this.openForm()
            })
          }}>编辑</el-button>
        </div>
      )
    },
    addData() {
      this.formDialogType = 0
      this.openForm()
    },
    openForm() {
      Promise.all([
        getTypeList({ "pageNum": 1, "pageSize": -1, "params": [{ "param": "a.dict_type", "compare": "=", "value": `PARTS_UNIT` }, { "param": "a.status", "compare": "=", "value": "ON" }] }),
        materialCategoryTree()
      ]).then(([res1, res2]) => {
        this.partsUnitList = res1.data.records
        this.materialCategoryTree = res2.data.filter(item => (item.child && item.child.length > 0))
        this.formDialog = true;
      })
    },
    formCancel() {
      this.$refs.formRef.$refs.inlineForm.clearValidate()
      this.$data.formData = this.$options.data().formData
      this.formDialog = false
    },
    formConfirm() {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          ([materialNormAdd, materialNormEdit][this.formDialogType])(this.formData).then(res => {
            this.$message({ type: 'success', message: `${this.formDialogTitles[this.formDialogType]}成功!` })
            this.formCancel()
            this.$refs.pageRef.refreshList()
          })
        }
      })
    },
    setRowStatus(type) {
      materialNormBatchUpdateStatus({
        ids: this.recordSelected.map(item => item.normId).join(','),
        stateEnum: type
      }).then(res => {
        this.$message({ type: 'success', message: `设置成功!` })
        this.$refs.pageRef.refreshList()
      })
    },
    setNumber(val) {
      return Number(val.toFixed(2))
    }
  }
}
</script>

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