<template>
	<zj-tab-page ref="tabPage" :defaultActives="[{ key: 'list', label: $route.meta.title+'-列表', essential: true }]">
		<template slot-scope="{activeKey, data}">
			<template-page v-if="activeKey == 'list'" ref="pageRef" :get-list="getList" :table-attributes="tableAttributes" :table-events="tableEvents"
			  :options-evens-group="optionsEvensGroup" :moreParameters="moreParameters" :column-parsing="columnParsing"
			  :operation="operation()" :exportList="exportList">
			</template-page>
			<div v-if="~['add', 'edit'].indexOf(activeKey)">
				<zj-form-container ref="formRef" :form-data="formData" :styleSwitch="false">
				  <zj-form-module title="" label-width="100px" :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="data.removeTab()">取 消</el-button>
				  <el-button size="mini" @click="formConfirm(data.removeTab)" type="primary">确 定</el-button>
				</div>
				<el-dialog title="" width="300px" custom-class="diy-dialog" append-to-body :modal="true" :visible.sync="formDialog2"
				  :show-close="true" :close-on-click-modal="false" :modal-append-to-body="false" :before-close="formCancel2">
				  <zj-form-container ref="formRef2" :form-data="formData2" :styleSwitch="false">
				    <zj-form-module title="地区选择" label-width="0px" :showPackUp="false" :form-data="formData2"
				      :form-items="formItems2">
				    </zj-form-module>
				  </zj-form-container>
				  <div slot="footer" class="dialog-footer">
				    <el-button size="mini" @click="formCancel2">取 消</el-button>
				    <el-button size="mini" @click="formConfirm2" type="primary">确 定</el-button>
				  </div>
				</el-dialog>
			</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 { freightListPageV2, freightPageExport, deleteFreight, addOrEditFreight, getFreightDetail, getRegionTree, changeFreightStatus } from "@/api/freight";
import operation_mixin from '@/components/template/operation_mixin.js'
export default {
  components: { TemplatePage },
  mixins: [import_mixin,operation_mixin],
  data() {
    return {
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: false
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      // 勾选选中行
      recordSelected: [],
      /** 表单变量 */
      formDialogType: 0,
      formDialogTitles: ["新增", "编辑"],
      formDialog: false,
      formData: {
        name: '',
        freightTemplateDetails: []
      },
      formDialog2: false,
      formData2: {},
      regionTree: [],
			formType: 'add',
			formVisible: false,
    }
  },
  computed: {
	// 事件组合
	optionsEvensGroup() {
		return [
			[
				[
					this.optionsEvensAuth("add", {
						click: () => {
							this.openForm('add')
						}
					})
				],
			]
		]
	},
    // 更多参数
    moreParameters() {
      return []
    },
    formItems() {
      return [{
        md: 24,
        isShow: true,
        name: 'el-input',
        attributes: { placeholder: '请输入' },
        formItemAttributes: {
          label: '仓储名称',
          prop: 'name',
          rules: [...required]
        }
      }, {
        md: 24,
        isShow: true,
        name: 'slot-component',
        formItemAttributes: {
          label: '配送区域',
          prop: '',
          rules: [...required]
        },
        render: (h, { props, onInput }) => {
          var { value } = props
          return (
            <div>
              <div><el-button type="primary" size="mini" onClick={() => {
                this.openForm2()
              }}>添加地区</el-button></div>
              <zj-table
                columns={[
                  {
                    columnAttributes: {
                      label: '省',
                      prop: 'province',
                      width: "140px",
                    }
                  },
                  {
                    columnAttributes: {
                      label: '市',
                      prop: 'city',
                      width: "140px",
                    }
                  },
                  {
                    columnAttributes: {
                      label: '首件(个)',
                      prop: 'firstLimit',
                      width: "160px",
                      'render-header': (h, obj) => this.renderHeader(h, obj, 'firstLimit')
                    },
                    render: this.tableInput
                  },
                  {
                    columnAttributes: {
                      label: '运费(元)',
                      prop: 'firstAmount',
                      width: "160px",
                      'render-header': (h, obj) => this.renderHeader(h, obj, 'firstAmount')
                    },
                    render: this.tableInput
                  },
                  {
                    columnAttributes: {
                      label: '续件(个)',
                      prop: 'continuousLimit',
                      width: "160px",
                      'render-header': (h, obj) => this.renderHeader(h, obj, 'continuousLimit')
                    },
                    render: this.tableInput
                  },
                  {
                    columnAttributes: {
                      label: '续费(元)',
                      prop: 'continuousAmount',
                      width: "160px",
                      'render-header': (h, obj) => this.renderHeader(h, obj, 'continuousAmount')
                    },
                    render: this.tableInput
                  },
                  {
                    columnAttributes: {
                      label: '操作',
                      prop: '',
                      width: "80px"
                    },
                    render: (h, { row, column, index }) => {
                      return <el-button size="mini" type="text" onClick={() => {
                        this.formData.freightTemplateDetails.splice(index, 1)
                      }}>删除</el-button>
                    }
                  }
                ]}
                tableData={this.formData.freightTemplateDetails}
                tableAttributes={{
                  size: 'mini',
                  border: true,
                }} />
            </div>
          )
        }
      }]
    },
    formItems2() {
      return [{
        md: 24,
        isShow: true,
        name: 'el-tree',
        attributes: {
          style: "max-height: 400px; overflow-y: scroll;",
          placeholder: '请输入', data: this.regionTree, 'show-checkbox': true, 'node-key': "id", props: {
            children: 'child',
            label: 'name'
          }
        },
        formItemAttributes: {
          label: '',
          prop: 'val',
          rules: [...required]
        }
      }]
    }
  },
  methods: {
    // 列表请求函数
    getList: freightListPageV2,
    // 列表导出函数
    exportList: freightPageExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
	// 表格操作列
	operation() {
		return this.operationBtn({
			edit: {
				btnType: 'text',
				click: ({ row, index, column }) => {
					this.openForm('edit',row.freightTemplateId)
				}
			},
			del: {
				btnType: 'text',
				prompt: '确定删除吗？',
				click: ({ row, index, column }) => {
					deleteFreight({ freightTemplateId: row.freightTemplateId }).then(() => {
					  this.$message({ type: 'success', message: '删除成功!' })
					  this.$refs.pageRef.refreshList()
					})
				}
			},
			status: {
				name: ({ row, index, column }) => {
					return row.status?'禁用':'启用'
				},
				btnType: 'text',
				prompt: ({ row, index, column }) => {
					return `是否${row.status?'禁用':'启用'}？`
				},
				click: ({ row, index, column }) => {
					changeFreightStatus({ freightTemplateId: row.freightTemplateId, status: !row.status }).then(res => {
					  this.$message({ type: 'success', message: `${row.status?'禁用':'启用'}成功!` })
					  this.$refs.pageRef.refreshList()
					})
				}
			},
		})
	},
    openForm(type, freightTemplateId) {
      this.$refs.tabPage.addTab({
      	// 对应显示的模块
      	activeKey: type,
      	// 唯一标识
      	key: type,
      	// 页签名称
      	label: ({ edit: "编辑", add: "新增" })[type],
      	// 打开时事件
      	triggerEvent: () => {
      		this.formCancel()
      		this.$nextTick(()=>{
      			this.formType = type
      			this.formVisible = true
      			if (type == 'add') {
      				this.formDialogType = 0
      			} else if(type == 'edit'){
      				this.formDialogType = 1
      				getFreightDetail({ freightTemplateId }).then(res => {
      				  Object.assign(this.formData, res.data)
      				})
      			}
      		})
      	},
      	// 关闭时事件
      	closeEvent: () => {
      	
      	}
      })
    },
    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) {
          addOrEditFreight(this.formData).then(res => {
            this.$message({ type: 'success', message: `${this.formDialogTitles[this.formDialogType]}成功!` })
            cancel('list')
            this.$refs.pageRef.refreshList()
          })
        }
      })
    },
    renderHeader(h, { column, $index }, type) {
      let that = this;
      return h(
        'div',
        [
          h('span', column.label),
          h('el-button', {
            props: {
              type: 'text',
              size: 'small',
            },
            style: 'color:#409EFF; margin-left:5px;',
            on: {
              click: function () {
                that.changeInput(type);
              }
            }
          }, '统一修改')
        ],
      )
    },
    changeInput(type) {
      const typeMap = {
        firstLimit: '首件',
        firstAmount: '运费',
        continuousLimit: '续件',
        continuousAmount: '续费'
      }
      this.$prompt('请输入' + typeMap[type], '编辑', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: function (value) {
          if (!value) return '请输入' + typeMap[type]
        },
      }).then(({ value }) => {
        this.formData.freightTemplateDetails.forEach(item => {
          item[type] = value;
        })
      }).catch(() => { });
    },
    tableInput(h, { row, column, index }) {
      return <el-form-item prop={`freightTemplateDetails.${index}.${column.columnAttributes.prop}`} rules={[...required]}>
        <el-input type="number" value={this.formData.freightTemplateDetails[index][column.columnAttributes.prop]} onInput={(val) => { this.formData.freightTemplateDetails[index][column.columnAttributes.prop] = val }}></el-input>
      </el-form-item>
    },
    openForm2() {
      getRegionTree().then((res) => {
        this.regionTree = res.data
        this.regionTree.forEach(value => {
          value.child.forEach(childValue => {
            delete childValue.child
          })
        })
        this.formDialog2 = true;
      })
    },
    formCancel2() {
      this.$refs.formRef2.$refs.inlineForm.clearValidate()
      this.$data.formData2 = this.$options.data().formData2
      this.formDialog2 = false
    },
    formConfirm2() {
      var tree = (function getEl(arr) {
        var data
        for (var item of arr) {
          if (item.$el.className === "el-tree") {
            return item
          } else if (item.$children && item.$children.length) {
            data = getEl(item.$children)
          }
        }
        if (data) {
          return data
        }
      })(this.$refs.formRef2.$children)
      tree.getCheckedNodes(true, false).forEach(value => {
        let province = value.parentName;
        let city = value.name;
        let exist = this.formData.freightTemplateDetails.find((obj) => {
          return obj.province === province && obj.city === city
        })
        if (!exist) {
          this.formData.freightTemplateDetails.push({
            province: province,
            city: city,
            firstLimit: 1,
            firstAmount: 1,
            continuousLimit: 1,
            continuousAmount: 1
          })
        }
      })
      this.formCancel2()
    },
    
  }
}
</script>

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