<template>
  <div class="app-list-content">
    <x-crud
      class="liu-crud-wrap"
      @load="onLoad"
    >
      <template #slot-tabs>
        <el-tabs class="liu-tabs" type="border-card" v-model="tabIndex" @tab-click="tabClick">
          <el-tab-pane v-for="(item, index) in tabsData" :key="index" :label="item.text" :name="item.key">
          </el-tab-pane>
        </el-tabs>
      </template>

			<template #table-column-cover="{ scope }">
				<cl-avatar
					shape="square"
					:size="32"
					:src="scope.row.cover"
					:style="{ margin: 'auto' }"
				></cl-avatar>
			</template>

      <template #table-column-goodsName="{scope}">
        <span>{{ scope.row.goodsName }}</span>
      </template>

      <template #table-column-unit="{scope}">
        <span>{{ scope.row.bigUnit }} / {{scope.row.smallUnit}}</span>
      </template>

      
      <template #table-column-inTurn="{scope}">
        <span v-if="!sort.status">{{ scope.row.inTurn }}</span>
        <el-input style="width:50%;" ref="sort-input" focus size="mini" v-else v-model="scope.row.inTurn" @blur="changeSort(scope.row, 'inTurn')" ></el-input>
      </template>

      <template #table-header-inTurn>
        <div class="set-sort">
          <span>排序</span>
          <el-button v-if="!sort.status" icon="el-icon-edit-outline" size="small" type="text" @click="showSort" class="show"></el-button>
          <el-button class="hide" v-else size="mini" @click="hideSort" type="primary">完成</el-button>
        </div>
      </template>

      <template #slot-modify="{ scope }">
				<el-button
					type="text"
					@click.native.stop="replaceBtnFn(scope.row.id)"
					>修改</el-button
				>
			</template>

      <template #table-column-addPrice="{scope}">
        <span v-if="!canAddPrice">{{ scope.row.addPrice }}</span>
        <el-input style="width:50%;" ref="add-price-input" focus size="mini" v-else v-model="scope.row.addPrice" @blur="changeSort(scope.row, 'addPrice')" ></el-input>
      </template>

      <template #table-header-addPrice>
        <div class="set-sort">
          <span>每扎加价</span>
          <el-button v-if="!canAddPrice" icon="el-icon-edit-outline" size="small" type="text" @click="showAddPrice" class="show"></el-button>
          <el-button class="hide" v-else size="mini" @click="hideSort" type="primary">完成</el-button>
        </div>
      </template>

      <template #table-header-cost>
        <div class="set-sort">
          <span>每扎成本价</span>
          <el-button v-if="!costPrice" icon="el-icon-edit-outline" size="small" type="text" @click="showCost" class="show"></el-button>
          <el-button class="hide" v-else size="mini" @click="hideSort" type="primary">完成</el-button>
        </div>
      </template>


      <template #table-column-cost="{scope}">
        <span v-if="!costPrice">{{ scope.row.cost }}</span>
        <el-input style="width:50%;" ref="sort-input" focus size="mini" v-else v-model="scope.row.cost" @blur="changeSort(scope.row, 'cost')" ></el-input>
      </template>
      <template #slot-add-goods-btn>
        <el-button type="primary" size="mini" @click="addFn()">添加</el-button>
      </template>

    </x-crud>
    <item-list-layer :show.sync="showItemModal" :classId.sync="classId" :className.sync="className" @confirm="selectItemFn" @cancel="showItemModal = false">
    </item-list-layer>
    <!-- 新增弹窗 -->
		<el-dialog
			title="修改花材"
			:visible.sync="addDialog"
			:close-on-click-modal="false"
			width="600px"
		>
      <div class="ad-modal-content">
        <el-form
					:model="replaceForm"
					:rules="replaceFormRules"
					ref="replaceForm"
					label-width="100px"
					class="demo-form"
				>
        <el-form-item label="名称" prop="name">
						<el-input
							v-model="replaceForm.name"
							placeholder="请输入名称"
							size="small"
						></el-input>
					</el-form-item>

          <el-form-item label="别名" prop="alias">
						<el-input
							v-model="replaceForm.alias"
							placeholder="请输入别名"
							size="small"
						></el-input>
					</el-form-item>

          <el-form-item label="图片" prop="cover">
						<cl-upload v-model="replaceForm.cover" :success="uploadSuccess"></cl-upload>
						<p style="font-size: 14px; color: #cccccc">建议上传图片比例 400X400</p>
					</el-form-item>

          <el-form-item label="分类" prop="classId">
						<el-select
							v-model="replaceForm.className"
							size="small"
							placeholder="请选择分类"
							@change="selClassFn"
						>
							<el-option
								v-for="(item, index) in itemClassList"
								:key="index"
								:value="item.name"
								>{{ item.name }}</el-option
							>
						</el-select>
					</el-form-item>

          <el-form-item label="库存预警" prop="stockWarning">
						<el-input
							v-model="replaceForm.stockWarning"
							placeholder="请输入数值"
							size="small"
						></el-input>
					</el-form-item>

          <el-form-item label="每扎重量" prop="weight">
						<el-input
							v-model="replaceForm.weight"
							placeholder="请输入斤数"
							size="small"
						></el-input>
					</el-form-item>

          <el-form-item label="每扎成本价" prop="cost">
						<el-input
							v-model="replaceForm.cost"
							placeholder="请输入成本价"
							size="small"
						></el-input>
					</el-form-item>

          <el-form-item label="每扎加价" prop="addPrice">
						<el-input
							v-model="replaceForm.addPrice"
							placeholder="请输入加价"
							size="small"
						></el-input>
					</el-form-item>

        </el-form>
      </div>
			<div slot="footer" class="dialog-footer">
				<el-button size="small" @click="resetForm">取 消</el-button>
				<el-button type="primary" size="small" @click="replaceConfirmFn">确认</el-button>
			</div>
		</el-dialog>
  </div>
</template>
<script>
import { mapGetters } from 'vuex';
import itemListLayer from '@/components/module/item-list-layer';
export default {
  name: 'item_list',
  components: {
    itemListLayer
  },
  data () {
    return {
      app: null,
      sortLink: '',
      operateData: {},
      tabIndex: '0',
      tabsData: [
        {
          text: '花材列表',
          key: '0'
        }
      ],
      selects: {},
      sort: {
        status: false
      },
      canAddPrice:false,
      costPrice: false,
      classId: 0,
      className:'',
      showItemModal: false,
      dataList: {
        form: {
          data: '',
          type: ''
        }
        
      },
      initData: [],
      addDialog: false,
      replaceForm: {
				name: '',
				alias: '',
				classId: '',
				className: '',
				cover: '',
        bigUnit: '',
				smallUnit: '',
				stockWarning:'',
				cost:'',
				addPrice:'',
				weight:'',
			},
      replaceFormRules: {
				name: {
					required: true,
					message: '名称不能为空',
				},
				cover: {
					required: true,
					message: '图片不能为空',
				},
				classId: {
					required: true,
					message: '请选择分类',
				},
				stockWarning: {
					required: true,
					message: '最低库存不能为空',
				},
				cost: {
					required: true,
					message: '运费不能为空',
				},
				addPrice: {
					required: true,
					message: '加价不能为空',
				},
				weight: {
					required: true,
					message: '重量不能为空',
				}
			},
      itemClassList: []
    };
  },
  computed: {
  },
  mounted() {
    
  },
  methods: {
    showCost() {
      this.initData = []
      this.costPrice = true
    },
    hideCost() {
      this.costPrice = false
    },
    selectItemFn (currentItem) {

      let item = currentItem.list
      let classId = currentItem.classId

      let param = []
      item.forEach(value => {
        let newObj = {}
        newObj.itemId = value.id
        newObj.classId = classId
        newObj.cost = value.cost
        newObj.addPrice = value.addPrice
        newObj.stockWarning = value.stockWarning
        param.push(newObj)
      })
      param = JSON.stringify(param)
      console.log(param)
      this.$service.item.batchAdd({ data: param }).then(res => {
        this.$message.success('操作成功！');
        this.showItemModal = false
        this.$router.go(0)
      }).catch(err => { console.log(err) })
    },
    getAllClass() {
			if (!this.$util.isEmpty(this.itemClassList)) {
				return this.itemClassList;
			}
			this.$service.itemClass.list().then((res) => {
        console.log(res)
				this.itemClassList = res.list;
			});
		},
    addFn () {
      this.showItemModal = true
    },
    selClassFn(val) {
			let index = this.itemClassList.findIndex((e) => e.name == val);
			this.replaceForm.classId = this.itemClassList[index].id;
		},
    resetForm() {
			this.goodsData = {};
			this.$refs['replaceForm'].resetFields();
			this.addDialog = false;
		},
    replaceConfirmFn() {
      this.$refs.replaceForm.validate((valid) => {
        if(valid) {
          this.$service.product.update(this.replaceForm).then(res => {
            console.log('res1111', res)
            this.$message.success('操作成功！');
            this.addDialog = false
            this.app.refresh()
          }).catch(err => {})
        }
      })
    },
    tabClick (tab, e) {
      this.app.refresh({ classId: this.classId });
    },
    onLoad ({ ctx, app }) {
      this.app = app
      if (this.$route.query.classId) {
        this.classId = Number(this.$route.query.classId);
        if (this.$route.query.className != '') {
          this.tabsData[0].text = this.$route.query.className;
          this.$forceUpdate();
        }
      }
      ctx.service(this.$service.product)
        .set('table', {
          columns: [
            {
              prop: 'id',
              label: 'ID',
              align: 'center'
            },
						{
							prop: 'cover',
							label: '图片',
							align: 'center',
							'min-width': 100,
						},
            {
              prop: 'name',
              label: '名称',
              align: 'center',
              'min-width': 180
            },
            {
              prop: 'className',
              label: '分类',
              align: 'center',
              'min-width': 100
            },
            {
              prop: 'stockWarning',
              label: '库存预警值',
              align: 'center',
              'min-width': 90
            },
            {
              prop: 'cost',
              label: '每扎成本价',
              align: 'center',
              'min-width': 120
            },
            {
              prop: 'addPrice',
              label: '每扎加价',
              align: 'center',
              'min-width': 120
            },
            {
              prop: 'weight',
              label: '重量',
              align: 'center',
              'min-width': 90
            },
            {
              prop: 'unit',
              label: '单位',
              align: 'center',
              'min-width': 100
            },
            {
              prop: 'ratio',
              label: '单位比',
              align: 'center',
              'min-width': 80
            },
            {
              prop: 'inTurn',
              label: '排序',
              align: 'center',
              minWidth: 120
            },
            {
              prop: 'addTime',
              label: '创建时间',
              align: 'center',
              minWidth: 180
            }
          ],
          op: {
            visible: true,
            props: {
              width: 200,
              align: 'center',
              fixed: 'right',
              label: '操作'
            },
            layout: ['slot-modify']
          }
        })
        .set('dict', {
          search: {
            keyWord: 'goodsName'
          },
        })
        .set('search', {
          key: {
            placeholder: '分类名称'
          }
        })
        .set('layout', [
          ['slot-tabs'],
          ['flex1', 'slot-add-goods-btn', 'refresh-btn'],
          ['data-table'],
          ['flex1', 'pagination']
        ])
        .done();
      app.refresh({ classId: this.classId});
      app.refresh({ showPage: 1 });
    },
    uploadSuccess() {
			console.log(this.$refs['replaceForm'].validateField('cover'))
		},
    refresh (params) {
      this.app.refresh(params);
    },
    showAddPrice(){
      this.initData = []
       this.canAddPrice = true
    },
    showSort (e) {
      this.initData = []
      this.sort.status = true;
    },

    hideSort (e) {
      this.dataList.form.data = JSON.stringify(this.initData)
      this.$service.product.productBatchUpdate(this.dataList.form).then(res => {
        console.log(res)
        this.$message.success('保存成功！');
      }).catch(err => {console.log(err)})
      this.sort.status = false;
      this.canAddPrice = false
      this.costPrice = false
    },
    replaceBtnFn(id) {
      this.addDialog = true
      this.getAllClass()
      this.$service.product.info({id}).then(res => {
        console.log(res)
        // this.replaceForm.name = res.name
				// this.replaceForm.alias = res.alias
				// this.replaceForm.classId = res.classId
				// this.replaceForm.className = res.classId
				// this.replaceForm.cover = res.cover
        // this.replaceForm.bigUnit = res.bigUnit
				// this.replaceForm.smallUnit = res.smallUnit
				// this.replaceForm.stockWarning = res.stockWarning
				// this.replaceForm.cost = res.cost
				// this.replaceForm.addPrice = res.addPrice
				// this.replaceForm.weight = res.weight
        let index = this.itemClassList.findIndex((e) => e.id == res.classId)
        this.replaceForm = res
        this.replaceForm.className = this.itemClassList[index].name
        console.log(this.replaceForm.cover)
        if(this.replaceForm.cover.indexOf('http') != -1 && this.replaceForm.cover.indexOf('/uploads') != -1) {
          let str = this.replaceForm.cover
          let str1 = str.substring(0, str.indexOf("/uploads"));
          this.replaceForm.cover = str.substring(str1.length+1, str.length);
        }
      })
    },
    changeSort (d, type) {
      this.dataList.form.type = type
      let obj = {
        id: d.id,
      }
      if(type == 'inTurn') {
        obj.inTurn = d.inTurn
      } else if(type == 'addPrice') {
        obj.addPrice = d.addPrice
      } else if(type == 'cost') {
        obj.cost  = d.cost 
      }
      this.initData.push(obj)
    }
  }
};
</script>

<style lang="scss" scoped>
.short-link {
  color: $mainColor;
  margin-left: 10px;
  cursor: pointer;
}
.set-sort {
  display: flex;
  align-items: center;
  justify-content: center;
  .el-button {
    margin-left: 10px;
  }
  .show {
    font-size: 16px;
  }
  .hide {
    padding: 2px 5px;
  }
}
</style>