<script>
import orderApi from "@/api/business/purchase/purchase-order";
import { initColumns, initDicts, initRules, initParams } from "@/utils/init";
import { Columns, TabColumns } from "./column";

const NewColumns = initColumns(Columns);
const NewTabColumns = TabColumns.map((element) => ({
  ...element,
  tableColumns: initColumns(element.tableColumns),
}));

const SelectColumns = NewColumns.filter((column) => column.inputType === "Select");
NewTabColumns.forEach((column) => {
  SelectColumns.push(
    ...column.tableColumns.filter((cColumn) => cColumn.inputType === "Select")
  );
});
console.log(SelectColumns, 'SelectColumns');

export default {
  name: "AddPurchaseOrderDrawer",
  dicts: initDicts(SelectColumns),
  components: {},

  data() {
    return {
      visible: false,
      columns: NewColumns,
      rules: initRules(NewColumns),

      params: {
        ...initParams(NewColumns),
        puOrderItemList: [],
        puOrderExecuteList: [],
      },

      tabColumns: NewTabColumns,

      tabName: "puOrderItemList",
    };
  },
  computed: {},
  watch: {
    "params.puOrderItemList": {
      handler(nVal, oVal) {
        console.log(nVal, 'nVal', oVal, 'oVal');
        this.handleSynchronousMaterial("puOrderItemList", "puOrderExecuteList");
      },
      deep: true,
    },
    "params.puOrderExecuteList": {
      handler(nVal, oVal) {
        this.handleSynchronousMaterial("puOrderExecuteList", "puOrderItemList");
      },
      deep: true,
    },
    "params": {
      handler(nVal, oVal) {


        // 组织变化
        if (nVal.puOrg != oVal.puOrg) {
          console.log(nVal.puOrg, 'nVal.puOrg', oVal.puOrg, 'oVal.puOrg');
          for (const key in this.params) {
            if (Array.isArray(this.params[key])) {
              this.params[key] = [];
            }
            else if (key != 'puOrg' && key != 'puOrgName'
              && key != 'buyer' && key != 'buyerName'
              && key != 'puDept' && key != 'puDeptName'
              && key != 'status') {
              this.params[key] = '';
            }
            else { }
          }
        }

      },
      deep: true,
    }
  },
  methods: {
    beforeOpen() {
      const { deptName, deptId, name, nickName, orgName, orgId } = this.$store.state.user;
      this.params.puOrg = orgId;
      this.params.puOrgName = orgName;
      this.params.buyer = name;
      this.params.buyerName = nickName;
      this.params.puDept = deptId;
      this.params.puDeptName = deptName;
      this.params.status = '0';

    },
    setVisible(prop) {
      this.visible = prop;
    },
    // 增行
    addTableRow(prop) {
      for (const key in this.params) {
        if (Array.isArray(this.params[key])) {
          const arr = this.tabColumns.find(
            (element) => element.key === key
          ).tableColumns;

          let rowData = initParams(arr, "key", "value");

          "rowno" in rowData &&
            (rowData["rowno"] = this.params[key].length + 1);
          "rowNo" in rowData &&
            (rowData["rowNo"] = this.params[key].length + 1);

          // 是否完成询价，新增明细行需默认明细为false
          rowData['whetherCompleteInquiry'] = false;

          this.params[key].push(rowData);
        }
      }

      // const arr = this.tabColumns.find(
      //   (element) => element.key === this.tabName
      // ).tableColumns;
      // prop.push(initParams(arr, "key", "value"));
    },
    // 删行
    delTableRow(prop, index) {
      for (const key in this.params) {
        if (Array.isArray(this.params[key])) {
          this.params[key].splice(index, 1);
        }
      }
      // prop.splice(index, 1);
    },
    // 同步子表物料
    handleSynchronousMaterial(key1, key2) {
      let _this = this;
      // this.params[key1]-- -> this.params[key2]
      this.params[key1] && this.params[key1].forEach((item, index) => {

        for (const key in item) {

          if (key in _this.params[key2][index]) {

            if (key == 'material' || key == 'materialName' || key == 'materialCode') {
              _this.params[key2][index].material = item.material;
              _this.params[key2][index].materialName = item.materialName;
              _this.params[key2][index].materialCode = item.materialCode;
            } else {

              _this.params[key2][index][key] = item[key];
            }
          }
        }

      });
    },
    // 取消
    handleCancel() {
      this.setVisible(false);
      this.params = initParams(this.columns, "key", "value");
    },
    // 保存
    async handleSava() {
      // orderAddForm
      console.log(this.params, "params");
      // this.$refs['orderAddForm'].validate(async (valid) => {
      //   if (valid) {
      try {
        const { code, msg } = await orderApi.create(this.params);
        if (code === 200) {
          this.$notify.success({ title: msg });
          this.setVisible(false);
        } else {
          this.$notify.warning({ title: msg });
        }
      } catch (err) {
        //
      } finally {
        // this.setVisible(false);
      }
      // } else {
      //   console.log('error submit!!');
      //   return false;
      // }
      // });
    },
    // 保存并新增
    async handleSubmit() {
      // this.$refs["orderAddForm"].validate(async (valid) => {
      //   if (valid) {
      try {
        const createById = this.params.buyer;
        const createByName = this.params.buyerName;
        const updateById = this.$store.state.user.id;
        const updateByName = this.$store.state.user.name;
        const { code, msg } = await orderApi.create({
          createById,
          createByName,
          updateById,
          updateByName,
          ...this.params,
        });
        if (code === 200) {
          this.$notify.success({ title: msg });
          this.setVisible(false);
        } else {
          this.$notify.warning({ title: msg });
        }
      } catch (err) {
        this.$notify.error({ title: "error", message: err });
      } finally {
        // this.setVisible(false);
      }
      //   } else {
      //     console.log("error submit!!");
      //     return false;
      //   }
      // });
    },
    // 子表参照改变之后
    handleReferChange(val, source, type) {
      console.log(val, 'val');
      console.log(source, 'source');
      console.log(type, 'type');

      // 触发物料参照
      if (type == 'MATERIAL_PARAM' && source.qty && source.qty != '') {

        this.handleGetPrice();
      }
    },

    // 子表input
    handleInputChange(row, type) {
      console.log(type, 'type');
      // 物料数量变化----询价
      if (type == 'qty' && row.material) {
        this.handleGetPrice();
      }
    },
    // 询价 getPrice
    async handleGetPrice() {
      try {
        // let { puOrg, priceType, customer, assignSupplier, material, } = data;
        let { code, data } = await orderApi.getPrice({ ...this.params })
        if (code == 200) {
          this.params = data;
        }
      } catch (error) {

      } finally {

      }
    },

  },
  created() {
    console.log("ADD CREATED", this.params)
  },
  mounted() { },
  destroyed() { },
};
</script>
<template>
  <el-drawer direction="btt" size="100%" :with-header="false" :visible.sync="visible" @open="beforeOpen"
    @close="$emit('close')">
    <el-form size="mini" label-position="right" ref="orderAddForm" label-width="135px" :model="params" :rules="rules">
      <el-card :body-style="{
        padding: '20px',
        display: 'flex',
        'flex-wrap': 'wrap',
      }" style="margin: 10px">
        <div slot="header" style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          ">
          <h3>新增</h3>
          <div style="text-align: right">
            <el-button size="mini" @click="handleCancel">取消</el-button>
            <el-button size="mini" type="danger" @click="handleSava">保存</el-button>
            <el-button size="mini" type="info" @click="handleSubmit">
              保存并新增
            </el-button>
          </div>
        </div>
        <el-row>
          <el-col v-for="(column, index) in columns" :key="index" :span="column.span || 6">
            <el-form-item :prop="column.key" :label="column.title">

              <el-input v-if="column.inputType === 'Input'" v-model="params[column.key]" :placeholder="column.placeholder"
                :clearable="column.clearable" :disabled="column.disabled" style="width: 100%">
              </el-input>
              <dr-popover-select v-if="column.inputType === 'PopoverSelect'" v-model="params[column.key]"
                :value-key="column.valueKey" :source.sync="params" :title="column.title" :type="column.referName"
                :multiple="column.multiple" :placeholder="column.placeholder" :data-mapping="column.dataMapping"
                :query-params="column.queryParams(params)">
              </dr-popover-select>

              <el-input v-if="column.inputType === 'Textarea'" v-model="params[column.key]" type="textarea"
                :placeholder="column.placeholder" :clearable="column.clearable" :disabled="column.disabled"
                style="width: 100%">
              </el-input>

              <el-input-number v-if="column.inputType === 'InputNumber'" v-model="params[column.key]"
                :controls-position="column.config.controlsPosition" :placeholder="column.placeholder"
                :clearable="column.clearable" :disabled="column.disabled" style="width: 100%">
              </el-input-number>
              <el-select v-if="column.inputType === 'Select'" v-model="params[column.key]" :disabled="column.disabled"
                :clearable="column.clearable" :placeholder="column.placeholder" style="width: 100%">
                <el-option v-for="item in dict.type[column.referName]" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
              <el-select v-if="column.inputType === 'TagSelect'" v-model="params[column.key]" multiple clearable
                collapse-tags :placeholder="column.placeholder" :clearable="column.clearable" :disabled="column.disabled"
                style="width: 100%">
                <template #prefix>
                  <el-icon class="el-icon-view" style="cursor: pointer" @click.stop="$message.info(234)"></el-icon>
                </template>
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
              <el-date-picker v-if="column.inputType === 'DatePicker'" v-model="params[column.key]" :type="column.type"
                :placeholder="column.placeholder" :clearable="column.clearable" :disabled="column.disabled"
                :picker-options="column.pickerOptions" style="width: 100%">
              </el-date-picker>
              <el-checkbox v-if="column.inputType === 'Checkbox'" v-model="params[column.key]" true-label="Y"
                false-label="N">
              </el-checkbox>
              <el-upload v-if="column.inputType === 'Upload'" :file-list="params[column.key]" :disabled="column.disabled"
                drag action="https://jsonplaceholder.typicode.com/posts/" multiple>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <div class="el-upload__tip" slot="tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card :body-style="{
        padding: '20px',
        display: 'flex',
        'flex-wrap': 'wrap',
        position: 'relative',
      }" style="margin: 10px">
        <el-tabs v-model="tabName" style="width: 100%">
          <el-tab-pane v-for="(column, index) in tabColumns" :key="index" :label="column.title" :name="column.key">
            <el-table :data="params[column.key]" style="width: 100%">
              <el-table-column v-for="(cColumn, cIndex) in column.tableColumns" :key="cIndex" :prop="cColumn.key"
                :label="cColumn.title" :width="cColumn.width || 80">
                <template slot-scope="scope">
                  <el-tag v-if="cColumn.key === 'index'">
                    {{ scope.$index + 1 }}
                  </el-tag>
                  <el-input v-if="cColumn.inputType === 'Input'" v-model="scope.row[cColumn.key]"
                    :placeholder="cColumn.placeholder" :clearable="cColumn.clearable" :disabled="cColumn.disabled"
                    size="mini" style="width: 100%" @change="handleInputChange(scope.row, cColumn.key)">
                  </el-input>

                  <!--  -->
                  <dr-popover-select v-if="cColumn.inputType === 'PopoverSelect'" v-model="scope.row[cColumn.key]"
                    :source.sync="scope.row" :title="cColumn.title" :value-key="cColumn.valueKey"
                    :type="cColumn.referName" :multiple="cColumn.multiple" :placeholder="cColumn.placeholder"
                    :data-mapping="cColumn.dataMapping" :query-params="cColumn.queryParams(scope.row)"
                    @change="handleReferChange" size="mini">
                  </dr-popover-select>

                  <el-input-number v-if="cColumn.inputType === 'InputNumber'" v-model="scope.row[cColumn.key]"
                    :controls-position="cColumn.config.controlsPosition" :placeholder="cColumn.placeholder"
                    :clearable="cColumn.clearable" :disabled="cColumn.disabled" size="mini" style="width: 100%">
                  </el-input-number>

                  <el-select v-if="cColumn.inputType === 'Select'" v-model="scope.row[cColumn.key]" size="mini"
                    :disabled="cColumn.disabled" :clearable="cColumn.clearable" :placeholder="cColumn.placeholder"
                    style="width: 100%">
                    <el-option v-for="item in dict.type[cColumn.referName]" :key="item.value" :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>


                  <el-checkbox v-if="cColumn.inputType === 'Checkbox'" v-model="scope.row[cColumn.key]" true-label="Y"
                    false-label="N">
                  </el-checkbox>

                </template>
              </el-table-column>

              <el-table-column fixed="right" label="操作" width="80">
                <template slot-scope="scope">
                  <el-button @click.native.prevent="
                    delTableRow(params[tabName], scope.$index)
                    " type="text" size="small">
                    删行
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <el-row style="position: absolute; top: 20px; right: 20px">
          <el-button size="mini" @click="addTableRow(params[tabName])">增行</el-button>
        </el-row>
      </el-card>
    </el-form>
  </el-drawer>
</template>
