<template>
  <template-page ref="pageRef" :get-list="getList" :exportList="exportList" :table-attributes="tableAttributes"
    :table-events="tableEvents" :options-evens-group="optionsEvensGroup" :moreParameters="moreParameters"
    :column-parsing="columnParsing" :operation="operation()" :replaceOrNotMap="false">
    <div class="cartographer">
      <el-dialog title="增值服务配置" width="100%" :modal="false" :visible.sync="formDialog" :before-close="formCancel">
        <zj-form-container v-if="formDialog" 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">
          <el-button size="mini" @click="formCancel">取 消</el-button>
          <el-button size="mini" @click="formConfirm" type="primary">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </template-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import { increConfigList, increConfigListExport, increConfigDetail, increConfigAdd, increConfigUpdate, increConfigUpOrDown } from "@/api/valueAddedConfig.js"
import { required, mobileRequired, mobile, httpUrl, email } from '@/components/template/rules_verify.js'
import { getClassifyList } from '@/api/goods'
import { getDataDictionary } from '@/api/dataDictionary.js'
import operation_mixin from '@/components/template/operation_mixin.js'
import { getWebsit } from "@/api/customerManagement.js"
export default {
  props: {
    storageType: {
      type: String,
      default: ""
    }
  },
  components: { TemplatePage },
  mixins: [import_mixin, operation_mixin],
  data() {
    return {
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: false
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      // 勾选选中数据
      recordSelected: [],
      formData: {
        "companyWechatId": "",
        "companyWechatName": "",
        "intro": "",
        "reason": "",
        "remark": "",
        "status": true,
        "type": "",
        "usedType": "",
        pgIncreItems: [],
        pgIncreWebsits: []
      },
      formDialog: false,
      isEditIndex: -1,
      orderBrands: [],
      classifyList: [],
      classifyListLv2: [],
      clickLook: true,
      websitList: [],
      websitIndex: -1
    }
  },
  computed: {
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth("add", {
              click: () => {
                this.openForm()
              }
            })
          ],
        ]
      ]
    },
    // 更多参数
    moreParameters() {
      return []
    },
    columns() {
      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={`pgIncreItems.${index}.${column.columnAttributes.prop}`} rules={required}>
                <el-select
                  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={`pgIncreItems.${index}.${column.columnAttributes.prop}`} rules={required}>
                <el-select
                  value={row[column.columnAttributes.prop]}
                  onInput={(val) => { row[column.columnAttributes.prop] = val }}
                  onChange={(val) => {
                    if (val) {
                      var data = this.classifyList.find(item => item.categoryId == val)
                      row.mainName = data.name
                    } else {
                      row.mainName = ""
                    }
                  }}
                  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-left:10px">{row.mainName}</div>
          }
        },
        {
          columnAttributes: {
            label: '服务内容',
            prop: 'content'
          },
          render: (h, { row, column, index }) => {
            return this.isEditIndex == index ? <div class="redbordererr">
              <el-form-item label="" label-width="0px" prop={`pgIncreItems.${index}.${column.columnAttributes.prop}`} rules={required}>
                <el-input
                  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: 'limitNum'
          },
          render: (h, { row, column, index }) => {
            return this.isEditIndex == index ? <div class="redbordererr">
              <el-form-item label="" label-width="0px" prop={`pgIncreItems.${index}.${column.columnAttributes.prop}`} rules={required} >
                <el-input
                  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: 'amount'
          },
          render: (h, { row, column, index }) => {
            return this.isEditIndex == index ? <div class="redbordererr">
              <el-form-item label="" label-width="0px" prop={`pgIncreItems.${index}.${column.columnAttributes.prop}`} rules={required}>
                <el-input
                  type="number"
                  value={row[column.columnAttributes.prop]}
                  onInput={(val) => {
                    row[column.columnAttributes.prop] = val
                    if (val && row.workerAmount && Number(row.workerAmount) > Number(val)) {
                      row.workerAmount = val
                    }
                  }}
                  placeholder="请输入内容"
                >
                </el-input>
              </el-form-item>
            </div> : <div style="padding-left:10px">{row[column.columnAttributes.prop]}</div>
          }
        },
        {
          columnAttributes: {
            label: '师傅分成金额',
            prop: 'workerAmount'
          },
          render: (h, { row, column, index }) => {
            return this.isEditIndex == index ? <div class="redbordererr">
              <el-form-item label="" label-width="0px" prop={`pgIncreItems.${index}.${column.columnAttributes.prop}`} rules={required}>
                <el-input
                  type="number"
                  value={row[column.columnAttributes.prop]}
                  onInput={(val) => {
                    row[column.columnAttributes.prop] = val && row.amount && Number(val) > Number(row.amount) ? row.amount : val
                  }}
                  placeholder="请输入内容"
                >
                </el-input>
              </el-form-item>
            </div> : <div style="padding-left:10px">{row[column.columnAttributes.prop]}</div>
          }
        },
        {
          columnAttributes: {
            label: '网点分成金额',
            prop: 'websitAmount'
          },
          render: (h, { row, column, index }) => {
            row[column.columnAttributes.prop] = (Number(row["amount"]) - Number(row["workerAmount"])).toFixed(2)
            return <div style="padding-left:10px">{row[column.columnAttributes.prop]}</div>
          }
        },
        {
          columnAttributes: {
            label: '创建人',
            prop: 'createBy'
          }
        },
        {
          columnAttributes: {
            label: '创建时间',
            prop: 'createTime'
          }
        },
        {
          columnAttributes: {
            label: '修改人',
            prop: 'updateBy'
          }
        },
        {
          columnAttributes: {
            label: '修改时间',
            prop: 'updateTime'
          }
        },
        {
          columnAttributes: {
            label: '操作',
          },
          render: (h, { row, column, index }) => {
            return <div style="padding-left:10px">
              <el-button type="text" onClick={() => {
                if (this.isEditIndex === index) {
                  this.isEditIndex = -1
                }
                this.formData.pgIncreItems.splice(index, 1)
              }}>删除</el-button>
              {this.isEditIndex == index && <el-button type="text" onClick={() => {
                if (this.panduancp()) {
                  this.$refs.formRef.validateField(this.getVfyKey(index), (valid, invalidFields, errLabels) => {
                    if (valid) {
                      this.isEditIndex = -1
                    }
                  })
                }
              }}>确定</el-button>}
              {this.isEditIndex == -1 && <el-button type="text" onClick={() => {
                this.isEditIndex = index
              }}>编辑</el-button>}
            </div>
          }
        }
      ]
    },
    formItems() {
      return [
        {
          name: 'el-input',
          md: 8,
          attributes: { disabled: true, placeholder: '请输入' },
          formItemAttributes: {
            label: '所属商户',
            prop: 'companyWechatName',
          }
        },
        {
          name: 'slot-component',
          md: 16,
          formItemAttributes: { label: '', prop: '' },
          render: (h, { props }) => { return null }
        },
        {
          name: 'el-select',
          md: 8,
          options: [{ label: "延保", value: 1 }, { label: "清洗", value: 2 }],
          attributes: {
            placeholder: '请选择',
            clearable: true,
            filterable: true
          },
          formItemAttributes: {
            label: '服务类型',
            prop: 'type',
            rules: [...required]
          },
          events: {
            change: (val) => {
              if (val == 1) {
                this.formData.usedType = "YEAR"
              }
            }
          }
        },
        {
          name: 'slot-component',
          md: 16,
          formItemAttributes: { label: '', prop: '' },
          render: (h, { props }) => { return null }
        },
        {
          name: 'el-select',
          md: 8,
          options: [{ label: "使用次数", value: "COUNT" }, { label: "使用年限", value: "YEAR" }],
          attributes: {
            placeholder: '请选择',
            clearable: true,
            filterable: true,
            disabled: this.formData.type == 1
          },
          formItemAttributes: {
            label: '使用类型',
            prop: 'usedType',
            rules: [...required]
          }
        },
        {
          name: 'slot-component',
          md: 16,
          formItemAttributes: { label: '', prop: '' },
          render: (h, { props }) => { return null }
        },
        {
          name: 'el-input',
          md: 8,
          name: 'el-radio',
          options: [{ label: "上架", value: true }, { label: "下架", value: false }],
          formItemAttributes: {
            label: '状态',
            prop: 'status',
            rules: [...required]
          }
        },
        {
          md: 24,
          isShow: true,
          name: 'slot-component',
          formItemAttributes: {
            label: '服务内容',
            prop: 'pgIncreItems',
            rules: [...required]
          },
          render: (h, { props, onInput }) => {
            var { value } = props
            return (
              <div>
                <div style="margin-bottom:8px">
                  <el-button onClick={() => {
                    if (this.panduancp()) {
                      if (this.formData.pgIncreItems.length == 0) {
                        this.formData.pgIncreItems.push({
                          "amount": "",
                          "brandId": "",
                          "brandName": "",
                          "content": "",
                          "limitNum": "",
                          "mainId": "",
                          "mainName": "",
                          "websitAmount": "",
                          "workerAmount": "",
                        })
                        this.isEditIndex = this.formData.pgIncreItems.length - 1
                      } else {
                        this.$refs.formRef.validateField(this.getVfyKey(this.isEditIndex), (valid, invalidFields, errLabels) => {
                          if (valid) {
                            this.formData.pgIncreItems.push({
                              "amount": "",
                              "brandId": "",
                              "brandName": "",
                              "content": "",
                              "limitNum": "",
                              "mainId": "",
                              "mainName": "",
                              "websitAmount": "",
                              "workerAmount": "",
                            })
                            this.isEditIndex = this.formData.pgIncreItems.length - 1
                          }
                        })
                      }
                    }
                  }}>添加</el-button>
                </div>
                <zj-table
                  columns={this.columns}
                  tableData={this.formData.pgIncreItems}
                  tableAttributes={{
                    size: 'mini',
                    border: true,
                  }} />
              </div>
            )
          }
        },
        {
          name: 'el-input',
          md: 24,
          attributes: {
            disabled: false,
            placeholder: '请输入',
            type: "textarea",
            autosize: { minRows: 2, maxRows: 4 },
            maxlength: 50,
            'show-word-limit': true
          },
          formItemAttributes: {
            label: '服务介绍',
            prop: 'intro',
            rules: [...required]
          }
        },
        {
          md: 24,
          name: 'slot-component',
          formItemAttributes: {
            label: '服务说明',
            prop: 'reason',
            rules: [...required]
          },
          render: (h, { props, onInput }) => {
            var { value } = props
            return (
              <v-quill-editor value={value} onInput={onInput} />
            )
          }
        },
        {
          md: 24,
          name: 'slot-component',
          formItemAttributes: {
            label: '服务网点',
            prop: 'pgIncreWebsits',
            rules: [...required]
          },
          render: (h, { props, onInput }) => {
            var { value } = props
            return (
              <div>
                <div style="margin-bottom:8px">
                  <el-button onClick={() => {
                    this.formData.pgIncreWebsits.push({
                      websitId: "",
                      linkName: "",
                      websitPhone: "",
                      address: "",
                    });
                    this.websitIndex = this.formData.pgIncreWebsits.length - 1
                  }}>添加</el-button>
                </div>
                <zj-table
                  columns={[{
                    columnAttributes: {
                      label: '网点名称',
                      prop: 'websitId'
                    },
                    render: (h, { row, column, index }) => {
                      return <div>
                        <el-form-item label="" label-width="0px" prop={`pgIncreWebsits.${index}.${column.columnAttributes.prop}`} rules={required}>
                          <el-select
                            value={row[column.columnAttributes.prop]}
                            onInput={(val) => { row[column.columnAttributes.prop] = val }}
                            disabled={!(this.websitIndex == index)}
                            onChange={(val) => {
                              if (val) {
                                var data = this.websitList.find(item => item.value == val)
                                row.linkName = data.data.linkName
                                row.websitPhone = data.data.websitPhone
                                row.address = data.data.address
                              } else {
                                row.linkName = ""
                                row.websitPhone = ""
                                row.address = ""
                              }
                            }}
                            placeholder="请选择">
                            {this.websitList.filter(item => (row.websitId == item.value || !this.formData.pgIncreWebsits.find(val => (val.websitId == item.value)))).map((item, index_) => <el-option key={index_} label={item.label} value={item.value}></el-option>)}
                          </el-select>
                        </el-form-item>
                      </div>
                    }
                  },
                  {
                    columnAttributes: {
                      label: '联系人',
                      prop: 'linkName'
                    }
                  },
                  {
                    columnAttributes: {
                      label: '联系电话',
                      prop: 'websitPhone'
                    }
                  },
                  {
                    columnAttributes: {
                      label: '地址',
                      prop: 'address'
                    }
                  },
                  {
                    columnAttributes: {
                      label: '操作',
                    },
                    render: (h, { row, column, index }) => {
                      return <div style="padding-left:10px">
                        {this.websitIndex == index ? <el-button type="text" onClick={() => {
                          this.websitIndex = -1
                        }}>确定</el-button> : null}
                        {this.websitIndex != index ? <el-button type="text" onClick={() => {
                          this.websitIndex = index
                        }}>编辑</el-button> : null}
                        <el-button type="text" onClick={() => {
                          if (this.websitIndex == index) {
                            this.websitIndex = -1
                          }
                          this.formData.pgIncreWebsits.splice(index, 1)
                        }}>删除</el-button>
                      </div>
                    }
                  }]}
                  tableData={this.formData.pgIncreWebsits}
                  tableAttributes={{
                    size: 'mini',
                    border: true,
                  }} />
              </div>
            )
          }
        },
        {
          name: 'el-input',
          md: 24,
          attributes: { disabled: false, placeholder: '请输入', type: "textarea" },
          formItemAttributes: {
            label: '备注',
            prop: 'remark',
            rules: []
          }
        },
      ]
    }
  },
  methods: {
    // 列表请求函数
    getList: increConfigList,
    // 列表导出函数
    exportList: increConfigListExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    // 表格操作列
    operation() {
      return this.operationBtn({
        detail: {
          btnType: 'text',
          click: ({ row, index, column }) => {
            this.getDetail(row.id)
          }
        }
      })
    },
    panduancp() {
      try {
        this.formData.pgIncreItems.map((row, index) => {
          this.formData.pgIncreItems.map((item, index_) => {
            if (
              `${row.brandId}_${row.mainId}_${row.content}` == `${item.brandId}_${item.mainId}_${item.content}` &&
              index_ != index
            ) {
              throw new Error('');
            }
          })
        })
      } catch (error) {
        this.$message.warning('服务内容重复')
        return false
      }
      return true
    },
    getDetail(id) {
      increConfigDetail({ id }).then(res => {
        Object.assign(this.formData, res.data, {
          pgIncreWebsits: res.data.pgIncreWebsits || []
        })
        this.openForm()
      })
    },
    getVfyKey(index, bool = true) {
      return [
        ...(() => {
          if (bool) {
            return [
              `pgIncreItems`,
            ]
          }
          return []
        })(),
        ...(() => {
          if (index > -1) {
            return [
              `pgIncreItems.${index}.brandId`,
              `pgIncreItems.${index}.mainId`,
              `pgIncreItems.${index}.content`,
              `pgIncreItems.${index}.limitNum`,
              `pgIncreItems.${index}.amount`,
              `pgIncreItems.${index}.websitAmount`,
              `pgIncreItems.${index}.workerAmount`,
            ]
          }
          return []
        })()
      ]
    },
    openForm() {
      Promise.all([
        getDataDictionary({ "pageNum": 1, "pageSize": -1, "params": [{ "param": "a.status", "compare": "=", "value": "ON" }, { "param": "a.dict_type", "compare": "=", "value": "BRAND" }] }),
        getClassifyList({ type: 2, status: true }),
        getWebsit({ isIncre: true, status:true })
      ]).then(([res1, res2, res3]) => {
        // 获取品牌
        this.orderBrands = res1.data.records.map(item => ({
          value: item.dictCode,
          label: item.dictValue
        }))
        // 获取产品大类小类
        var classifyListLv2 = []
        this.classifyList = res2.data.map(item => {
          var { children, ...data } = item
          classifyListLv2.push(...(children || []))
          return {
            ...data
          }
        });
        this.classifyListLv2 = classifyListLv2

        this.websitList = res3.data.map(item => ({
          label: item.name,
          value: item.websitId,
          data: item
        }))

        var { companyWechatId, companyName } = JSON.parse(localStorage.getItem('greemall_user'))
        this.formData.companyWechatId = companyWechatId
        this.formData.companyWechatName = companyName
        // 打开弹窗
        this.formDialog = true
      })
    },
    // 关闭弹窗
    formCancel() {
      this.$refs.formRef.$refs.inlineForm.clearValidate()
      this.$data.formData = this.$options.data().formData
      this.isEditIndex = -1
      this.formDialog = false
    },
    formConfirm() {
      if (this.clickLook && this.panduancp()) {
        this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
          if (valid) {
            this.clickLook = false;
            ([increConfigAdd, increConfigUpdate][this.formData.id ? 1 : 0])({
              ...this.formData
            }).then(res => {
              this.$message({ type: 'success', message: `成功!` })
              this.formCancel()
              this.$refs.pageRef.refreshList()
              this.clickLook = true
            }).catch(() => {
              this.clickLook = true
            })
          }
        })
      } else {
        this.$message.warning('服务内容没有确认')
      }
    },
  }
}
</script>

<style lang="scss">
.redbordererr {
  .el-form-item {
    margin: 0 !important;
    overflow: hidden;
  }
}
</style>
